language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def executemany(self, operation, seq_of_parameters):
"""Prepare a database operation (query or command) and then execute it against all parameter
sequences or mappings found in the sequence ``seq_of_parameters``.
Only the final result set is retained.
Return values are not defined.
"""
values_list = []
RE_INSERT_VALUES = re.compile(
r"\s*((?:INSERT|REPLACE)\s.+\sVALUES?\s*)" +
r"(\(\s*(?:%s|%\(.+\)s)\s*(?:,\s*(?:%s|%\(.+\)s)\s*)*\))" +
r"(\s*(?:ON DUPLICATE.*)?);?\s*\Z",
re.IGNORECASE | re.DOTALL)
m = RE_INSERT_VALUES.match(operation)
if m:
q_prefix = m.group(1) % ()
q_values = m.group(2).rstrip()
for parameters in seq_of_parameters[:-1]:
values_list.append(q_values % _escaper.escape_args(parameters))
query = '{} {};'.format(q_prefix, ','.join(values_list))
return self._db.raw(query)
for parameters in seq_of_parameters[:-1]:
self.execute(operation, parameters, is_response=False) |
java | public ClassFileBuilder prepare() throws SupportException {
if (mPrimaryKey == null) {
throw new IllegalStateException("Primary key not defined");
}
// Clear the cached result, if any
mStorableClass = null;
mClassFileGenerator = new StorableClassFileBuilder(
mClassNameProvider,
mLoader,
SyntheticStorableBuilder.class,
mEvolvable);
ClassFile cf = mClassFileGenerator.getClassFile();
for (SyntheticProperty prop : mPropertyList) {
definePropertyBeanMethods(cf, prop);
}
definePrimaryKey(cf);
defineAlternateKeys(cf);
defineIndexes(cf);
return mClassFileGenerator;
} |
java | public static PathMappingResult of(String path, @Nullable String query) {
return of(path, query, ImmutableMap.of());
} |
java | public void addCoords(Point3d[] atoms, BoundingBox bounds) {
this.iAtoms = atoms;
this.iAtomObjects = null;
if (bounds!=null) {
this.ibounds = bounds;
} else {
this.ibounds = new BoundingBox(iAtoms);
}
this.jAtoms = null;
this.jAtomObjects = null;
this.jbounds = null;
fillGrid();
} |
python | def on_print(self, node): # ('dest', 'values', 'nl')
"""Note: implements Python2 style print statement, not print()
function.
May need improvement....
"""
dest = self.run(node.dest) or self.writer
end = ''
if node.nl:
end = '\n'
out = [self.run(tnode) for tnode in node.values]
if out and len(self.error) == 0:
self._printer(*out, file=dest, end=end) |
python | def delete_database(client, db_name, username=None, password=None):
"""Delete Arangodb database
"""
(username, password) = get_user_creds(username, password)
sys_db = client.db("_system", username=username, password=password)
try:
return sys_db.delete_database(db_name)
except Exception:
log.warn("No arango database {db_name} to delete, does not exist") |
java | public int getColumnType(final int column) throws SQLException {
final Class<?> clazz = this.columnClasses.get(column-1);
if (clazz == null) {
return -1;
} // end of if
// ---
String cn = null;
if (clazz.isPrimitive()) {
if (clazz.equals(Boolean.TYPE)) {
cn = Boolean.class.getName();
} // end of if
if (clazz.equals(Character.TYPE)) {
cn = Character.class.getName();
} // end of if
if (clazz.equals(Byte.TYPE)) {
cn = Byte.class.getName();
} // end of if
if (clazz.equals(Short.TYPE)) {
cn = Short.class.getName();
} // end of if
if (clazz.equals(Integer.TYPE)) {
cn = Integer.class.getName();
} // end of if
if (clazz.equals(Long.TYPE)) {
cn = Long.class.getName();
} // end of if
if (clazz.equals(Float.TYPE)) {
cn = Float.class.getName();
} // end of if
if (clazz.equals(Double.TYPE)) {
cn = Double.class.getName();
} // end of if
} else {
cn = clazz.getName();
} // end of else
final String className = cn;
if (className == null) {
return -1;
} // end of if
// ---
for (final Map.Entry<Integer,String> kv : Defaults.
jdbcTypeMappings.entrySet()) {
if (kv.getValue().equals(className)) {
return kv.getKey();
} // end of if
} // end of for
return -1;
} |
java | public EClass getIPS() {
if (ipsEClass == null) {
ipsEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(282);
}
return ipsEClass;
} |
python | def _clone_reverses(self, old_reverses):
"""
Clones all the objects that were previously gathered.
"""
for ctype, reverses in old_reverses.items():
for parts in reverses.values():
sub_objs = parts[1]
field_name = parts[0]
attrs = {}
for sub_obj in sub_objs:
if ctype != 'm2m' and not attrs:
field = sub_obj._meta.get_field(field_name)
attrs = {
field.column: getattr(self, field.rel.field_name)
}
sub_obj._clone(**attrs)
if ctype == 'm2m':
setattr(self, field_name, sub_objs) |
java | public boolean hasVertex(float x, float y) {
if (points.length == 0) {
return false;
}
checkPoints();
for (int i=0;i<points.length;i+=2) {
if ((points[i] == x) && (points[i+1] == y)) {
return true;
}
}
return false;
} |
python | def insert_history_item(self, parent, history_item, description, dummy=False):
"""Enters a single history item into the tree store
:param Gtk.TreeItem parent: Parent tree item
:param HistoryItem history_item: History item to be inserted
:param str description: A description to be added to the entry
:param None dummy: Whether this is just a dummy entry (wrapper for concurrency items)
:return: Inserted tree item
:rtype: Gtk.TreeItem
"""
if not history_item.state_reference:
logger.error("This must never happen! Current history_item is {}".format(history_item))
return None
content = None
if global_gui_config.get_config_value("SHOW_PATH_NAMES_IN_EXECUTION_HISTORY", False):
content = (history_item.state_reference.name + " - " +
history_item.state_reference.get_path() + " - " +
description, None if dummy else history_item,
None if dummy else self.TOOL_TIP_TEXT)
else:
content = (history_item.state_reference.name + " - " +
description, None if dummy else history_item,
None if dummy else self.TOOL_TIP_TEXT)
tree_item = self.history_tree_store.insert_before(
parent, None, content)
return tree_item |
python | def _check_for_dictionary_key(self, logical_id, dictionary, keys):
"""
Checks a dictionary to make sure it has a specific key. If it does not, an
InvalidResourceException is thrown.
:param string logical_id: logical id of this resource
:param dict dictionary: the dictionary to check
:param list keys: list of keys that should exist in the dictionary
"""
for key in keys:
if key not in dictionary:
raise InvalidResourceException(logical_id, 'Resource is missing the required [{}] '
'property.'.format(key)) |
java | private static InputStream inputFor( File file)
{
try
{
return
file == null
? null
: new FileInputStream( file);
}
catch( Exception e)
{
throw new IllegalArgumentException( "Can't open file=" + file);
}
} |
python | def open_xmldoc(fobj, **kwargs):
"""Try and open an existing LIGO_LW-format file, or create a new Document
Parameters
----------
fobj : `str`, `file`
file path or open file object to read
**kwargs
other keyword arguments to pass to
:func:`~ligo.lw.utils.load_filename`, or
:func:`~ligo.lw.utils.load_fileobj` as appropriate
Returns
--------
xmldoc : :class:`~ligo.lw.ligolw.Document`
either the `Document` as parsed from an existing file, or a new, empty
`Document`
"""
from ligo.lw.ligolw import (Document, LIGOLWContentHandler)
from ligo.lw.lsctables import use_in
from ligo.lw.utils import (load_filename, load_fileobj)
use_in(kwargs.setdefault('contenthandler', LIGOLWContentHandler))
try: # try and load existing file
if isinstance(fobj, string_types):
return load_filename(fobj, **kwargs)
if isinstance(fobj, FILE_LIKE):
return load_fileobj(fobj, **kwargs)[0]
except (OSError, IOError): # or just create a new Document
return Document()
except LigolwElementError as exc:
if LIGO_LW_COMPAT_ERROR.search(str(exc)):
try:
return open_xmldoc(fobj, ilwdchar_compat=True, **kwargs)
except Exception: # for any reason, raise original
pass
raise |
java | private void visitMemberFunctionDefInObjectLit(Node n, Node parent) {
String name = n.getString();
Node nameNode = n.getFirstFirstChild();
Node stringKey = withType(IR.stringKey(name, n.getFirstChild().detach()), n.getJSType());
stringKey.setJSDocInfo(n.getJSDocInfo());
parent.replaceChild(n, stringKey);
stringKey.useSourceInfoFrom(nameNode);
compiler.reportChangeToEnclosingScope(stringKey);
} |
python | def createComment(self, repo_user, repo_name, pull_number,
body, commit_id, path, position):
"""
POST /repos/:owner/:repo/pulls/:number/comments
:param pull_number: The pull request's ID.
:param body: The text of the comment.
:param commit_id: The SHA of the commit to comment on.
:param path: The relative path of the file to comment on.
:param position: The line index in the diff to comment on.
"""
return self.api.makeRequest(
["repos", repo_user, repo_name,
"pulls", str(pull_number), "comments"],
method="POST",
data=dict(body=body,
commit_id=commit_id,
path=path,
position=position)) |
java | public static <T extends Comparable<T>> RelationalOperator<T> equalTo(T value) {
return new EqualToOperator<>(value);
} |
java | public void setOptions(String[] options) throws Exception {
String tmpStr;
ClassOption option;
tmpStr = Utils.getOption('B', options);
option = (ClassOption) m_Generator.copy();
if (tmpStr.length() == 0)
option.setCurrentObject(new LEDGenerator());
else
option.setCurrentObject(MOAUtils.fromCommandLine(m_Generator, tmpStr));
setGenerator(option);
super.setOptions(options);
} |
java | @Override
public CommerceAccountUserRel fetchByCommerceAccountId_First(
long commerceAccountId,
OrderByComparator<CommerceAccountUserRel> orderByComparator) {
List<CommerceAccountUserRel> list = findByCommerceAccountId(commerceAccountId,
0, 1, orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
} |
java | protected BooleanQuery.Builder appendDateCreatedFilter(BooleanQuery.Builder filter, long startTime, long endTime) {
// create special optimized sub-filter for the date last modified search
Query dateFilter = createDateRangeFilter(CmsSearchField.FIELD_DATE_CREATED_LOOKUP, startTime, endTime);
if (dateFilter != null) {
// extend main filter with the created date filter
filter.add(new BooleanClause(dateFilter, BooleanClause.Occur.MUST));
}
return filter;
} |
java | public static version_matrix_status[] get(nitro_service client) throws Exception
{
version_matrix_status resource = new version_matrix_status();
resource.validate("get");
return (version_matrix_status[]) resource.get_resources(client);
} |
python | def binary2str(b, proto_id, proto_fmt_type):
"""
Transfer binary to string
:param b: binary content to be transformed to string
:return: string
"""
if proto_fmt_type == ProtoFMT.Json:
return b.decode('utf-8')
elif proto_fmt_type == ProtoFMT.Protobuf:
rsp = pb_map[proto_id]
if IS_PY2:
rsp.ParseFromString(str(b))
else:
rsp.ParseFromString(b)
return MessageToJson(rsp)
else:
raise Exception("binary2str: unknown proto format.") |
python | def _check_paramiko_handlers(logger=None):
"""
Add a console handler for paramiko.transport's logger if not present
"""
paramiko_logger = logging.getLogger('paramiko.transport')
if not paramiko_logger.handlers:
if logger:
paramiko_logger.handlers = logger.handlers
else:
console_handler = logging.StreamHandler()
console_handler.setFormatter(
logging.Formatter('%(asctime)s | %(levelname)-8s| PARAMIKO: '
'%(lineno)03d@%(module)-10s| %(message)s')
)
paramiko_logger.addHandler(console_handler) |
python | def remove(self, member):
"""Remove element from set; it must be a member.
:raises KeyError: if the element is not a member.
"""
if not self.client.srem(self.name, member):
raise KeyError(member) |
java | public synchronized void stopThrow() throws JMException {
if (connector != null) {
try {
connector.stop();
} catch (IOException e) {
throw createJmException("Could not stop our Jmx connector server", e);
} finally {
connector = null;
}
}
if (rmiRegistry != null) {
try {
UnicastRemoteObject.unexportObject(rmiRegistry, true);
} catch (NoSuchObjectException e) {
throw createJmException("Could not unexport our RMI registry", e);
} finally {
rmiRegistry = null;
}
}
if (serverHostNamePropertySet) {
System.clearProperty(RMI_SERVER_HOST_NAME_PROPERTY);
serverHostNamePropertySet = false;
}
} |
java | Coordinator getCoordinator()
{
coordinator = new Coordinator();
try
{
for (String pu : clientMap.keySet())
{
PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,
pu);
String txResource = puMetadata.getProperty(PersistenceProperties.KUNDERA_TRANSACTION_RESOURCE);
if (txResource != null)
{
TransactionResource resource = (TransactionResource) Class.forName(txResource).newInstance();
coordinator.addResource(resource, pu);
Client client = clientMap.get(pu);
if (!(client instanceof TransactionBinder))
{
throw new KunderaTransactionException(
"Client : "
+ client.getClass()
+ " must implement TransactionBinder interface, if {kundera.transaction.resource.class} property provided!");
}
else
{
((TransactionBinder) client).bind(resource);
}
}
else
{
coordinator.addResource(new DefaultTransactionResource(clientMap.get(pu)), pu);
}
}
}
catch (Exception e)
{
log.error("Error while initializing Transaction Resource:", e);
throw new KunderaTransactionException(e);
}
return coordinator;
} |
python | def MakeRequestAndDecodeJSON(self, url, method, **kwargs):
"""Make a HTTP request and decode the results as JSON.
Args:
url (str): URL to make a request to.
method (str): HTTP method to used to make the request. GET and POST are
supported.
kwargs: parameters to the requests .get() or post() methods, depending
on the value of the method parameter.
Returns:
dict[str, object]: body of the HTTP response, decoded from JSON.
Raises:
ConnectionError: If it is not possible to connect to the given URL, or it
the request returns a HTTP error.
ValueError: If an invalid HTTP method is specified.
"""
method_upper = method.upper()
if method_upper not in ('GET', 'POST'):
raise ValueError('Method {0:s} is not supported')
if url.lower().startswith('https'):
self._CheckPythonVersionAndDisableWarnings()
try:
if method_upper == 'GET':
response = requests.get(url, **kwargs)
elif method_upper == 'POST':
response = requests.post(url, **kwargs)
response.raise_for_status()
except requests.ConnectionError as exception:
error_string = 'Unable to connect to {0:s} with error: {1!s}'.format(
url, exception)
raise errors.ConnectionError(error_string)
except requests.HTTPError as exception:
error_string = '{0:s} returned a HTTP error: {1!s}'.format(
url, exception)
raise errors.ConnectionError(error_string)
return response.json() |
java | public int update(String sql) {
String msId = msUtils.update(sql);
return sqlSession.update(msId);
} |
python | def submit_by_selector(self, selector):
"""Submit the form matching the CSS selector."""
elem = find_element_by_jquery(world.browser, selector)
elem.submit() |
python | def Any(*validators):
"""
Combines all the given validator callables into one, running the given
value through them in sequence until a valid result is given.
"""
@wraps(Any)
def built(value):
error = None
for validator in validators:
try:
return validator(value)
except Error as e:
error = e
raise error
return built |
python | def visitShapeOrRef(self, ctx: ShExDocParser.ShapeOrRefContext):
""" shapeOrRef: shapeDefinition | shapeRef """
if ctx.shapeDefinition():
from pyshexc.parser_impl.shex_shape_definition_parser import ShexShapeDefinitionParser
shdef_parser = ShexShapeDefinitionParser(self.context, self.label)
shdef_parser.visitChildren(ctx)
self.expr = shdef_parser.shape
else:
self.expr = self.context.shapeRef_to_iriref(ctx.shapeRef()) |
java | public static int findAvailableTcpPort(int minPortRange, int maxPortRange) {
ArgumentUtils.check(() -> minPortRange > MIN_PORT_RANGE)
.orElseFail("Port minimum value must be greater than " + MIN_PORT_RANGE);
ArgumentUtils.check(() -> maxPortRange >= minPortRange)
.orElseFail("Max port range must be greater than minimum port range");
ArgumentUtils.check(() -> maxPortRange <= MAX_PORT_RANGE)
.orElseFail("Port maximum value must be less than " + MAX_PORT_RANGE);
int currentPort = nextPort(minPortRange, maxPortRange);
while (!isTcpPortAvailable(currentPort)) {
currentPort = nextPort(minPortRange, maxPortRange);
}
return currentPort;
} |
python | def wait_socket(host, port, timeout=120):
'''
Wait for socket opened on remote side. Return False after timeout
'''
return wait_result(lambda: check_socket(host, port), True, timeout) |
java | public static Object newInstance(Class target, Class[] types, Object[] args, boolean makeAccessible) throws InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException,
NoSuchMethodException,
SecurityException
{
Constructor con;
if (makeAccessible)
{
con = target.getDeclaredConstructor(types);
if (makeAccessible && !con.isAccessible())
{
con.setAccessible(true);
}
}
else
{
con = target.getConstructor(types);
}
return con.newInstance(args);
} |
python | def from_xyz_string(xyz_string):
"""
Args:
xyz_string: string of the form 'x, y, z', '-x, -y, z',
'-2y+1/2, 3x+1/2, z-y+1/2', etc.
Returns:
SymmOp
"""
rot_matrix = np.zeros((3, 3))
trans = np.zeros(3)
toks = xyz_string.strip().replace(" ", "").lower().split(",")
re_rot = re.compile(r"([+-]?)([\d\.]*)/?([\d\.]*)([x-z])")
re_trans = re.compile(r"([+-]?)([\d\.]+)/?([\d\.]*)(?![x-z])")
for i, tok in enumerate(toks):
# build the rotation matrix
for m in re_rot.finditer(tok):
factor = -1 if m.group(1) == "-" else 1
if m.group(2) != "":
factor *= float(m.group(2)) / float(m.group(3)) \
if m.group(3) != "" else float(m.group(2))
j = ord(m.group(4)) - 120
rot_matrix[i, j] = factor
# build the translation vector
for m in re_trans.finditer(tok):
factor = -1 if m.group(1) == "-" else 1
num = float(m.group(2)) / float(m.group(3)) \
if m.group(3) != "" else float(m.group(2))
trans[i] = num * factor
return SymmOp.from_rotation_and_translation(rot_matrix, trans) |
java | private byte[] getKeyFromKDF(byte[] ki, String label, byte[] context, int l)
throws IOException {
int bytesCount = l >>> 3;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] counter = new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x01 };
baos.write(counter);
baos.write(label.getBytes());
baos.write((byte) 0x00);
baos.write(context);
byte[] len = new byte[4];
for (int i = 3; i >= 0; i--) {
len[i] = (byte) (l & 0xFF);
l >>>= 8;
}
baos.write(len);
byte[] array = baos.toByteArray();
baos.close();
byte[] hmac = createSHAHMAC(array, 0, array.length, ki);
// Create a new result array of aL bits
byte[] result = new byte[bytesCount];
// Copy aL leftmost bits of the HMAC
System.arraycopy(hmac, 0, result, 0, bytesCount);
return result;
} |
python | def ip_acl_ip_access_list_standard_hide_ip_acl_std_seq_action(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ip_acl = ET.SubElement(config, "ip-acl", xmlns="urn:brocade.com:mgmt:brocade-ip-access-list")
ip = ET.SubElement(ip_acl, "ip")
access_list = ET.SubElement(ip, "access-list")
standard = ET.SubElement(access_list, "standard")
name_key = ET.SubElement(standard, "name")
name_key.text = kwargs.pop('name')
hide_ip_acl_std = ET.SubElement(standard, "hide-ip-acl-std")
seq = ET.SubElement(hide_ip_acl_std, "seq")
seq_id_key = ET.SubElement(seq, "seq-id")
seq_id_key.text = kwargs.pop('seq_id')
action = ET.SubElement(seq, "action")
action.text = kwargs.pop('action')
callback = kwargs.pop('callback', self._callback)
return callback(config) |
java | @SuppressWarnings("unchecked")
public static <M extends PMessage<M,F>, F extends PField, B extends PMessageBuilder<M,F>>
List<B> mutateAll(Collection<M> messages) {
if (messages == null) {
return null;
}
return (List<B>) messages.stream()
.map(PMessage::mutate)
.collect(Collectors.toList());
} |
java | protected void deleteTypeVertex(AtlasVertex instanceVertex, DataTypes.TypeCategory typeCategory, boolean force) throws AtlasException {
switch (typeCategory) {
case STRUCT:
case TRAIT:
deleteTypeVertex(instanceVertex, force);
break;
case CLASS:
deleteEntities(Collections.singletonList(instanceVertex));
break;
default:
throw new IllegalStateException("Type category " + typeCategory + " not handled");
}
} |
java | public VirtualMachineCaptureResultInner beginCapture(String resourceGroupName, String vmName, VirtualMachineCaptureParameters parameters) {
return beginCaptureWithServiceResponseAsync(resourceGroupName, vmName, parameters).toBlocking().single().body();
} |
java | public void registerControlAdapterAsMBean()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "registerControlAdapterAsMBean");
if (isRegistered() ) {
// Don't register a 2nd time.
} else {
super.registerControlAdapterAsMBean();
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "registerControlAdapterAsMBean");
} |
python | def validate(self, data):
"""
Validated data using defined regex.
:param data: data to be validated
:return: return validated data.
"""
e = self._error
try:
if self._pattern.search(data):
return data
else:
raise SchemaError("%r does not match %r" % (self, data), e)
except TypeError:
raise SchemaError("%r is not string nor buffer" % data, e) |
python | def _read_datasets(self, dataset_nodes, **kwargs):
"""Read the given datasets from file."""
# Sort requested datasets by reader
reader_datasets = {}
for node in dataset_nodes:
ds_id = node.name
# if we already have this node loaded or the node was assigned
# by the user (node data is None) then don't try to load from a
# reader
if ds_id in self.datasets or not isinstance(node.data, dict):
continue
reader_name = node.data.get('reader_name')
if reader_name is None:
# This shouldn't be possible
raise RuntimeError("Dependency tree has a corrupt node.")
reader_datasets.setdefault(reader_name, set()).add(ds_id)
# load all datasets for one reader at a time
loaded_datasets = DatasetDict()
for reader_name, ds_ids in reader_datasets.items():
reader_instance = self.readers[reader_name]
new_datasets = reader_instance.load(ds_ids, **kwargs)
loaded_datasets.update(new_datasets)
self.datasets.update(loaded_datasets)
return loaded_datasets |
python | def value(self):
""" Return current value for the metric """
if self.buffer:
return np.quantile(self.buffer, self.quantile)
else:
return 0.0 |
python | def _lmder1_linear_r1zcr(n, m, factor, target_fnorm1, target_fnorm2, target_params):
"""A rank-1 linear function with zero columns and rows (lmder test #3)"""
def func(params, vec):
s = 0
for j in range(1, n - 1):
s += (j + 1) * params[j]
for i in range(m):
vec[i] = i * s - 1
vec[m-1] = -1
def jac(params, jac):
jac.fill(0)
for i in range(1, n - 1):
for j in range(1, m - 1):
jac[i,j] = j * (i + 1)
guess = np.ones(n) * factor
#_lmder1_test(m, func, jac, guess)
_lmder1_driver(m, func, jac, guess,
target_fnorm1, target_fnorm2, None) |
java | @Override
public ICmdLineArg<E> setRequiredValue(final boolean bool) throws ParseException
{
if (!bool)
throw new ParseException("requiredValue must be true for type: " + getClass().getName(), -1);
requiredValue = bool;
return this;
} |
java | void compileClass(Source javaSource, Source javaClass,
String sourcePath, boolean isMake)
throws ClassNotFoundException
{
try {
JavaCompilerUtil compiler = JavaCompilerUtil.create(getClassLoader());
compiler.setClassDir(_classDir);
compiler.setSourceDir(_sourceDir);
if (_encoding != null)
compiler.setEncoding(_encoding);
compiler.setArgs(_args);
compiler.setCompileParent(! isMake);
compiler.setSourceExtension(_sourceExt);
if (_compiler != null)
compiler.setCompiler(_compiler);
//LineMap lineMap = new LineMap(javaFile.getNativePath());
// The context path is obvious from the browser url
//lineMap.add(name.replace('.', '/') + _sourceExt, 1, 1);
// Force this into a relative path so different compilers will work
String prefix = _sourceDir.getPath();
String full = javaSource.getPath();
String source;
if (full.startsWith(prefix)) {
source = full.substring(prefix.length());
if (source.startsWith("/"))
source = source.substring(1);
}
else
source = javaSource.getPath();
/*
if (javaSource.canRead() && javaClass.exists())
javaClass.remove();
*/
compiler.compileIfModified(source, null);
} catch (Exception e) {
//getClassLoader().addDependency(new Depend(javaSource));
log.log(Level.FINEST, e.toString(), e);
// Compile errors are wrapped in a special ClassNotFound class
// so the server can give a nice error message
throw new CompileClassNotFound(e);
}
} |
python | def from_io_control(fobj):
"""
Call TIOCGWINSZ (Terminal I/O Control to Get the WINdow SiZe)
where ``fobj`` is a file object (e.g. ``sys.stdout``),
returning the terminal width assigned to that file.
See the ``ioctl``, ``ioctl_list`` and tty_ioctl`` man pages
for more information.
"""
import fcntl, termios, array
winsize = array.array("H", [0] * 4) # row, col, xpixel, ypixel
if not fcntl.ioctl(fobj.fileno(), termios.TIOCGWINSZ, winsize, True):
return winsize[1] |
java | @Override
public EEnum getIfcRampTypeEnum() {
if (ifcRampTypeEnumEEnum == null) {
ifcRampTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
.get(1047);
}
return ifcRampTypeEnumEEnum;
} |
java | public void fsync(long sequence, K key, Result<Boolean> result)
{
scheduleFsync(sequence, key, result);
flush();
} |
python | def retry(exception_cls, max_tries=10, sleep=0.05):
"""Decorator for retrying a function if it throws an exception.
:param exception_cls: an exception type or a parenthesized tuple of exception types
:param max_tries: maximum number of times this function can be executed. Must be at least 1.
:param sleep: number of seconds to sleep between function retries
"""
assert max_tries > 0
def with_max_retries_call(delegate):
for i in xrange(0, max_tries):
try:
return delegate()
except exception_cls:
if i + 1 == max_tries:
raise
time.sleep(sleep)
def outer(fn):
is_generator = inspect.isgeneratorfunction(fn)
@functools.wraps(fn)
def retry_fun(*args, **kwargs):
return with_max_retries_call(lambda: fn(*args, **kwargs))
@functools.wraps(fn)
def retry_generator_fun(*args, **kwargs):
def get_first_item():
results = fn(*args, **kwargs)
for first_result in results:
return [first_result], results
return [], results
cache, generator = with_max_retries_call(get_first_item)
for item in cache:
yield item
for item in generator:
yield item
if not is_generator:
# so that qcore.inspection.get_original_fn can retrieve the original function
retry_fun.fn = fn
# Necessary for pickling of Cythonized functions to work. Cython's __reduce__
# method always returns the original name of the function.
retry_fun.__reduce__ = lambda: fn.__name__
return retry_fun
else:
retry_generator_fun.fn = fn
retry_generator_fun.__reduce__ = lambda: fn.__name__
return retry_generator_fun
return outer |
python | def by_date(self, chamber, date):
"Return votes cast in a chamber on a single day"
date = parse_date(date)
return self.by_range(chamber, date, date) |
java | public void delete(String resourceGroupName, String managedClusterName, String agentPoolName) {
deleteWithServiceResponseAsync(resourceGroupName, managedClusterName, agentPoolName).toBlocking().last().body();
} |
java | @Override
public Predicate or(Expression<Boolean> arg0, Expression<Boolean> arg1)
{
// TODO Auto-generated method stub
if (arg0 != null && arg1 != null)
{
if (arg0.getClass().isAssignableFrom(ComparisonPredicate.class) && arg1.getClass().isAssignableFrom(ComparisonPredicate.class))
{
return new DisjunctionPredicate((Predicate)arg0, (Predicate)arg1);
}
}
return null;
} |
java | private boolean checkForMapKey(TabularType pType) {
List<String> indexNames = pType.getIndexNames();
return
// Single index named "key"
indexNames.size() == 1 && indexNames.contains(TD_KEY_KEY) &&
// Only convert to map for simple types for all others use normal conversion. See #105 for details.
pType.getRowType().getType(TD_KEY_KEY) instanceof SimpleType;
} |
java | protected void initHtmlImportObject() {
Object o;
String uri = getJsp().getRequestContext().getUri();
if ((uri == null) || uri.endsWith(IMPORT_STANDARD_PATH)) {
m_dialogMode = MODE_STANDARD;
} else if (uri.endsWith(IMPORT_DEFAULT_PATH)) {
m_dialogMode = MODE_DEFAULT;
} else {
m_dialogMode = MODE_ADVANCED;
}
if (CmsStringUtil.isEmpty(getParamAction())) {
o = new CmsHtmlImport(getJsp().getCmsObject());
} else {
// this is not the initial call, get the job object from session
o = getDialogObject();
}
if (!(o instanceof CmsHtmlImport)) {
// create a new HTML import handler object
m_htmlimport = new CmsHtmlImport(getJsp().getCmsObject());
} else {
// reuse HTML import handler object stored in session
m_htmlimport = (CmsHtmlImport)o;
// this is needed, because the user can switch between the sites, now get the current
m_htmlimport.setCmsObject(getJsp().getCmsObject());
}
// gets the data from the configuration file
fillHtmlImport();
} |
java | public static CommerceAvailabilityEstimate fetchByGroupId_First(
long groupId,
OrderByComparator<CommerceAvailabilityEstimate> orderByComparator) {
return getPersistence().fetchByGroupId_First(groupId, orderByComparator);
} |
python | def nice(self, work_spec_name, nice):
'''Change the priority of an existing work spec.'''
with self.registry.lock(identifier=self.worker_id) as session:
session.update(NICE_LEVELS, dict(work_spec_name=nice)) |
java | public static DefaultTableModel leftShift(DefaultTableModel self, Object row) {
if (row == null) {
// adds an empty row
self.addRow((Object[]) null);
return self;
}
self.addRow(buildRowData(self, row));
return self;
} |
java | public static <T extends Serializable> Flowable<T> read(final File file, final int bufferSize) {
Callable<ObjectInputStream> resourceFactory = new Callable<ObjectInputStream>() {
@Override
public ObjectInputStream call() throws IOException {
return new ObjectInputStream(new BufferedInputStream(new FileInputStream(file), bufferSize));
}
};
@SuppressWarnings("unchecked")
Function<ObjectInputStream, Flowable<T>> flowableFactory = (Function<ObjectInputStream, Flowable<T>>) (Function<?, ?>) ObjectInputStreamFlowableFactoryHolder.INSTANCE;
Consumer<ObjectInputStream> disposeAction = Consumers.close();
return Flowable.using(resourceFactory, flowableFactory, disposeAction, true);
} |
java | public static MenuItem newMenuItem(final Class<? extends Page> pageClass,
final String resourceModelKey, final Component component, final PageParameters parameters)
{
final BookmarkablePageLink<String> bookmarkablePageLink = new BookmarkablePageLink<>(
MenuPanel.LINK_ID, pageClass, parameters);
final IModel<String> labelModel = ResourceModelFactory.newResourceModel(resourceModelKey,
component);
final MenuItem menuItem = new MenuItem(bookmarkablePageLink, labelModel);
return menuItem;
} |
python | def createPopulationFile(inputFiles, labels, outputFileName):
"""Creates a population file.
:param inputFiles: the list of input files.
:param labels: the list of labels (corresponding to the input files).
:param outputFileName: the name of the output file.
:type inputFiles: list
:type labels: list
:type outputFileName: str
The ``inputFiles`` is in reality a list of ``tfam`` files composed of
samples. For each of those ``tfam`` files, there is a label associated with
it (representing the name of the population).
The output file consists of one row per sample, with the following three
columns: the family ID, the individual ID and the population of each
sample.
"""
outputFile = None
try:
outputFile = open(outputFileName, 'w')
except IOError:
msg = "%(outputFileName)s: can't write file"
raise ProgramError(msg)
for i in xrange(len(inputFiles)):
# For each file
fileName = inputFiles[i]
label = labels[i]
try:
with open(fileName, 'r') as inputFile:
for line in inputFile:
row = line.rstrip("\r\n").split(" ")
# Getting the informations
famID = row[0]
indID = row[1]
# Printing to file
print >>outputFile, "\t".join([famID, indID, label])
except IOError:
msg = "%(fileName)s: no such file" % locals()
raise ProgramError(msg)
# Closing the output file
outputFile.close() |
python | def findPolymorphisms(self, strSeq, strict = False):
"""
Compares strSeq with self.sequence.
If not 'strict', this function ignores the cases of matching heterozygocity (ex: for a given position i, strSeq[i] = A and self.sequence[i] = 'A/G'). If 'strict' it returns all positions where strSeq differs self,sequence
"""
arr = self.encode(strSeq)[0]
res = []
if not strict :
for i in range(len(arr)+len(self)) :
if i >= len(arr) or i > len(self) :
break
if arr[i] & self[i] == 0:
res.append(i)
else :
for i in range(len(arr)+len(self)) :
if i >= len(arr) or i > len(self) :
break
if arr[i] != self[i] :
res.append(i)
return res |
python | def get_functions(cls, entry):
"""
get `models.Function` objects from XML node entry
:param entry: XML node entry
:return: list of :class:`pyuniprot.manager.models.Function` objects
"""
comments = []
query = "./comment[@type='function']"
for comment in entry.iterfind(query):
text = comment.find('./text').text
comments.append(models.Function(text=text))
return comments |
python | def __check_msg_for_headers(self, msg, ** email_headers):
"""
Checks an Email.Message object for the headers in email_headers.
Following are acceptable header names: ['Delivered-To',
'Received', 'Return-Path', 'Received-SPF',
'Authentication-Results', 'DKIM-Signature',
'DomainKey-Signature', 'From', 'To', 'Message-ID',
'Subject', 'MIME-Version', 'Content-Type', 'Date',
'X-Sendgrid-EID', 'Sender'].
@Params
msg - the Email.message object to check
email_headers - list of headers to check against
@Returns
Boolean whether all the headers were found
"""
all_headers_found = False
email_headers['Delivered-To'] = email_headers['To']
email_headers.pop('To')
all_headers_found = all(k in msg.keys() for k in email_headers)
return all_headers_found |
java | public static PrimitiveParameter binarySearch(
List<PrimitiveParameter> params, long timestamp) {
/*
* The conditions for using index versus iterator are grabbed from the
* JDK source code.
*/
if (params.size() < 5000 || params instanceof RandomAccess) {
return indexedBinarySearch(params, timestamp);
} else {
return iteratorBinarySearch(params, timestamp);
}
} |
python | def single_qubit_matrix_to_phased_x_z(
mat: np.ndarray,
atol: float = 0
) -> List[ops.SingleQubitGate]:
"""Implements a single-qubit operation with a PhasedX and Z gate.
If one of the gates isn't needed, it will be omitted.
Args:
mat: The 2x2 unitary matrix of the operation to implement.
atol: A limit on the amount of error introduced by the
construction.
Returns:
A list of gates that, when applied in order, perform the desired
operation.
"""
xy_turn, xy_phase_turn, total_z_turn = (
_deconstruct_single_qubit_matrix_into_gate_turns(mat))
# Build the intended operation out of non-negligible XY and Z rotations.
result = [
ops.PhasedXPowGate(exponent=2 * xy_turn,
phase_exponent=2 * xy_phase_turn),
ops.Z**(2 * total_z_turn)
]
result = [
g for g in result
if protocols.trace_distance_bound(g) > atol
]
# Special case: XY half-turns can absorb Z rotations.
if len(result) == 2 and abs(xy_turn) >= 0.5 - atol:
return [
ops.PhasedXPowGate(phase_exponent=2 * xy_phase_turn + total_z_turn)
]
return result |
java | private String jsonStringOf(Policy policy) throws JsonGenerationException,
IOException {
generator.writeStartObject();
writeJsonKeyValue(JsonDocumentFields.VERSION, policy.getVersion());
if (isNotNull(policy.getId()))
writeJsonKeyValue(JsonDocumentFields.POLICY_ID, policy.getId());
writeJsonArrayStart(JsonDocumentFields.STATEMENT);
for (Statement statement : policy.getStatements()) {
generator.writeStartObject();
if (isNotNull(statement.getId())) {
writeJsonKeyValue(JsonDocumentFields.STATEMENT_ID, statement.getId());
}
writeJsonKeyValue(JsonDocumentFields.STATEMENT_EFFECT, statement
.getEffect().toString());
List<Principal> principals = statement.getPrincipals();
if (isNotNull(principals) && !principals.isEmpty())
writePrincipals(principals);
List<Action> actions = statement.getActions();
if (isNotNull(actions) && !actions.isEmpty())
writeActions(actions);
List<Resource> resources = statement.getResources();
if (isNotNull(resources) && !resources.isEmpty())
writeResources(resources);
List<Condition> conditions = statement.getConditions();
if (isNotNull(conditions) && !conditions.isEmpty())
writeConditions(conditions);
generator.writeEndObject();
}
writeJsonArrayEnd();
generator.writeEndObject();
generator.flush();
return writer.toString();
} |
python | def write(obj, data=None, **kwargs):
"""Write a value in to loader source
:param obj: settings object
:param data: vars to be stored
:param kwargs: vars to be stored
:return:
"""
if obj.VAULT_ENABLED_FOR_DYNACONF is False:
raise RuntimeError(
"Vault is not configured \n"
"export VAULT_ENABLED_FOR_DYNACONF=true\n"
"and configure the VAULT_FOR_DYNACONF_* variables"
)
data = data or {}
data.update(kwargs)
if not data:
raise AttributeError("Data must be provided")
client = get_client(obj)
path = "/".join(
[obj.VAULT_PATH_FOR_DYNACONF, obj.current_env.lower()]
).replace("//", "/")
client.write(path, data=data)
load(obj) |
java | private boolean doesReaderOwnTooManySegments(ReaderGroupState state) {
Map<String, Double> sizesOfAssignemnts = state.getRelativeSizes();
Set<Segment> assignedSegments = state.getSegments(readerId);
if (sizesOfAssignemnts.isEmpty() || assignedSegments == null || assignedSegments.size() <= 1) {
return false;
}
double min = sizesOfAssignemnts.values().stream().min(Double::compareTo).get();
return sizesOfAssignemnts.get(readerId) > min + Math.max(1, state.getNumberOfUnassignedSegments());
} |
python | def _parse_phone_and_hash(self, phone, phone_hash):
"""
Helper method to both parse and validate phone and its hash.
"""
phone = utils.parse_phone(phone) or self._phone
if not phone:
raise ValueError(
'Please make sure to call send_code_request first.'
)
phone_hash = phone_hash or self._phone_code_hash.get(phone, None)
if not phone_hash:
raise ValueError('You also need to provide a phone_code_hash.')
return phone, phone_hash |
python | def update_coordinates(self, points, mesh=None, render=True):
"""
Updates the points of the an object in the plotter.
Parameters
----------
points : np.ndarray
Points to replace existing points.
mesh : vtk.PolyData or vtk.UnstructuredGrid, optional
Object that has already been added to the Plotter. If
None, uses last added mesh.
render : bool, optional
Forces an update to the render window. Default True.
"""
if mesh is None:
mesh = self.mesh
mesh.points = points
if render:
self._render() |
java | public void set(Expr expr) {
this.type = expr.type;
this.value = expr.value;
this.left = expr.left;
this.right = expr.right;
this.query = expr.query;
} |
python | def set_state_from_exit_status(self, status, notif_period, hosts, services):
"""Set the state in UP, WARNING, CRITICAL, UNKNOWN or UNREACHABLE
according to the status of a check result.
:param status: integer between 0 and 4
:type status: int
:return: None
"""
now = time.time()
# we should put in last_state the good last state:
# if not just change the state by an problem/impact
# we can take current state. But if it's the case, the
# real old state is self.state_before_impact (it's the TRUE
# state in fact)
# but only if the global conf have enable the impact state change
cls = self.__class__
if cls.enable_problem_impacts_states_change \
and self.is_impact \
and not self.state_changed_since_impact:
self.last_state = self.state_before_impact
else: # standard case
self.last_state = self.state
# The last times are kept as integer values rather than float... no need for ms!
if status == 0:
self.state = u'OK'
self.state_id = 0
self.last_time_ok = int(self.last_state_update)
# self.last_time_ok = self.last_state_update
state_code = 'o'
elif status == 1:
self.state = u'WARNING'
self.state_id = 1
self.last_time_warning = int(self.last_state_update)
# self.last_time_warning = self.last_state_update
state_code = 'w'
elif status == 2:
self.state = u'CRITICAL'
self.state_id = 2
self.last_time_critical = int(self.last_state_update)
# self.last_time_critical = self.last_state_update
state_code = 'c'
elif status == 3:
self.state = u'UNKNOWN'
self.state_id = 3
self.last_time_unknown = int(self.last_state_update)
# self.last_time_unknown = self.last_state_update
state_code = 'u'
elif status == 4:
self.state = u'UNREACHABLE'
self.state_id = 4
self.last_time_unreachable = int(self.last_state_update)
# self.last_time_unreachable = self.last_state_update
state_code = 'x'
else:
self.state = u'CRITICAL' # exit code UNDETERMINED
self.state_id = 2
self.last_time_critical = int(self.last_state_update)
# self.last_time_critical = self.last_state_update
state_code = 'c'
if state_code in self.flap_detection_options:
self.add_flapping_change(self.state != self.last_state)
# Now we add a value, we update the is_flapping prop
self.update_flapping(notif_period, hosts, services)
if self.state != self.last_state:
self.last_state_change = self.last_state_update
self.duration_sec = now - self.last_state_change |
python | def _game_image_from_screen(self, game_type):
"""Return the image of the given game type from the screen.
Return None if no game is found.
"""
# screen
screen_img = self._screen_shot()
# game image
game_rect = self._game_finders[game_type].locate_in(screen_img)
if game_rect is None:
return
t, l, b, r = game_rect
game_img = screen_img[t:b, l:r]
return game_img |
python | def get_schema_node(self, path: SchemaPath) -> Optional[SchemaNode]:
"""Return the schema node addressed by a schema path.
Args:
path: Schema path.
Returns:
Schema node if found in the schema, or ``None``.
Raises:
InvalidSchemaPath: If the schema path is invalid.
"""
return self.schema.get_schema_descendant(
self.schema_data.path2route(path)) |
python | def prepare_runtime(self, runtime_dir, data):
"""Prepare runtime directory."""
# Copy over Python process runtime (resolwe.process).
import resolwe.process as runtime_package
src_dir = os.path.dirname(inspect.getsourcefile(runtime_package))
dest_package_dir = os.path.join(runtime_dir, PYTHON_RUNTIME_DIRNAME, 'resolwe', 'process')
shutil.copytree(src_dir, dest_package_dir)
os.chmod(dest_package_dir, 0o755)
# Write python source file.
source = data.process.run.get('program', '')
program_path = os.path.join(runtime_dir, PYTHON_PROGRAM_FILENAME)
with open(program_path, 'w') as file:
file.write(source)
os.chmod(program_path, 0o755)
# Write serialized inputs.
inputs = copy.deepcopy(data.input)
hydrate_input_references(inputs, data.process.input_schema)
hydrate_input_uploads(inputs, data.process.input_schema)
inputs_path = os.path.join(runtime_dir, PYTHON_INPUTS_FILENAME)
# XXX: Skip serialization of LazyStorageJSON. We should support
# LazyStorageJSON in Python processes on the new communication protocol
def default(obj):
"""Get default value."""
class_name = obj.__class__.__name__
if class_name == 'LazyStorageJSON':
return ''
raise TypeError(f'Object of type {class_name} is not JSON serializable')
with open(inputs_path, 'w') as file:
json.dump(inputs, file, default=default)
# Generate volume maps required to expose needed files.
volume_maps = {
PYTHON_RUNTIME_DIRNAME: PYTHON_RUNTIME_VOLUME,
PYTHON_PROGRAM_FILENAME: PYTHON_PROGRAM_VOLUME,
PYTHON_INPUTS_FILENAME: PYTHON_INPUTS_VOLUME,
}
return volume_maps |
python | def patch_namespaced_role_binding(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_role_binding # noqa: E501
partially update the specified RoleBinding # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_role_binding(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the RoleBinding (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param UNKNOWN_BASE_TYPE body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: V1RoleBinding
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_namespaced_role_binding_with_http_info(name, namespace, body, **kwargs) # noqa: E501
else:
(data) = self.patch_namespaced_role_binding_with_http_info(name, namespace, body, **kwargs) # noqa: E501
return data |
java | public void marshall(OverallVolume overallVolume, ProtocolMarshaller protocolMarshaller) {
if (overallVolume == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(overallVolume.getVolumeStatistics(), VOLUMESTATISTICS_BINDING);
protocolMarshaller.marshall(overallVolume.getReadRatePercent(), READRATEPERCENT_BINDING);
protocolMarshaller.marshall(overallVolume.getDomainIspPlacements(), DOMAINISPPLACEMENTS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | public void setMonth(Integer newMonth) {
Integer oldMonth = month;
month = newMonth;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.UNIVERSAL_DATE_AND_TIME_STAMP__MONTH, oldMonth, month));
} |
java | public String getArgument( int index )
{
if (index >= arguments.size()) return null;
return arguments.get( index );
} |
java | private Configuration getMimeTypeConfiguration() {
return new AbstractConfiguration() {
@Override
public void configure(WebAppContext context) throws Exception {
MimeTypes mimeTypes = context.getMimeTypes();
for (MimeMappings.Mapping mapping : getMimeMappings()) {
mimeTypes.addMimeMapping(mapping.getExtension(),
mapping.getMimeType());
}
}
};
} |
java | public static boolean invert(ZMatrixRMaj input , ZMatrixRMaj output )
{
LinearSolverDense<ZMatrixRMaj> solver = LinearSolverFactory_ZDRM.lu(input.numRows);
if( solver.modifiesA() )
input = input.copy();
if( !solver.setA(input))
return false;
solver.invert(output);
return true;
} |
java | public void marshall(DirectConnectGatewayAssociationProposal directConnectGatewayAssociationProposal, ProtocolMarshaller protocolMarshaller) {
if (directConnectGatewayAssociationProposal == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(directConnectGatewayAssociationProposal.getProposalId(), PROPOSALID_BINDING);
protocolMarshaller.marshall(directConnectGatewayAssociationProposal.getDirectConnectGatewayId(), DIRECTCONNECTGATEWAYID_BINDING);
protocolMarshaller
.marshall(directConnectGatewayAssociationProposal.getDirectConnectGatewayOwnerAccount(), DIRECTCONNECTGATEWAYOWNERACCOUNT_BINDING);
protocolMarshaller.marshall(directConnectGatewayAssociationProposal.getProposalState(), PROPOSALSTATE_BINDING);
protocolMarshaller.marshall(directConnectGatewayAssociationProposal.getAssociatedGateway(), ASSOCIATEDGATEWAY_BINDING);
protocolMarshaller.marshall(directConnectGatewayAssociationProposal.getExistingAllowedPrefixesToDirectConnectGateway(),
EXISTINGALLOWEDPREFIXESTODIRECTCONNECTGATEWAY_BINDING);
protocolMarshaller.marshall(directConnectGatewayAssociationProposal.getRequestedAllowedPrefixesToDirectConnectGateway(),
REQUESTEDALLOWEDPREFIXESTODIRECTCONNECTGATEWAY_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | public RedisLinkedServerWithPropertiesInner create(String resourceGroupName, String name, String linkedServerName, RedisLinkedServerCreateParameters parameters) {
return createWithServiceResponseAsync(resourceGroupName, name, linkedServerName, parameters).toBlocking().last().body();
} |
java | public short[] toShortArray() {
return collectSized(ShortBuffer::new, ShortBuffer::add, ShortBuffer::addAll, ShortBuffer::new,
ShortBuffer::addUnsafe).toArray();
} |
python | def similarity(self, other: Trigram) -> Tuple[float, L]:
"""
Returns the best matching score and the associated label.
"""
return max(
((t % other, l) for t, l in self.trigrams),
key=lambda x: x[0],
) |
python | def no_missing_parents(data_wrapper):
'''Check that all points have existing parents
Point's parent ID must exist and parent must be declared
before child.
Returns:
CheckResult with result and list of IDs that have no parent
'''
db = data_wrapper.data_block
ids = np.setdiff1d(db[:, COLS.P], db[:, COLS.ID])[1:]
return CheckResult(len(ids) == 0, ids.astype(np.int) + 1) |
java | public static <T> List<List<T>> partition(List<T> list, final int partitionSize) {
List<List<T>> parts = new ArrayList<List<T>>();
final int listSize = list.size();
for (int i = 0; i < listSize; i += partitionSize) {
parts.add(new ArrayList<T>(list.subList(i, Math.min(listSize, i + partitionSize))));
}
return parts;
} |
java | @Override
public void getServers(
GetServersRequest request, StreamObserver<GetServersResponse> responseObserver) {
ServerList servers = channelz.getServers(request.getStartServerId(), maxPageSize);
GetServersResponse resp;
try {
resp = ChannelzProtoUtil.toGetServersResponse(servers);
} catch (StatusRuntimeException e) {
responseObserver.onError(e);
return;
}
responseObserver.onNext(resp);
responseObserver.onCompleted();
} |
python | def _cytomine_parameter_name_synonyms(name, prefix="--"):
"""For a given parameter name, returns all the possible usual synonym (and the parameter itself). Optionally, the
function can prepend a string to the found names.
If a parameters has no known synonyms, the function returns only the prefixed $name.
Parameters
----------
name: str
Parameter based on which synonyms must searched for
prefix: str
The prefix
Returns
-------
names: str
List of prefixed parameter names containing at least $name (preprended with $prefix).
"""
synonyms = [
["host", "cytomine_host"],
["public_key", "publicKey", "cytomine_public_key"],
["private_key", "privateKey", "cytomine_private_key"],
["base_path", "basePath", "cytomine_base_path"],
["id_software", "cytomine_software_id", "cytomine_id_software", "idSoftware", "software_id"],
["id_project", "cytomine_project_id", "cytomine_id_project", "idProject", "project_id"]
]
synonyms_dict = {params[i]: params[:i] + params[(i + 1):] for params in synonyms for i in range(len(params))}
if name not in synonyms_dict:
return [prefix + name]
return [prefix + n for n in ([name] + synonyms_dict[name])] |
python | def merge(self, other):
"""Merge documents from the other index. Update precomputed similarities
in the process."""
other.qindex.normalize, other.qindex.num_best = False, self.topsims
# update precomputed "most similar" for old documents (in case some of
# the new docs make it to the top-N for some of the old documents)
logger.info("updating old precomputed values")
pos, lenself = 0, len(self.qindex)
for chunk in self.qindex.iter_chunks():
for sims in other.qindex[chunk]:
if pos in self.pos2id:
# ignore masked entries (deleted, overwritten documents)
docid = self.pos2id[pos]
sims = self.sims2scores(sims)
self.id2sims[docid] = merge_sims(self.id2sims[docid], sims, self.topsims)
pos += 1
if pos % 10000 == 0:
logger.info("PROGRESS: updated doc #%i/%i" % (pos, lenself))
self.id2sims.sync()
logger.info("merging fresh index into optimized one")
pos, docids = 0, []
for chunk in other.qindex.iter_chunks():
for vec in chunk:
if pos in other.pos2id: # don't copy deleted documents
self.qindex.add_documents([vec])
docids.append(other.pos2id[pos])
pos += 1
self.qindex.save()
self.update_ids(docids)
logger.info("precomputing most similar for the fresh index")
pos, lenother = 0, len(other.qindex)
norm, self.qindex.normalize = self.qindex.normalize, False
topsims, self.qindex.num_best = self.qindex.num_best, self.topsims
for chunk in other.qindex.iter_chunks():
for sims in self.qindex[chunk]:
if pos in other.pos2id:
# ignore masked entries (deleted, overwritten documents)
docid = other.pos2id[pos]
self.id2sims[docid] = self.sims2scores(sims)
pos += 1
if pos % 10000 == 0:
logger.info("PROGRESS: precomputed doc #%i/%i" % (pos, lenother))
self.qindex.normalize, self.qindex.num_best = norm, topsims
self.id2sims.sync() |
java | public int getLength()
{
// Tell if this is being called from within a predicate.
boolean isPredicateTest = (this == m_execContext.getSubContextList());
// And get how many total predicates are part of this step.
int predCount = getPredicateCount();
// If we have already calculated the length, and the current predicate
// is the first predicate, then return the length. We don't cache
// the anything but the length of the list to the first predicate.
if (-1 != m_length && isPredicateTest && m_predicateIndex < 1)
return m_length;
// I'm a bit worried about this one, since it doesn't have the
// checks found above. I suspect it's fine. -sb
if (m_foundLast)
return m_pos;
// Create a clone, and count from the current position to the end
// of the list, not taking into account the current predicate and
// predicates after the current one.
int pos = (m_predicateIndex >= 0) ? getProximityPosition() : m_pos;
LocPathIterator clone;
try
{
clone = (LocPathIterator) clone();
}
catch (CloneNotSupportedException cnse)
{
return -1;
}
// We want to clip off the last predicate, but only if we are a sub
// context node list, NOT if we are a context list. See pos68 test,
// also test against bug4638.
if (predCount > 0 && isPredicateTest)
{
// Don't call setPredicateCount, because it clones and is slower.
clone.m_predCount = m_predicateIndex;
// The line above used to be:
// clone.m_predCount = predCount - 1;
// ...which looks like a dumb bug to me. -sb
}
int next;
while (DTM.NULL != (next = clone.nextNode()))
{
pos++;
}
if (isPredicateTest && m_predicateIndex < 1)
m_length = pos;
return pos;
} |
java | public String getString(int key) {
PebbleTuple tuple = getTuple(key, PebbleTuple.TupleType.STRING);
if (tuple == null) {
return null;
}
return (String) tuple.value;
} |
python | def ref2names2commdct(ref2names, commdct):
"""embed ref2names into commdct"""
for comm in commdct:
for cdct in comm:
try:
refs = cdct['object-list'][0]
validobjects = ref2names[refs]
cdct.update({'validobjects':validobjects})
except KeyError as e:
continue
return commdct |
java | public CoinbaseRecurringPayments getCoinbaseRecurringPayments(Integer page, final Integer limit)
throws IOException {
final CoinbaseRecurringPayments recurringPayments =
coinbase.getRecurringPayments(
page,
limit,
exchange.getExchangeSpecification().getApiKey(),
signatureCreator,
exchange.getNonceFactory());
return recurringPayments;
} |
python | def owner(*paths, **kwargs):
'''
.. versionadded:: 2014.7.0
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.yumpkg.version>`, if a
single path is passed, a string will be returned, and if multiple paths are
passed, a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Examples:
.. code-block:: bash
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /etc/httpd/conf/httpd.conf
'''
if not paths:
return ''
ret = {}
cmd_prefix = ['rpm', '-qf', '--queryformat', '%{name}']
for path in paths:
ret[path] = __salt__['cmd.run_stdout'](
cmd_prefix + [path],
output_loglevel='trace',
python_shell=False
)
if 'not owned' in ret[path].lower():
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret |
python | def main():
"""
NAME
dmag_magic.py
DESCRIPTION
plots intensity decay curves for demagnetization experiments
SYNTAX
dmag_magic -h [command line options]
INPUT
takes magic formatted measurements.txt files
OPTIONS
-h prints help message and quits
-f FILE: specify input file, default is: measurements.txt
-obj OBJ: specify object [loc, sit, sam, spc] for plot,
default is by location
-LT [AF,T,M]: specify lab treatment type, default AF
-XLP [PI]: exclude specific lab protocols,
(for example, method codes like LP-PI)
-N do not normalize by NRM magnetization
-sav save plots silently and quit
-fmt [svg,jpg,png,pdf] set figure format [default is svg]
NOTE
loc: location (study); sit: site; sam: sample; spc: specimen
"""
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
# initialize variables from command line + defaults
dir_path = pmag.get_named_arg("-WD", default_val=".")
input_dir_path = pmag.get_named_arg('-ID', '')
if not input_dir_path:
input_dir_path = dir_path
in_file = pmag.get_named_arg("-f", default_val="measurements.txt")
in_file = pmag.resolve_file_name(in_file, input_dir_path)
if "-ID" not in sys.argv:
input_dir_path = os.path.split(in_file)[0]
plot_by = pmag.get_named_arg("-obj", default_val="loc")
LT = pmag.get_named_arg("-LT", "AF")
no_norm = pmag.get_flag_arg_from_sys("-N")
norm = False if no_norm else True
save_plots = pmag.get_flag_arg_from_sys("-sav")
fmt = pmag.get_named_arg("-fmt", "svg")
XLP = pmag.get_named_arg("-XLP", "")
spec_file = pmag.get_named_arg("-fsp", default_val="specimens.txt")
samp_file = pmag.get_named_arg("-fsa", default_val="samples.txt")
site_file = pmag.get_named_arg("-fsi", default_val="sites.txt")
loc_file = pmag.get_named_arg("-flo", default_val="locations.txt")
dmag_magic(in_file, dir_path, input_dir_path, spec_file, samp_file,
site_file, loc_file, plot_by, LT, norm, XLP,
save_plots, fmt) |
java | private TimeZone parseTimezone(CharSequenceScanner scanner) {
int pos = scanner.getCurrentIndex();
Integer offset = parseTimezoneOffset(scanner);
// has offset?
if (offset != null) {
int offsetMs = offset.intValue();
String tzName = "GMT";
if (offsetMs != 0) {
if (offsetMs < 0) {
tzName += "-";
} else {
tzName += "+";
}
tzName += scanner.substring(pos, scanner.getCurrentIndex());
}
return new SimpleTimeZone(offsetMs, tzName);
} else if (scanner.getCurrentIndex() == pos) {
return null;
} else {
// UTC
return TZ_UTC;
}
} |
java | public com.google.api.ads.admanager.axis.v201902.ProposalApprovalStatus getApprovalStatus() {
return approvalStatus;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.