language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
python | def govuk_template(context: Context, version='0.23.0', replace_fonts=True):
"""
Installs GOV.UK template
"""
if FileSet(os.path.join(context.app.govuk_templates_path, 'base.html')):
# NB: check is only on main template and not the assets included
return
url = 'https://github.com/alphagov/govuk_template/releases' \
'/download/v{0}/django_govuk_template-{0}.tgz'.format(version)
try:
context.shell('curl --location %(silent)s --output govuk_template.tgz %(url)s' % {
'silent': '--silent' if context.verbosity == 0 else '',
'url': url,
})
context.shell('tar xzf govuk_template.tgz ./govuk_template')
rsync_flags = '-avz' if context.verbosity == 2 else '-az'
context.shell('rsync %s govuk_template/static/ %s/' % (rsync_flags, context.app.asset_build_path))
context.shell('rsync %s govuk_template/templates/ %s/' % (rsync_flags, context.app.templates_path))
finally:
context.shell('rm -rf govuk_template.tgz ./govuk_template')
if replace_fonts:
# govuk_template includes .eot font files for IE, but they load relative to current URL not the stylesheet
# this option removes these files so common's fonts-ie8.css override is used
context.shell('rm -rf %s/stylesheets/fonts-ie8.css'
' %s/stylesheets/fonts/' % (context.app.asset_build_path, context.app.asset_build_path)) |
python | def _get_headers(self, environ):
"""The list of headers for this response
"""
headers = self.headers
method = environ['REQUEST_METHOD']
if has_empty_content(self.status_code, method) and method != HEAD:
headers.pop('content-type', None)
headers.pop('content-length', None)
self._content = ()
else:
if not self.is_streamed():
cl = reduce(count_len, self._content, 0)
headers['content-length'] = str(cl)
ct = headers.get('content-type')
# content type encoding available
if self.encoding:
ct = ct or 'text/plain'
if ';' not in ct:
ct = '%s; charset=%s' % (ct, self.encoding)
if ct:
headers['content-type'] = ct
if method == HEAD:
self._content = ()
# Cookies
if (self.status_code < 400 and self._can_store_cookies and
self._cookies):
for c in self.cookies.values():
headers.add('set-cookie', c.OutputString())
return headers.items() |
java | @Override
public CPSpecificationOption findByUUID_G(String uuid, long groupId)
throws NoSuchCPSpecificationOptionException {
CPSpecificationOption cpSpecificationOption = fetchByUUID_G(uuid,
groupId);
if (cpSpecificationOption == null) {
StringBundler msg = new StringBundler(6);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("uuid=");
msg.append(uuid);
msg.append(", groupId=");
msg.append(groupId);
msg.append("}");
if (_log.isDebugEnabled()) {
_log.debug(msg.toString());
}
throw new NoSuchCPSpecificationOptionException(msg.toString());
}
return cpSpecificationOption;
} |
java | private static String createFingerprintForUrl(final URI url) {
StringBuilder truncatedUrl = new StringBuilder(url.getHost());
String path = url.getPath();
if (path != null) {
truncatedUrl.append(path);
}
String query = url.getQuery();
if (query != null) {
truncatedUrl.append("?");
String[] queryParams = url.getQuery().split("&");
List<String> queryParamList = Arrays.asList(queryParams);
queryParamList.stream()
.sorted(String::compareToIgnoreCase)
.forEachOrdered(truncatedUrl::append);
}
return DigestUtils.sha256Hex(truncatedUrl.toString());
} |
java | @Override
public boolean listenToResultSet(final BenchmarkMethod meth, final AbstractMeter meter, final double data) {
Method m = meth.getMethodToBench();
try {
return view.updateCurrentElement(meter, (m.getDeclaringClass().getName() + "." + m.getName()));
} catch (final SocketViewException e) {
throw new IllegalStateException(e);
}
} |
java | private RepositoryBrowser infer() {
for( AbstractProject p : Jenkins.getInstance().allItems(AbstractProject.class) ) {
SCM scm = p.getScm();
if (scm!=null && scm.getClass()==owner.getClass() && scm.getBrowser()!=null &&
((SCMDescriptor)scm.getDescriptor()).isBrowserReusable(scm,owner)) {
return scm.getBrowser();
}
}
return null;
} |
java | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLInverseObjectPropertiesAxiomImpl instance) throws SerializationException {
deserialize(streamReader, instance);
} |
python | def wavelength_match(a, b):
"""Return if two wavelengths are equal.
Args:
a (tuple or scalar): (min wl, nominal wl, max wl) or scalar wl
b (tuple or scalar): (min wl, nominal wl, max wl) or scalar wl
"""
if type(a) == (type(b) or
isinstance(a, numbers.Number) and
isinstance(b, numbers.Number)):
return a == b
elif a is None or b is None:
return False
elif isinstance(a, (list, tuple)) and len(a) == 3:
return a[0] <= b <= a[2]
elif isinstance(b, (list, tuple)) and len(b) == 3:
return b[0] <= a <= b[2]
else:
raise ValueError("Can only compare wavelengths of length 1 or 3") |
java | public void displayValidation(String entityId, CmsValidationResult validationResult) {
if (m_formTabPanel != null) {
CmsAttributeHandler.clearErrorStyles(m_formTabPanel);
}
m_rootHandler.visit(CmsValidationHandler::clearValidation);
if (validationResult.hasWarnings(entityId)) {
for (Entry<String[], String> warning : validationResult.getWarnings(entityId).entrySet()) {
String[] pathElements = warning.getKey();
// check if there are no errors for this attribute
if (!validationResult.hasErrors(entityId)
|| !validationResult.getErrors(entityId).containsKey(pathElements)) {
CmsAttributeHandler handler = m_rootHandler.getHandlerByPath(pathElements);
if (handler != null) {
String attributeName = pathElements[pathElements.length - 1];
handler.setWarningMessage(
CmsContentDefinition.extractIndex(attributeName),
warning.getValue(),
m_formTabPanel);
}
}
}
}
if (validationResult.hasErrors(entityId)) {
for (Entry<String[], String> error : validationResult.getErrors(entityId).entrySet()) {
String[] pathElements = error.getKey();
CmsAttributeHandler handler = m_rootHandler.getHandlerByPath(pathElements);
if (handler != null) {
String attributeName = pathElements[pathElements.length - 1];
handler.setErrorMessage(
CmsContentDefinition.extractIndex(attributeName),
error.getValue(),
m_formTabPanel);
}
}
m_validationContext.addInvalidEntity(entityId);
} else {
m_validationContext.addValidEntity(entityId);
}
ValueChangeEvent.fire(this, m_validationContext);
m_validating = false;
} |
python | def get_module(self, module_name):
"""Return loaded module from the given name."""
try:
return self.module[module_name]
except KeyError:
return sys.modules[module_name] |
java | @Override
public SIUncoordinatedTransaction createUncoordinatedTransaction()
throws SIConnectionUnavailableException, SIConnectionDroppedException,
SIErrorException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "createUncoordinatedTransaction");
SIUncoordinatedTransaction tran = createUncoordinatedTransaction(true);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "createUncoordinatedTransaction", tran);
return tran;
} |
java | public static LocalDate getDateFromFloatingPointDate(LocalDate referenceDate, double floatingPointDate) {
if(referenceDate == null) {
return null;
}
return referenceDate.plusDays((int)Math.round(floatingPointDate*365.0));
} |
java | public static String getReconcileHashCode(Map<String, AtomicInteger> instanceCountMap) {
StringBuilder reconcileHashCode = new StringBuilder(75);
for (Map.Entry<String, AtomicInteger> mapEntry : instanceCountMap.entrySet()) {
reconcileHashCode.append(mapEntry.getKey()).append(STATUS_DELIMITER).append(mapEntry.getValue().get())
.append(STATUS_DELIMITER);
}
return reconcileHashCode.toString();
} |
python | def add(self, document):
"""
Add a document to the database.
"""
docid = int(document.uniqueIdentifier())
text = u' '.join(document.textParts())
self.store.executeSQL(self.addSQL, (docid, text)) |
java | @Override
public void clean() throws IOException {
if (this.isDatasetBlacklisted) {
this.log.info("Dataset blacklisted. Cleanup skipped for " + datasetRoot());
return;
}
boolean atLeastOneFailureSeen = false;
for (VersionFinderAndPolicy<T> versionFinderAndPolicy : getVersionFindersAndPolicies()) {
VersionSelectionPolicy<T> selectionPolicy = versionFinderAndPolicy.getVersionSelectionPolicy();
VersionFinder<? extends T> versionFinder = versionFinderAndPolicy.getVersionFinder();
if (!selectionPolicy.versionClass().isAssignableFrom(versionFinder.versionClass())) {
throw new IOException("Incompatible dataset version classes.");
}
this.log.info(String.format("Cleaning dataset %s. Using version finder %s and policy %s", this,
versionFinder.getClass().getName(), selectionPolicy));
List<T> versions = Lists.newArrayList(versionFinder.findDatasetVersions(this));
if (versions.isEmpty()) {
this.log.warn("No dataset version can be found. Ignoring.");
continue;
}
Collections.sort(versions, Collections.reverseOrder());
Collection<T> deletableVersions = selectionPolicy.listSelectedVersions(versions);
cleanImpl(deletableVersions);
List<DatasetVersion> allVersions = Lists.newArrayList();
for (T ver : versions) {
allVersions.add(ver);
}
for (RetentionAction retentionAction : versionFinderAndPolicy.getRetentionActions()) {
try {
retentionAction.execute(allVersions);
} catch (Throwable t) {
atLeastOneFailureSeen = true;
log.error(String.format("RetentionAction %s failed for dataset %s", retentionAction.getClass().getName(),
this.datasetRoot()), t);
}
}
}
if (atLeastOneFailureSeen) {
throw new RuntimeException(String.format(
"At least one failure happened while processing %s. Look for previous logs for failures", datasetRoot()));
}
} |
python | def _priority(s):
"""Return priority for a given object."""
if type(s) in (list, tuple, set, frozenset):
return ITERABLE
if type(s) is dict:
return DICT
if issubclass(type(s), type):
return TYPE
if hasattr(s, "validate"):
return VALIDATOR
if callable(s):
return CALLABLE
else:
return COMPARABLE |
python | def indirect(self, interface):
"""
Create an L{IConchUser} avatar which will use L{ShellServer} to
interact with the connection.
"""
if interface is IConchUser:
componentized = Componentized()
user = _BetterTerminalUser(componentized, None)
session = _BetterTerminalSession(componentized)
session.transportFactory = TerminalSessionTransport
session.chainedProtocolFactory = lambda: ServerProtocol(ShellServer, self.store)
componentized.setComponent(IConchUser, user)
componentized.setComponent(ISession, session)
return user
raise NotImplementedError(interface) |
python | def convert_to_unicode( tscii_input ):
""" convert a byte-ASCII encoded string into equivalent Unicode string
in the UTF-8 notation."""
output = list()
prev = None
prev2x = None
# need a look ahead of 2 tokens atleast
for char in tscii_input:
## print "%2x"%ord(char) # debugging
if ord(char) < 128 :
# base-ASCII copy to output
output.append( char )
prev = None
prev2x = None
elif ord(char) in ISCII_DIRECT_LOOKUP:
if ( prev in ISCII_PRE_MODIFIER ):
curr_char = [ISCII[ord(char)],ISCII[prev]]
else:
# we are direct lookup char
curr_char = [ISCII[ord(char)]]
char = None
output.extend( curr_char )
elif ( (ord(char) in ISCII_POST_MODIFIER) ):
if ( (prev in ISCII_DIRECT_LOOKUP) and
(prev2x in ISCII_PRE_MODIFIER) ):
if len(output) >= 2:
del output[-1] #we are reducing this token to something new
del output[-2]
elif len(output)==1:
del output[-1]
else:
# nothing to delete here..
pass
output.extend( [ISCII[prev], ISCII[prev2x]] )
else:
print("Warning: malformed ISCII encoded file; skipping characters")
prev = None
char = None
else:
# pass - must be one of the pre/post modifiers
pass
prev2x = prev
if char:
prev = ord(char)
return u"".join(output) |
java | @Override
public void init(final ServletConfig config) throws ServletException {
try {
ContextClassLoaderUtils.doWithClassLoader(jasperClassLoader,
new Callable<Void>() {
@Override
public Void call() throws Exception {
config.getServletContext().setAttribute(
org.apache.tomcat.InstanceManager.class
.getName(), new InstanceManager());
jasperServlet.init(config);
return null;
}
});
} catch (ServletException e) {
// re-thrown
throw e;
//CHECKSTYLE:OFF
} catch (Exception ignore) {
// ignored as it should never happen
LOG.error("Ignored exception", ignore);
}
//CHECKSTYLE:ON
} |
java | protected Predicate createPredicate(Path root, CriteriaQuery<?> query, CriteriaBuilder cb, String propertyName,
ComparisonOperator operator, Object argument, PersistenceContext context)
{
logger.debug("Creating criterion: {} {} {}", propertyName, operator, argument);
switch (operator)
{
case EQUAL:
{
if (containWildcard(argument))
{
return createLike(root, query, cb, propertyName, argument, context);
}
else
{
return createEqual(root, query, cb, propertyName, argument, context);
}
}
case NOT_EQUAL:
{
if (containWildcard(argument))
{
return createNotLike(root, query, cb, propertyName, argument, context);
}
else
{
return createNotEqual(root, query, cb, propertyName, argument, context);
}
}
case GREATER_THAN:
return createGreaterThan(root, query, cb, propertyName, argument, context);
case GREATER_EQUAL:
return createGreaterEqual(root, query, cb, propertyName, argument, context);
case LESS_THAN:
return createLessThan(root, query, cb, propertyName, argument, context);
case LESS_EQUAL:
return createLessEqual(root, query, cb, propertyName, argument, context);
case IN:
return createIn(root, query, cb, propertyName, argument, context);
case NOT_IN:
return createNotIn(root, query, cb, propertyName, argument, context);
}
throw new IllegalArgumentException("Unknown operator: " + operator);
} |
python | def enabled(name):
'''
Enable the RDP service and make sure access to the RDP
port is allowed in the firewall configuration
'''
ret = {'name': name,
'result': True,
'changes': {},
'comment': ''}
stat = __salt__['rdp.status']()
if not stat:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'RDP will be enabled'
return ret
ret['result'] = __salt__['rdp.enable']()
ret['changes'] = {'RDP was enabled': True}
return ret
ret['comment'] = 'RDP is enabled'
return ret |
java | public static double getSwapAnnuity(double evaluationTime, ScheduleInterface schedule, DiscountCurveInterface discountCurve, AnalyticModelInterface model) {
double value = 0.0;
for(int periodIndex=0; periodIndex<schedule.getNumberOfPeriods(); periodIndex++) {
double paymentDate = schedule.getPayment(periodIndex);
if(paymentDate <= evaluationTime) {
continue;
}
double periodLength = schedule.getPeriodLength(periodIndex);
double discountFactor = discountCurve.getDiscountFactor(model, paymentDate);
value += periodLength * discountFactor;
}
return value / discountCurve.getDiscountFactor(model, evaluationTime);
} |
python | def popitem(self):
"""Remove and return the `(key, value)` pair least frequently used."""
try:
(key, _), = self.__counter.most_common(1)
except ValueError:
raise KeyError('%s is empty' % self.__class__.__name__)
else:
return (key, self.pop(key)) |
java | public void sendGroupContact(final String groupId, final String[] contactIds) throws NotFoundException, GeneralException, UnauthorizedException {
// reuestByID appends the "ID" to the base path, so this workaround
// lets us add a query string.
String path = String.format("%s%s?%s", groupId, CONTACTPATH, getQueryString(contactIds));
messageBirdService.requestByID(GROUPPATH, path, null);
} |
python | def get_delay(self, planned, estimated):
"""Min of delay on planned departure."""
delay = 0 # default is no delay
if estimated >= planned: # there is a delay
delay = round((estimated - planned).seconds / 60)
else: # leaving earlier
delay = round((planned - estimated).seconds / 60) * -1
return delay |
python | def add_dataset_to_collection(dataset_id, collection_id, **kwargs):
"""
Add a single dataset to a dataset collection.
"""
collection_i = _get_collection(collection_id)
collection_item = _get_collection_item(collection_id, dataset_id)
if collection_item is not None:
raise HydraError("Dataset Collection %s already contains dataset %s", collection_id, dataset_id)
new_item = DatasetCollectionItem()
new_item.dataset_id=dataset_id
new_item.collection_id=collection_id
collection_i.items.append(new_item)
db.DBSession.flush()
return 'OK' |
java | public static boolean addFilelistener(String pResourcename, String pListenerPath)
throws FileNotFoundException, IOException, ClassNotFoundException {
mFilelistenerToPaths = new HashMap<String, String>();
File listenerFilePaths = new File(StorageManager.ROOT_PATH + File.separator + "mapping.data");
getFileListenersFromSystem(listenerFilePaths);
mFilelistenerToPaths.put(pResourcename, pListenerPath);
ByteArrayDataOutput output = ByteStreams.newDataOutput();
for (Entry<String, String> e : mFilelistenerToPaths.entrySet()) {
output.write((e.getKey() + "\n").getBytes());
output.write((e.getValue() + "\n").getBytes());
}
java.nio.file.Files.write(listenerFilePaths.toPath(), output.toByteArray(),
StandardOpenOption.TRUNCATE_EXISTING);
return true;
} |
java | public static double binomialCdf(int k, double p, int n) {
if(k<0 || p<0 || n<1) {
throw new IllegalArgumentException("All the parameters must be positive and n larger than 1.");
}
k = Math.min(k, n);
double probabilitySum = approxBinomialCdf(k,p,n);
return probabilitySum;
} |
python | def constrain(*objs):
"""Constrain group of DataFrames & Series to intersection of indices.
Parameters
----------
objs : iterable
DataFrames and/or Series to constrain
Returns
-------
new_dfs : list of DataFrames, copied rather than inplace
"""
# TODO: build in the options to first dropna on each index before finding
# intersection, AND to use `dropcol` from this module. Note that this
# would require filtering out Series to which dropcol isn't applicable.
# A little bit of set magic below.
# Note that pd.Index.intersection only applies to 2 Index objects
common_idx = pd.Index(set.intersection(*[set(o.index) for o in objs]))
new_dfs = (o.reindex(common_idx) for o in objs)
return tuple(new_dfs) |
java | public Date setMinSelectableDate(Date min) {
if (min == null) {
minSelectableDate = defaultMinSelectableDate;
} else {
minSelectableDate = min;
}
return minSelectableDate;
} |
java | private long grow(PrintStream out, List<ItemSet> list, TotalSupportTree ttree, HeaderTableItem header, int[] itemset, int[] localItemSupport, int[] prefixItemset) {
long n = 1;
int support = header.count;
int item = header.id;
itemset = insert(itemset, item);
collect(out, list, ttree, itemset, support);
if (header.node.next == null) {
FPTree.Node node = header.node;
n += grow(out, list, ttree, node.parent, itemset, support);
} else {
// Count singles in linked list
if (getLocalItemSupport(header.node, localItemSupport)) {
// Create local FP tree
FPTree fptree = getLocalFPTree(header.node, localItemSupport, prefixItemset);
// Mine new FP-tree
n += grow(out, list, ttree, fptree, itemset, localItemSupport, prefixItemset);
}
}
return n;
} |
python | def from_dictionary(cls, dictionary):
"""Parse a dictionary representing all command line parameters."""
if not isinstance(dictionary, dict):
raise TypeError('dictionary has to be a dict type, got: {}'.format(type(dictionary)))
return cls(dictionary) |
java | public String[] getBuildMetaDataParts() {
if (this.buildMetaDataParts.length == 0) {
return EMPTY_ARRAY;
}
return Arrays.copyOf(this.buildMetaDataParts, this.buildMetaDataParts.length);
} |
python | def execute(self, input_data):
''' Execute method '''
# Grab the raw bytes of the sample
raw_bytes = input_data['sample']['raw_bytes']
# Spin up the rekall session and render components
session = MemSession(raw_bytes)
renderer = WorkbenchRenderer(session=session)
# Run the plugin
session.RunPlugin(self.plugin_name, renderer=renderer)
return renderer.get_output() |
java | private boolean hasTextContent(Node child) {
return child.getNodeType() != Node.COMMENT_NODE
&& child.getNodeType() != Node.PROCESSING_INSTRUCTION_NODE;
} |
java | private void executeGlobalPostProcessing(boolean processBundleFlag, StopWatch stopWatch) {
// Launch global postprocessing
if (resourceTypePostprocessor != null) {
if (stopWatch != null) {
stopWatch.start("Global postprocessing");
}
GlobalPostProcessingContext ctx = new GlobalPostProcessingContext(config, this, resourceHandler,
processBundleFlag);
resourceTypePostprocessor.processBundles(ctx, this.bundles);
if (stopWatch != null) {
stopWatch.stop();
}
}
} |
java | public static long convertToUtc(long millis, String tz)
{
long ret = millis;
if(tz != null && tz.length() > 0)
{
DateTime dt = new DateTime(millis, DateTimeZone.forID(tz));
ret = dt.withZoneRetainFields(DateTimeZone.forID("UTC")).getMillis();
}
return ret;
} |
python | def mount_control_encode(self, target_system, target_component, input_a, input_b, input_c, save_position):
'''
Message to control a camera mount, directional antenna, etc.
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
input_a : pitch(deg*100) or lat, depending on mount mode (int32_t)
input_b : roll(deg*100) or lon depending on mount mode (int32_t)
input_c : yaw(deg*100) or alt (in cm) depending on mount mode (int32_t)
save_position : if "1" it will save current trimmed position on EEPROM (just valid for NEUTRAL and LANDING) (uint8_t)
'''
return MAVLink_mount_control_message(target_system, target_component, input_a, input_b, input_c, save_position) |
python | def load_fasta_file(filename):
"""Load a FASTA file and return the sequences as a list of SeqRecords
Args:
filename (str): Path to the FASTA file to load
Returns:
list: list of all sequences in the FASTA file as Biopython SeqRecord objects
"""
with open(filename, "r") as handle:
records = list(SeqIO.parse(handle, "fasta"))
return records |
java | private EDiff diffAlgorithm(final INodeReadTrx paramNewRtx, final INodeReadTrx paramOldRtx,
final DepthCounter paramDepth) throws TTIOException {
EDiff diff = null;
// Check if node has been deleted.
if (paramDepth.getOldDepth() > paramDepth.getNewDepth()) {
diff = EDiff.DELETED;
} else if (checkUpdate(paramNewRtx, paramOldRtx)) { // Check if node has
// been updated.
diff = EDiff.UPDATED;
} else {
// See if one of the right sibling matches.
EFoundEqualNode found = EFoundEqualNode.FALSE;
final long key = paramOldRtx.getNode().getDataKey();
while (((ITreeStructData)paramOldRtx.getNode()).hasRightSibling()
&& paramOldRtx.moveTo(((ITreeStructData)paramOldRtx.getNode()).getRightSiblingKey())
&& found == EFoundEqualNode.FALSE) {
if (checkNodes(paramNewRtx, paramOldRtx)) {
found = EFoundEqualNode.TRUE;
}
}
paramOldRtx.moveTo(key);
diff = found.kindOfDiff();
}
assert diff != null;
return diff;
} |
python | def publish(self,message,message_type,topic=''):
"""
Publish the message on the PUB socket with the given topic name.
Args:
- message: the message to publish
- message_type: the type of message being sent
- topic: the topic on which to send the message. Defaults to ''.
"""
if message_type == MULTIPART:
raise Exception("Unsupported request type")
super(Publisher,self).send(message,message_type,topic) |
java | protected void validate(String operationType) throws Exception
{
super.validate(operationType);
MPSString sessionid_validator = new MPSString();
sessionid_validator.setConstraintIsReq(MPSConstants.DELETE_CONSTRAINT, true);
sessionid_validator.validate(operationType, sessionid, "\"sessionid\"");
MPSString username_validator = new MPSString();
username_validator.setConstraintCharSetRegEx(MPSConstants.GENERIC_CONSTRAINT,"[ a-zA-Z0-9_#.:@=-]+");
username_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 128);
username_validator.setConstraintMinStrLen(MPSConstants.GENERIC_CONSTRAINT, 1);
username_validator.setConstraintIsReq(MPSConstants.ADD_CONSTRAINT, true);
username_validator.validate(operationType, username, "\"username\"");
MPSString password_validator = new MPSString();
password_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 128);
password_validator.setConstraintMinStrLen(MPSConstants.GENERIC_CONSTRAINT, 1);
password_validator.setConstraintIsReq(MPSConstants.ADD_CONSTRAINT, true);
password_validator.validate(operationType, password, "\"password\"");
MPSInt session_timeout_validator = new MPSInt();
session_timeout_validator.validate(operationType, session_timeout, "\"session_timeout\"");
} |
python | def read(self):
"""Read a DNS master file and build a zone object.
@raises dns.zone.NoSOA: No SOA RR was found at the zone origin
@raises dns.zone.NoNS: No NS RRset was found at the zone origin
"""
try:
while 1:
token = self.tok.get(True, True).unescape()
if token.is_eof():
if not self.current_file is None:
self.current_file.close()
if len(self.saved_state) > 0:
(self.tok,
self.current_origin,
self.last_name,
self.current_file,
self.ttl) = self.saved_state.pop(-1)
continue
break
elif token.is_eol():
continue
elif token.is_comment():
self.tok.get_eol()
continue
elif token.value[0] == '$':
u = token.value.upper()
if u == '$TTL':
token = self.tok.get()
if not token.is_identifier():
raise dns.exception.SyntaxError("bad $TTL")
self.ttl = dns.ttl.from_text(token.value)
self.tok.get_eol()
elif u == '$ORIGIN':
self.current_origin = self.tok.get_name()
self.tok.get_eol()
if self.zone.origin is None:
self.zone.origin = self.current_origin
elif u == '$INCLUDE' and self.allow_include:
token = self.tok.get()
if not token.is_quoted_string():
raise dns.exception.SyntaxError("bad filename in $INCLUDE")
filename = token.value
token = self.tok.get()
if token.is_identifier():
new_origin = dns.name.from_text(token.value, \
self.current_origin)
self.tok.get_eol()
elif not token.is_eol_or_eof():
raise dns.exception.SyntaxError("bad origin in $INCLUDE")
else:
new_origin = self.current_origin
self.saved_state.append((self.tok,
self.current_origin,
self.last_name,
self.current_file,
self.ttl))
self.current_file = file(filename, 'r')
self.tok = dns.tokenizer.Tokenizer(self.current_file,
filename)
self.current_origin = new_origin
else:
raise dns.exception.SyntaxError("Unknown master file directive '" + u + "'")
continue
self.tok.unget(token)
self._rr_line()
except dns.exception.SyntaxError, detail:
(filename, line_number) = self.tok.where()
if detail is None:
detail = "syntax error"
raise dns.exception.SyntaxError("%s:%d: %s" % (filename, line_number, detail))
# Now that we're done reading, do some basic checking of the zone.
if self.check_origin:
self.zone.check_origin() |
python | def open(filename, frame='unspecified'):
"""Create a Point from data saved in a file.
Parameters
----------
filename : :obj:`str`
The file to load data from.
frame : :obj:`str`
The frame to apply to the created point.
Returns
-------
:obj:`Point`
A point created from the data in the file.
"""
data = BagOfPoints.load_data(filename)
return Point(data, frame) |
java | private String toXml(Node node) {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(node);
transformer.transform(source, result);
return result.getWriter().toString();
} catch(TransformerException ex) {
throw new IllegalArgumentException("Could not transform " +node + " to XML", ex);
}
} |
python | def _validate_overriden_fields_are_not_defined_in_superclasses(class_to_field_type_overrides,
schema_graph):
"""Assert that the fields we want to override are not defined in superclasses."""
for class_name, field_type_overrides in six.iteritems(class_to_field_type_overrides):
for superclass_name in schema_graph.get_inheritance_set(class_name):
if superclass_name != class_name:
superclass = schema_graph.get_element_by_class_name(superclass_name)
for field_name in field_type_overrides:
if field_name in superclass.properties:
raise AssertionError(
u'Attempting to override field "{}" from class "{}", but the field is '
u'defined in superclass "{}"'
.format(field_name, class_name, superclass_name)) |
python | def inbox_count_for(user):
"""
returns the number of unread messages for the given user but does not
mark them seen
"""
return Message.objects.filter(recipient=user, read_at__isnull=True, recipient_deleted_at__isnull=True).count() |
java | private void RGBtoHSV(float red, float green, float blue) {
float min = 0;
float max = 0;
float delta = 0;
min = MIN(red, green, blue);
max = MAX(red, green, blue);
m_bri = max; // v
delta = max - min;
if (max != 0) {
m_sat = delta / max; // s
} else {
m_sat = 0;
m_hue = 0;
return;
}
if (delta == 0) {
m_hue = 0;
return;
}
if (red == max) {
m_hue = (green - blue) / delta;
} else if (green == max) {
m_hue = 2 + ((blue - red) / delta);
} else {
m_hue = 4 + ((red - green) / delta);
}
m_hue *= 60;
if (m_hue < 0) {
m_hue += 360;
}
} |
python | def main():
"""
NAME
fisher.py
DESCRIPTION
generates set of Fisher distribed data from specified distribution
INPUT (COMMAND LINE ENTRY)
OUTPUT
dec, inc
SYNTAX
fisher.py [-h] [-i] [command line options]
OPTIONS
-h prints help message and quits
-i for interactive entry
-k specify kappa as next argument, default is 20
-n specify N as next argument, default is 100
where:
kappa: fisher distribution concentration parameter
N: number of directions desired
"""
N,kappa=100,20
if '-h' in sys.argv:
print(main.__doc__)
sys.exit()
elif '-i' in sys.argv:
ans=input(' Kappa: ')
kappa=float(ans)
ans=input(' N: ')
N=int(ans)
else:
if '-k' in sys.argv:
ind=sys.argv.index('-k')
kappa=float(sys.argv[ind+1])
if '-n' in sys.argv:
ind=sys.argv.index('-n')
N=int(sys.argv[ind+1])
for k in range(N): spitout(kappa) |
java | public Generic onWildcard(Generic wildcard) {
return new OfWildcardType.Latent(wildcard.getUpperBounds().accept(this), wildcard.getLowerBounds().accept(this), wildcard);
} |
java | private void resetCorrectOffsets(ConsumerWorker worker) {
KafkaConsumer<String, Serializable> consumer = worker.consumer;
Map<String, List<PartitionInfo>> topicInfos = consumer.listTopics();
Set<String> topics = topicInfos.keySet();
List<String> expectTopics = new ArrayList<>(topicHandlers.keySet());
List<PartitionInfo> patitions = null;
consumer.poll(200);
for (String topic : topics) {
if(!expectTopics.contains(topic))continue;
patitions = topicInfos.get(topic);
for (PartitionInfo partition : patitions) {
try {
//期望的偏移
long expectOffsets = consumerContext.getLatestProcessedOffsets(topic, partition.partition());
//
TopicPartition topicPartition = new TopicPartition(partition.topic(), partition.partition());
OffsetAndMetadata metadata = consumer.committed(topicPartition);
Set<TopicPartition> assignment = consumer.assignment();
if(assignment.contains(topicPartition)){
if(expectOffsets > 0 && expectOffsets < metadata.offset()){
consumer.seek(topicPartition, expectOffsets);
//consumer.seekToBeginning(assignment);
logger.info(">>>>>>> seek Topic[{}] partition[{}] from {} to {}",topic, partition.partition(),metadata.offset(),expectOffsets);
}
}
} catch (Exception e) {
logger.warn("try seek topic["+topic+"] partition["+partition.partition()+"] offsets error");
}
}
}
consumer.resume(consumer.assignment());
} |
python | def nsummary(self,prn=None, lfilter=None):
"""prints a summary of each packet with the packet's number
prn: function to apply to each packet instead of lambda x:x.summary()
lfilter: truth function to apply to each packet to decide whether it will be displayed"""
for i, p in enumerate(self.res):
if lfilter is not None:
if not lfilter(p):
continue
print(conf.color_theme.id(i,fmt="%04i"), end = " ")
if prn is None:
print(self._elt2sum(p))
else:
print(prn(p)) |
python | def _parse_method_response(self, method_name, method_response, httpStatus):
'''
Helper function to construct the method response params, models, and integration_params
values needed to configure method response integration/mappings.
'''
method_response_models = {}
method_response_pattern = '.*'
if method_response.schema:
method_response_models['application/json'] = method_response.schema
method_response_pattern = self._get_pattern_for_schema(method_response.schema, httpStatus)
method_response_params = {}
method_integration_response_params = {}
for header in method_response.headers:
response_header = 'method.response.header.{0}'.format(header)
method_response_params[response_header] = False
header_data = method_response.headers.get(header)
method_integration_response_params[response_header] = (
"'{0}'".format(header_data.get('default')) if 'default' in header_data else "'*'")
response_templates = self._get_response_template(method_name, httpStatus)
return {'params': method_response_params,
'models': method_response_models,
'integration_params': method_integration_response_params,
'pattern': method_response_pattern,
'response_templates': response_templates} |
python | def set_scope(self, include=None, exclude=None):
"""
Sets `scope`, the "start point" for the audit.
Args:
include: A list of css selectors specifying the elements that
contain the portion of the page that should be audited.
Defaults to auditing the entire document.
exclude: This arg is not implemented in this ruleset.
Examples:
To check only the `div` with id `foo`::
page.a11y_audit.config.set_scope(["div#foo"])
To reset the scope to check the whole document::
page.a11y_audit.config.set_scope()
"""
if include:
self.scope = u"document.querySelector(\"{}\")".format(
u', '.join(include)
)
else:
self.scope = "null"
if exclude is not None:
raise NotImplementedError(
"The argument `exclude` has not been implemented in "
"AxsAuditConfig.set_scope method."
) |
java | public DocumentT findOneAndDelete(final Bson filter) {
return operations.findOneAndModify(
"findOneAndDelete",
filter,
new BsonDocument(),
new RemoteFindOneAndModifyOptions(),
documentClass).execute(service);
} |
java | public static String getBaseHash(Object object) {
return object.getClass().getSimpleName() + "@" + Integer.toString((new Object()).hashCode());
} |
java | public com.google.api.ads.adwords.axis.v201809.cm.AdCustomizerFeedAttribute[] getFeedAttributes() {
return feedAttributes;
} |
java | public Set<ArtifactSpec> getTransientDependencies() {
if (null == allTransient) {
allTransient = getTransientDependencies(true, true);
}
return allTransient;
} |
java | public Stroke getStroke() {
Stroke theStroke = stroke;
if (theStroke == null) {
theStroke = new BasicStroke(strokeWidth);
stroke = theStroke;
}
return theStroke;
} |
java | public static PrimitiveIterator.OfInt of(ThrowingIterator.OfInt<Nothing> itr) {
return of(itr, Nothing.class);
} |
java | public static File toFile(final URL aURL) throws MalformedURLException {
if (aURL.getProtocol().equals(FILE_TYPE)) {
return new File(aURL.toString().replace("file:", ""));
}
throw new MalformedURLException(LOGGER.getI18n(MessageCodes.UTIL_036, aURL));
} |
java | public static ChromPos getChromPosForward(int cdsPos, List<Integer> exonStarts, List<Integer> exonEnds, int cdsStart, int cdsEnd) {
boolean inCoding = false;
int codingLength = 0;
@SuppressWarnings("unused")
int lengthExons = 0;
// map forward
for (int i = 0; i < exonStarts.size(); i++) {
// start can include UTR
int start = exonStarts.get(i);
int end = exonEnds.get(i);
lengthExons += end - start;
if (start <= cdsStart +1 && end >= cdsStart+1) {
// first exon with UTR
if (codingLength + (end - cdsStart-1) >= cdsPos) {
// we are reaching our target position
int tmp = cdsPos - codingLength;
logger.debug(cdsStart + " | " + codingLength + " | " + tmp);
logger.debug(" -> found position in UTR exon: #"+(i+1)+ " cdsPos:" + cdsPos +
" return:"+(cdsStart +1 + tmp) +" start:" + format(start + 1) + " " + format(tmp) + " " + cdsStart + " " + codingLength);
// we start 1 after cdsStart...
return new ChromPos((cdsStart +1 + tmp),-1);
}
inCoding = true;
codingLength += (end - cdsStart);
logger.debug(" UTR : " + format(start+1) + " - " + (cdsStart ));
logger.debug(" -> Exon : " + format(cdsStart+1) + " - " + format(end) + " | " + format(end - cdsStart) + " | " + codingLength + " | " + (codingLength % 3));
} else if (start+1 <= cdsEnd && end >= cdsEnd) {
// LAST EXON with UTR
//logger.debug(" <-- CDS end at: " + cdsEnd );
inCoding = false;
if (codingLength + (cdsEnd - start-1) >= cdsPos) {
int tmp = cdsPos - codingLength;
logger.debug(" <- Exon : " + format(start+1) + " - " + format(cdsEnd) + " | " + format(cdsEnd - start) + " | " + codingLength + " | " + (codingLength % 3));
logger.debug(" UTR : " + format(cdsEnd + 1) + " - " + format(end));
logger.debug( codingLength + " | " + tmp + " | " + format(start+1));
logger.debug(" -> chromPosForward found position in non coding exon: " + cdsPos + " " + format(start+1) + " " + format(tmp) + " " + format(cdsStart) + " " + codingLength);
return new ChromPos((start +1 + tmp),cdsPos%3);
}
codingLength += (cdsEnd - start-1);
logger.debug(" <- Exon : " + format(start+1) + " - " + format(cdsEnd) + " | " + format(cdsEnd - start) + " | " + codingLength + " | " + (codingLength % 3));
logger.debug(" UTR : " + format(cdsEnd + 1) + " - " + format(end));
} else if (inCoding) {
// A standard coding Exon
// tests for the maximum length of this coding exon
if (codingLength + (end - start -1) >= cdsPos) {
// we are within the range of this exon
int tmp = cdsPos - codingLength ;
logger.debug(" Exon : " + format(start+1) + " - " + format(end) + " | " + format(end - start) + " | " + tmp + " | " + codingLength);
logger.debug(" -> found chr position in coding exon #" + (i+1) + ": cdsPos:" + format(cdsPos) + " s:" + format(start) + "-" + format(end) + " tmp:" + format(tmp) + " cdsStart:" + format(cdsStart) + " codingLength:" + codingLength);
return new ChromPos((start +1 + tmp),cdsPos%3);
}
// full exon is coding
codingLength += (end - start );
logger.debug(" Exon : " + format(start+1) + " - " + format(end) + " | " + format(end - start) + " | " + codingLength + " | " + (codingLength % 3));
}
}
return new ChromPos(-1,-1);
} |
python | def create_char(self, location, pattern):
"""Fill one of the first 8 CGRAM locations with custom characters.
The location parameter should be between 0 and 7 and pattern should
provide an array of 8 bytes containing the pattern. E.g. you can easyly
design your custom character at http://www.quinapalus.com/hd44780udg.html
To show your custom character use eg. lcd.message('\x01')
"""
# only position 0..7 are allowed
location &= 0x7
self.write8(LCD_SETCGRAMADDR | (location << 3))
for i in range(8):
self.write8(pattern[i], char_mode=True) |
python | def run_file(path):
"""Run a module from a path and return its variables."""
if PY26:
dirpath, name, _ = splitname(path)
found = imp.find_module(name, [dirpath])
module = imp.load_module("__main__", *found)
return vars(module)
else:
return runpy.run_path(path, run_name="__main__") |
python | def update(self, date, data=None, inow=None):
"""
Update strategy. Updates prices, values, weight, etc.
"""
# resolve stale state
self.root.stale = False
# update helpers on date change
# also set newpt flag
newpt = False
if self.now == 0:
newpt = True
elif date != self.now:
self._net_flows = 0
self._last_price = self._price
self._last_value = self._value
self._last_fee = 0.0
newpt = True
# update now
self.now = date
if inow is None:
if self.now == 0:
inow = 0
else:
inow = self.data.index.get_loc(date)
# update children if any and calculate value
val = self._capital # default if no children
if self.children is not None:
for c in self._childrenv:
# avoid useless update call
if c._issec and not c._needupdate:
continue
c.update(date, data, inow)
val += c.value
if self.root == self:
if (val < 0) and not self.bankrupt:
# Declare a bankruptcy
self.bankrupt = True
self.flatten()
# update data if this value is different or
# if now has changed - avoid all this if not since it
# won't change
if newpt or self._value != val:
self._value = val
self._values.values[inow] = val
bottom = self._last_value + self._net_flows
if bottom != 0:
ret = self._value / (self._last_value + self._net_flows) - 1
else:
if self._value == 0:
ret = 0
else:
raise ZeroDivisionError(
'Could not update %s. Last value '
'was %s and net flows were %s. Current'
'value is %s. Therefore, '
'we are dividing by zero to obtain the return '
'for the period.' % (self.name,
self._last_value,
self._net_flows,
self._value))
self._price = self._last_price * (1 + ret)
self._prices.values[inow] = self._price
# update children weights
if self.children is not None:
for c in self._childrenv:
# avoid useless update call
if c._issec and not c._needupdate:
continue
if val != 0:
c._weight = c.value / val
else:
c._weight = 0.0
# if we have strategy children, we will need to update them in universe
if self._has_strat_children:
for c in self._strat_children:
# TODO: optimize ".loc" here as well
self._universe.loc[date, c] = self.children[c].price
# Cash should track the unallocated capital at the end of the day, so
# we should update it every time we call "update".
# Same for fees
self._cash.values[inow] = self._capital
self._fees.values[inow] = self._last_fee
# update paper trade if necessary
if newpt and self._paper_trade:
self._paper.update(date)
self._paper.run()
self._paper.update(date)
# update price
self._price = self._paper.price
self._prices.values[inow] = self._price |
java | @SuppressWarnings("deprecation")
private void addGalleriesForType(Map<String, CmsGalleryTypeInfo> galleryTypeInfos, String typeName)
throws CmsLoaderException {
I_CmsResourceType contentType = getResourceManager().getResourceType(typeName);
for (I_CmsResourceType galleryType : contentType.getGalleryTypes()) {
if (galleryTypeInfos.containsKey(galleryType.getTypeName())) {
CmsGalleryTypeInfo typeInfo = galleryTypeInfos.get(galleryType.getTypeName());
typeInfo.addContentType(contentType);
} else {
CmsGalleryTypeInfo typeInfo;
typeInfo = new CmsGalleryTypeInfo(
galleryType,
contentType,
getGalleriesByType(galleryType.getTypeId()));
galleryTypeInfos.put(galleryType.getTypeName(), typeInfo);
}
}
} |
java | public void setTargetGroupInfoList(java.util.Collection<TargetGroupInfo> targetGroupInfoList) {
if (targetGroupInfoList == null) {
this.targetGroupInfoList = null;
return;
}
this.targetGroupInfoList = new com.amazonaws.internal.SdkInternalList<TargetGroupInfo>(targetGroupInfoList);
} |
java | public Request releaseRequest(Thread thread) {
int threadId = thread.hashCode();
synchronized (requestsByThreadId) {
StandardRequest request = (StandardRequest) requestsByThreadId.get(threadId);
if (request != null) {
if (request.getTimesEntered() > 0) {
request.decreaseTimesEntered();
} else {
requestsByThreadId.remove(threadId);
}
return request;
}
}
return null;
} |
java | @RequestMapping(value = "project-sync/{projectId}", method = RequestMethod.GET)
public GitSynchronisationInfo getProjectGitSyncInfo(@PathVariable ID projectId) {
Project project = structureService.getProject(projectId);
return gitService.getProjectGitSyncInfo(project);
} |
java | @Override
public synchronized void free(Page page) {
if (page.isFreeable()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Freeing a {}B buffer from chunk {} &{}", DebuggingUtils.toBase2SuffixedString(page.size()), page.index(), page.address());
}
markAllAvailable();
sliceAllocators.get(page.index()).free(page.address(), page.size());
victims.get(page.index()).remove(page);
victimAllocators.get(page.index()).tryFree(page.address(), page.size());
if (!fallingThresholds.isEmpty()) {
long allocated = getAllocatedSize();
fireThresholds(allocated + page.size(), allocated);
}
}
} |
python | def _get_real_ip(self):
"""
Get IP from request.
:param request: A usual request object
:type request: HttpRequest
:return: ipv4 string or None
"""
try:
# Trying to work with most common proxy headers
real_ip = self.request.META['HTTP_X_FORWARDED_FOR']
return real_ip.split(',')[0]
except KeyError:
return self.request.META['REMOTE_ADDR']
except Exception:
# Unknown IP
return None |
java | public void marshall(ExecutionStartedEventDetails executionStartedEventDetails, ProtocolMarshaller protocolMarshaller) {
if (executionStartedEventDetails == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(executionStartedEventDetails.getInput(), INPUT_BINDING);
protocolMarshaller.marshall(executionStartedEventDetails.getRoleArn(), ROLEARN_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
python | def stop_all(self):
"""
Stop all nodes
"""
pool = Pool(concurrency=3)
for node in self.nodes.values():
pool.append(node.stop)
yield from pool.join() |
java | private void writeConstructor(GinjectorBindings bindings, SourceWriteUtil sourceWriteUtil,
SourceWriter writer) {
String implClassName = ginjectorNameGenerator.getClassName(bindings);
if (bindings.getParent() == null) {
// In outputInterfaceField, we verify that we have a bound injector if we
// are the root module, so this should never be null:
Class<?> boundGinjector = getBoundGinjector(bindings);
String interfaceCanonicalClassName = boundGinjector.getCanonicalName();
String fieldName = bindings.getNameGenerator().getGinjectorInterfaceFieldName();
sourceWriteUtil.writeMethod(writer,
String.format("public %s(%s %s)", implClassName, interfaceCanonicalClassName, fieldName),
String.format("this.%1$s = %1$s;", fieldName));
} else {
String parentImplCanonicalClassName = ginjectorNameGenerator.getCanonicalClassName(
bindings.getParent());
writer.print(String.format("private final %s parent;\n", parentImplCanonicalClassName));
sourceWriteUtil.writeMethod(writer, String.format("public %s getParent()",
parentImplCanonicalClassName), "return parent;");
sourceWriteUtil.writeMethod(writer, String.format("public %1$s(%2$s parent)",
implClassName, parentImplCanonicalClassName), "this.parent = parent;");
}
} |
java | protected boolean isConfigLocation(URI location) {
String scheme = location.getScheme();
if (scheme == null) {
// interpret as place holder
try {
String resolvedPlaceholder = getProperty(location.getRawSchemeSpecificPart());
if (resolvedPlaceholder == null) {
return false;
}
location = new URI(resolvedPlaceholder);
scheme = location.getScheme();
} catch (URISyntaxException e) {
return false;
}
}
return (scheme != null && SUPPORTED_SCHEMES.contains(scheme.toLowerCase(StringUtil.LOCALE_INTERNAL)));
} |
python | def add_librispeech_hparams(hparams):
"""Adding to base hparams the attributes for for librispeech."""
hparams.batch_size = 36
hparams.audio_compression = 8
hparams.hidden_size = 2048
hparams.max_input_seq_length = 600000
hparams.max_target_seq_length = 350
hparams.max_length = hparams.max_input_seq_length
hparams.min_length_bucket = hparams.max_input_seq_length // 2
hparams.learning_rate = 0.05
hparams.train_steps = 5000000
hparams.num_hidden_layers = 4
return hparams |
python | def migrate_autoload_details(autoload_details, shell_name, shell_type):
""" Migrate autoload details. Add namespace for attributes
:param autoload_details:
:param shell_name:
:param shell_type:
:return:
"""
mapping = {}
for resource in autoload_details.resources:
resource.model = "{shell_name}.{model}".format(shell_name=shell_name, model=resource.model)
mapping[resource.relative_address] = resource.model
for attribute in autoload_details.attributes:
if not attribute.relative_address: # Root element
attribute.attribute_name = "{shell_type}.{attr_name}".format(shell_type=shell_type,
attr_name=attribute.attribute_name)
else:
attribute.attribute_name = "{model}.{attr_name}".format(model=mapping[attribute.relative_address],
attr_name=attribute.attribute_name)
return autoload_details |
python | def from_csv(cls, filename):
"""Create gyro stream from CSV data
Load data from a CSV file.
The data must be formatted with three values per line: (x, y, z)
where x, y, z is the measured angular velocity (in radians) of the specified axis.
Parameters
-------------------
filename : str
Path to the CSV file
Returns
---------------------
GyroStream
A gyroscope stream
"""
instance = cls()
instance.data = np.loadtxt(filename, delimiter=',')
return instance |
java | public void marshall(FailWorkflowExecutionDecisionAttributes failWorkflowExecutionDecisionAttributes, ProtocolMarshaller protocolMarshaller) {
if (failWorkflowExecutionDecisionAttributes == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(failWorkflowExecutionDecisionAttributes.getReason(), REASON_BINDING);
protocolMarshaller.marshall(failWorkflowExecutionDecisionAttributes.getDetails(), DETAILS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
python | def audit_trail_users(self):
'''A set of all usernames recorded in the :attr:`audit_trail`,
if available.'''
if self.audit_trail:
return set([r.user for r in self.audit_trail.records])
return set() |
java | public static float[] asFloatTypeArray(List<Float> input) {
float[] result = new float[input.size()];
for (int i = 0; i < result.length; i++) {
result[i] = input.get(i);
}
return result;
} |
java | public void copyToMasterPrimaryKey(Storable reference, S master) throws FetchException {
try {
mCopyToMasterPkMethod.invoke(reference, master);
} catch (Exception e) {
ThrowUnchecked.fireFirstDeclaredCause(e, FetchException.class);
}
} |
java | private RowKeyBuilder initializeRowKeyBuilder() {
RowKeyBuilder builder = new RowKeyBuilder();
if ( hasIdentifier ) {
builder.addColumns( getIdentifierColumnName() );
}
else {
builder.addColumns( getKeyColumnNames() );
// !isOneToMany() present in delete not in update
if ( !isOneToMany() && hasIndex && !indexContainsFormula ) {
builder.addIndexColumns( getIndexColumnNames() );
}
else {
builder.addColumns( getElementColumnNames() );
}
}
return builder;
} |
java | public static byte[] toByteArray(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
ByteArrayOutputStream out = null;
try {
out = new ByteArrayOutputStream();
bitmap.compress(format, quality, out);
return out.toByteArray();
} finally {
CloseableUtils.close(out);
}
} |
java | @Override
public boolean hasStableIds() {
Collection<? extends Binder<?, ?>> allBinders = getAllBinders();
if (allBinders.size() == 1) {
// Save an allocation by checking for List first.
if (allBinders instanceof List) {
//noinspection unchecked
return ((List<Binder<?, ?>>) allBinders).get(0).hasStableIds();
}
return allBinders.iterator().next().hasStableIds();
}
// Can't possibly have stable IDs if we have multiple binders.
return false;
} |
java | public com.google.api.ads.adwords.axis.v201809.o.StatsEstimate getMaxEstimate() {
return maxEstimate;
} |
java | public static Point multiply(Point p, BigInteger k) {
BigInteger e = k;
BigInteger h = e.multiply(BigInteger.valueOf(3));
Point neg = p.negate();
Point R = p;
for (int i = h.bitLength() - 2; i > 0; --i) {
R = R.twice();
boolean hBit = h.testBit(i);
boolean eBit = e.testBit(i);
if (hBit != eBit) {
R = R.add(hBit ? p : neg);
}
}
return R;
} |
python | def main(args=None):
"""Call the CLI interface and wait for the result."""
retcode = 0
try:
ci = CliInterface()
args = ci.parser.parse_args()
result = args.func(args)
if result is not None:
print(result)
retcode = 0
except Exception:
retcode = 1
traceback.print_exc()
sys.exit(retcode) |
java | @Nullable
@Override
public String apply(@Nullable String key)
{
if (NullHandling.isNullOrEquivalent(key)) {
return null;
}
return key.toLowerCase(locale);
} |
python | def federation_payment(self,
fed_address,
amount,
asset_code='XLM',
asset_issuer=None,
source=None,
allow_http=False):
"""Append a :class:`Payment <stellar_base.operation.Payment>` operation
to the list of operations using federation on the destination address.
Translates the destination stellar address to an account ID via
:func:`federation <stellar_base.federation.federation>`, before
creating a new payment operation via :meth:`append_payment_op`.
:param str fed_address: A Stellar Address that needs to be translated
into a valid account ID via federation.
:param str amount: The amount of the currency to send in the payment.
:param str asset_code: The asset code for the asset to send.
:param str asset_issuer: The address of the issuer of the asset.
:param str source: The source address of the payment.
:param bool allow_http: When set to `True`, connections to insecure http protocol federation servers
will be allowed. Must be set to `False` in production. Default: `False`.
:return: This builder instance.
"""
fed_info = federation(
address_or_id=fed_address, fed_type='name', allow_http=allow_http)
if not fed_info or not fed_info.get('account_id'):
raise FederationError(
'Cannot determine Stellar Address to Account ID translation '
'via Federation server.')
self.append_payment_op(fed_info['account_id'], amount, asset_code,
asset_issuer, source)
memo_type = fed_info.get('memo_type')
if memo_type is not None and memo_type in ('text', 'id', 'hash'):
getattr(self, 'add_' + memo_type.lower() + '_memo')(fed_info['memo']) |
java | public With andWith(final String alias, final Expression expression) {
this.clauses.add(new ImmutablePair<>(new Name(alias), expression));
return this;
} |
java | public void buildMethodDetails(XMLNode node,
Content memberDetailsTree) throws DocletException {
configuration.getBuilderFactory().
getMethodBuilder(writer).buildChildren(node, memberDetailsTree);
} |
python | def __remove_handler_factory(self, svc_ref):
# type: (ServiceReference) -> None
"""
Removes an handler factory
:param svc_ref: ServiceReference of the handler factory to remove
"""
with self.__handlers_lock:
# Get the handler ID
handler_id = svc_ref.get_property(handlers_const.PROP_HANDLER_ID)
# Check if this is the handler we use
if svc_ref not in self._handlers_refs:
return
# Clean up
self.__context.unget_service(svc_ref)
self._handlers_refs.remove(svc_ref)
del self._handlers[handler_id]
# List the components using this handler
to_stop = set() # type: Set[StoredInstance]
for factory_name in self.__factories:
_, factory_context = self.__get_factory_with_context(
factory_name
)
if handler_id in factory_context.get_handlers_ids():
to_stop.update(self.__get_stored_instances(factory_name))
with self.__instances_lock:
for stored_instance in to_stop:
# Extract information
context = stored_instance.context
name = context.name
instance = stored_instance.instance
# Clean up the stored instance (iPOPO side)
del self.__instances[name]
stored_instance.kill()
# Add the component to the waiting queue
self.__waiting_handlers[name] = (context, instance)
# Try to find a new handler factory
new_ref = self.__context.get_service_reference(
handlers_const.SERVICE_IPOPO_HANDLER_FACTORY,
"({0}={1})".format(handlers_const.PROP_HANDLER_ID, handler_id),
)
if new_ref is not None:
self.__add_handler_factory(new_ref) |
java | protected void reset()
{
this.active = false;
synchronized (this.cachedChannelsNonTransactional)
{
for (ChannelProxy channel : this.cachedChannelsNonTransactional)
{
try
{
channel.getTargetChannel().close();
}
catch (Throwable ex)
{
this.logger.trace("Could not close cached Rabbit Channel", ex);
}
}
this.cachedChannelsNonTransactional.clear();
}
synchronized (this.cachedChannelsTransactional)
{
for (ChannelProxy channel : this.cachedChannelsTransactional)
{
try
{
channel.getTargetChannel().close();
}
catch (Throwable ex)
{
this.logger.trace("Could not close cached Rabbit Channel", ex);
}
}
this.cachedChannelsTransactional.clear();
}
this.active = true;
} |
java | private void parseRange() throws BadThresholdException {
PushbackReader reader = new PushbackReader(new StringReader(thresholdString));
StringBuilder currentParsedBuffer = new StringBuilder();
byte b;
try {
while ((b = (byte) reader.read()) != -1) {
currentParsedBuffer.append((char) b);
if (b == '@') {
if (curState != MINVAL) {
throw new BadThresholdException("Unparsable threshold '" + thresholdString + "'. Error at char "
+ currentParsedBuffer.length() + ": the '@' should not be there.");
}
negateThreshold = true;
continue;
}
if (b == ':') {
switch (curState) {
case MINVAL:
if (minVal == null) {
minVal = new BigDecimal(0);
}
curState = MAXVAL;
currentParsedBuffer = new StringBuilder();
continue;
case MAXVAL:
throw new BadThresholdException("Unparsable threshold '" + thresholdString + "'. Error at char "
+ currentParsedBuffer.length() + ": the ':' should not be there.");
// m_iCurState = END;
// continue;
default:
curState = MAXVAL;
}
}
if (b == '~') {
switch (curState) {
case MINVAL:
minVal = new BigDecimal(Integer.MIN_VALUE);
currentParsedBuffer = new StringBuilder();
// m_iCurState = MAXVAL;
continue;
case MAXVAL:
maxVal = new BigDecimal(Integer.MAX_VALUE);
curState = END;
currentParsedBuffer = new StringBuilder();
continue;
default:
}
}
StringBuilder numberBuffer = new StringBuilder();
// while (i < vBytes.length &&
// Character.isDigit((char)vBytes[i]))
do {
numberBuffer.append((char) b);
} while (((b = (byte) reader.read()) != -1) && (Character.isDigit((char) b) || b == '+' || b == '-' || b == '.'));
if (b != -1) {
reader.unread(b);
}
String numberString = numberBuffer.toString();
if (numberString.trim().length() == 0 || "+".equals(numberString) || "-".equals(numberString)) {
throw new BadThresholdException("A number was expected after '" + currentParsedBuffer.toString()
+ "', but an empty string was found");
}
switch (curState) {
case MINVAL:
try {
minVal = new BigDecimal(numberString.trim());
} catch (NumberFormatException nfe) {
throw new BadThresholdException("Expected a number but found '" + numberString + "' instead [" + thresholdString + "]", nfe);
}
currentParsedBuffer = new StringBuilder();
continue;
case MAXVAL:
try {
maxVal = new BigDecimal(numberString.trim());
} catch (NumberFormatException nfe) {
throw new BadThresholdException("Expected a number but found '" + numberString + "' instead", nfe);
}
currentParsedBuffer = new StringBuilder();
continue;
default:
curState = END;
currentParsedBuffer = new StringBuilder();
}
// if (i < vBytes.length)
// i-=2;
}
} catch (IOException ioe) {
// Intentionally empty...
}
if (curState == MINVAL) {
maxVal = minVal;
minVal = new BigDecimal(0);
}
if (curState == MAXVAL && maxVal == null && !thresholdString.isEmpty() && thresholdString.charAt(0) == ':') {
throw new BadThresholdException("At least one of maximum or minimum " + "value must me specified (" + thresholdString + ")");
}
} |
java | public static BizuinInfoResult getCardBizuinInfo(String access_token, BizuinInfo bizuinCube) {
return getCardBizuinInfo(access_token, JsonUtil.toJSONString(bizuinCube));
} |
java | public double getColorPercentage(Area node)
{
int tlen = 0;
double sum = 0;
for (Box box : node.getBoxes())
{
int len = letterLength(box.getText());
if (len > 0)
{
sum += getColorPercentage(box.getColor()) * len;
tlen += len;
}
}
for (int i = 0; i < node.getChildCount(); i++)
{
Area child = node.getChildAt(i);
int nlen = letterLength(child.getText());
tlen += nlen;
sum += getColorPercentage(child) * nlen;
}
if (tlen == 0)
return 0;
else
return sum / tlen;
} |
java | public int getOffset(int era, int year, int month,int dom, int dow, int millis, int monthLength){
if ((era != GregorianCalendar.AD && era != GregorianCalendar.BC)
|| month < Calendar.JANUARY
|| month > Calendar.DECEMBER
|| dom < 1
|| dom > monthLength
|| dow < Calendar.SUNDAY
|| dow > Calendar.SATURDAY
|| millis < 0
|| millis >= Grego.MILLIS_PER_DAY
|| monthLength < 28
|| monthLength > 31) {
throw new IllegalArgumentException();
}
if (era == GregorianCalendar.BC) {
year = -year;
}
if (finalZone != null && year >= finalStartYear) {
return finalZone.getOffset(era, year, month, dom, dow, millis);
}
// Compute local epoch millis from input fields
long time = Grego.fieldsToDay(year, month, dom) * Grego.MILLIS_PER_DAY + millis;
int[] offsets = new int[2];
getHistoricalOffset(time, true, LOCAL_DST, LOCAL_STD, offsets);
return offsets[0] + offsets[1];
} |
python | def match(path, glob):
"""Match the path with the glob.
Arguments:
path -- A list of keys representing the path.
glob -- A list of globs to match against the path.
"""
path_len = len(path)
glob_len = len(glob)
ss = -1
ss_glob = glob
if '**' in glob:
ss = glob.index('**')
if '**' in glob[ss + 1:]:
raise dpath.exceptions.InvalidGlob("Invalid glob. Only one '**' is permitted per glob.")
if path_len >= glob_len:
# Just right or more stars.
more_stars = ['*'] * (path_len - glob_len + 1)
ss_glob = glob[:ss] + more_stars + glob[ss + 1:]
elif path_len == glob_len - 1:
# Need one less star.
ss_glob = glob[:ss] + glob[ss + 1:]
if path_len == len(ss_glob):
# Python 3 support
if PY3:
return all(map(fnmatch.fnmatch, list(map(str, paths_only(path))), list(map(str, ss_glob))))
else: # Default to Python 2
return all(map(fnmatch.fnmatch, map(str, paths_only(path)), map(str, ss_glob)))
return False |
java | private void addHighlights(Collection<? extends Point> points, Color color)
{
removeHighlights(points);
Map<Point, Object> newHighlights =
JTextComponents.addHighlights(textComponent, points, color);
highlights.putAll(newHighlights);
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.