language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
|---|---|
python
|
def stageContent(self, configFiles, dateTimeFormat=None):
"""Parses a JSON configuration file to stage content.
Args:
configFiles (list): A list of JSON files on disk containing
configuration data for staging content.
dateTimeFormat (str): A valid date formatting directive, as understood
by :py:meth:`datetime.datetime.strftime`. Defaults to ``None``, i.e.,
``'%Y-%m-%d %H:%M'``.
"""
results = None
groups = None
items = None
group = None
content = None
contentInfo = None
startTime = None
orgTools = None
if dateTimeFormat is None:
dateTimeFormat = '%Y-%m-%d %H:%M'
scriptStartTime = datetime.datetime.now()
try:
print ("********************Stage Content Started********************")
print ("Script started at %s" % scriptStartTime.strftime(dateTimeFormat))
if self.securityhandler.valid == False:
print ("Login required")
else:
orgTools = orgtools.orgtools(securityinfo=self)
if orgTools is None:
print ("Error creating org tools")
else:
for configFile in configFiles:
config = common.init_config_json(config_file=configFile)
if config is not None:
if 'ContentItems' in config:
startTime = datetime.datetime.now()
print ("Processing config %s, starting at: %s" % (configFile,startTime.strftime(dateTimeFormat)))
contentInfo = config['ContentItems']
for cont in contentInfo:
content = cont['Content']
group = cont['ShareToGroup']
print ("Sharing content to: %s" % group)
if os.path.isfile(content):
with open(content, 'rb') as csvfile:
items = []
groups = []
for row in csv.DictReader(csvfile,dialect='excel'):
if cont['Type'] == "Group":
groups.append(row['id'])
elif cont['Type'] == "Items":
items.append(row['id'])
results = orgTools.shareItemsToGroup(shareToGroupName=group,items=items,groups=groups)
print ("Config %s completed, time to complete: %s" % (configFile, str(datetime.datetime.now() - startTime)))
else:
print ("Config file missing ContentItems section")
else:
print ("Config %s not found" % configFile)
except(TypeError,ValueError,AttributeError) as e:
print (e)
except (common.ArcRestHelperError) as e:
print ("error in function: %s" % e[0]['function'])
print ("error on line: %s" % e[0]['line'])
print ("error in file name: %s" % e[0]['filename'])
print ("with error message: %s" % e[0]['synerror'])
if 'arcpyError' in e[0]:
print ("with arcpy message: %s" % e[0]['arcpyError'])
except Exception as e:
if (reportToolsInstalled):
if isinstance(e,(ReportTools.ReportToolsError,DataPrep.DataPrepError)):
print ("error in function: %s" % e[0]['function'])
print ("error on line: %s" % e[0]['line'])
print ("error in file name: %s" % e[0]['filename'])
print ("with error message: %s" % e[0]['synerror'])
if 'arcpyError' in e[0]:
print ("with arcpy message: %s" % e[0]['arcpyError'])
else:
line, filename, synerror = trace()
print ("error on line: %s" % line)
print ("error in file name: %s" % filename)
print ("with error message: %s" % synerror)
else:
line, filename, synerror = trace()
print ("error on line: %s" % line)
print ("error in file name: %s" % filename)
print ("with error message: %s" % synerror)
finally:
print ("Script complete, time to complete: %s" % str(datetime.datetime.now() - scriptStartTime))
print ("###############Stage Content Completed#################")
print ("")
#if orgTools is not None:
#orgTools.dispose()
results = None
groups = None
items = None
group = None
content = None
contentInfo = None
startTime = None
orgTools = None
del results
del groups
del items
del group
del content
del contentInfo
del startTime
del orgTools
gc.collect()
|
java
|
private int insertFromBlockingEvent(final Collection<UUID> allEntitlementUUIDs, final BlockingState currentBlockingState, final List<SubscriptionEvent> inputExistingEvents, final SupportForOlderVersionThan_0_17_X backwardCompatibleContext, final InternalTenantContext internalTenantContext, final Collection<SubscriptionEvent> outputNewEvents) {
// Keep the current state per entitlement
final Map<UUID, TargetState> targetStates = new HashMap<UUID, TargetState>();
for (final UUID cur : allEntitlementUUIDs) {
targetStates.put(cur, new TargetState());
}
//
// Find out where to insert next event, and calculate current state for each entitlement at the position where we stop.
//
int index = -1;
final Iterator<SubscriptionEvent> it = inputExistingEvents.iterator();
// Where we need to insert in that stream
DefaultSubscriptionEvent curInsertion = null;
while (it.hasNext()) {
final DefaultSubscriptionEvent cur = (DefaultSubscriptionEvent) it.next();
final int compEffectiveDate = currentBlockingState.getEffectiveDate().compareTo(cur.getEffectiveDateTime());
final boolean shouldContinue;
switch (compEffectiveDate) {
case -1:
shouldContinue = false;
break;
case 0:
shouldContinue = compareBlockingStateWithNextSubscriptionEvent(currentBlockingState, cur) > 0;
break;
case 1:
shouldContinue = true;
break;
default:
// Make compiler happy
throw new IllegalStateException("Cannot reach statement");
}
if (!shouldContinue) {
break;
}
index++;
final TargetState curTargetState = targetStates.get(cur.getEntitlementId());
switch (cur.getSubscriptionEventType()) {
case START_ENTITLEMENT:
curTargetState.setEntitlementStarted();
break;
case STOP_ENTITLEMENT:
curTargetState.setEntitlementStopped();
break;
case START_BILLING:
// For older subscriptions we miss the START_ENTITLEMENT (the START_BILLING marks both start of billing and entitlement)
if (backwardCompatibleContext.isOlderEntitlement(cur.getEntitlementId())) {
curTargetState.setEntitlementStarted();
}
curTargetState.setBillingStarted();
break;
case PAUSE_BILLING:
case PAUSE_ENTITLEMENT:
case RESUME_ENTITLEMENT:
case RESUME_BILLING:
case SERVICE_STATE_CHANGE:
curTargetState.addEntitlementEvent(cur);
break;
case STOP_BILLING:
curTargetState.setBillingStopped();
break;
}
curInsertion = cur;
}
// Extract the list of targets based on the type of blocking state
final List<UUID> targetEntitlementIds = currentBlockingState.getType() == BlockingStateType.SUBSCRIPTION ? ImmutableList.<UUID>of(currentBlockingState.getBlockedId()) :
ImmutableList.<UUID>copyOf(allEntitlementUUIDs);
// For each target compute the new events that should be inserted in the stream
for (final UUID targetEntitlementId : targetEntitlementIds) {
final SubscriptionEvent[] prevNext = findPrevNext(inputExistingEvents, targetEntitlementId, curInsertion);
final TargetState curTargetState = targetStates.get(targetEntitlementId);
final List<SubscriptionEventType> eventTypes = curTargetState.addStateAndReturnEventTypes(currentBlockingState);
for (final SubscriptionEventType t : eventTypes) {
outputNewEvents.add(toSubscriptionEvent(prevNext[0], prevNext[1], targetEntitlementId, currentBlockingState, t, internalTenantContext));
}
}
return index;
}
|
java
|
public Node createProxyNode(Object sourceNodeId, Object targetNodeId, GraphDatabaseService graphDb,
EntityMetadata sourceEntityMetadata, EntityMetadata targetEntityMetadata)
{
String sourceNodeIdColumnName = ((AbstractAttribute) sourceEntityMetadata.getIdAttribute()).getJPAColumnName();
String targetNodeIdColumnName = ((AbstractAttribute) targetEntityMetadata.getIdAttribute()).getJPAColumnName();
Node node = graphDb.createNode();
node.setProperty(PROXY_NODE_TYPE_KEY, PROXY_NODE_VALUE);
node.setProperty(sourceNodeIdColumnName, sourceNodeId);
node.setProperty(targetNodeIdColumnName, targetNodeId);
return node;
}
|
python
|
def findcorrectionhandling(self, cls):
"""Find the proper correctionhandling given a textclass by looking in the underlying corrections where it is reused"""
if cls == "current":
return CorrectionHandling.CURRENT
elif cls == "original":
return CorrectionHandling.ORIGINAL #backward compatibility
else:
correctionhandling = None
#but any other class may be anything
#Do we have corrections at all? otherwise no need to bother
for correction in self.select(Correction):
#yes, in which branch is the text class found?
found = False
hastext = False
if correction.hasnew():
found = True
doublecorrection = correction.new().count(Correction) > 0
if doublecorrection: return None #skipping text validation, correction is too complex (nested) to handle for now
for t in correction.new().select(TextContent):
hastext = True
if t.cls == cls:
if correctionhandling is not None and correctionhandling != CorrectionHandling.CURRENT:
return None #inconsistent
else:
correctionhandling = CorrectionHandling.CURRENT
break
elif correction.hascurrent():
found = True
doublecorrection = correction.current().count(Correction) > 0
if doublecorrection: return None #skipping text validation, correction is too complex (nested) to handle for now
for t in correction.current().select(TextContent):
hastext = True
if t.cls == cls:
if correctionhandling is not None and correctionhandling != CorrectionHandling.CURRENT:
return None #inconsistent
else:
correctionhandling = CorrectionHandling.CURRENT
break
if correction.hasoriginal():
found = True
doublecorrection = correction.original().count(Correction) > 0
if doublecorrection: return None #skipping text validation, correction is too complex (nested) to handle for now
for t in correction.original().select(TextContent):
hastext = True
if t.cls == cls:
if correctionhandling is not None and correctionhandling != CorrectionHandling.ORIGINAL:
return None #inconsistent
else:
correctionhandling = CorrectionHandling.ORIGINAL
break
if correctionhandling is None:
#well, we couldn't find our textclass in any correction, just fall back to current and let text validation fail if needed
return CorrectionHandling.CURRENT
|
java
|
public int replace(final K key, final int value)
{
int curValue = getValue(key);
if (curValue != missingValue)
{
curValue = put(key, value);
}
return curValue;
}
|
java
|
public void setMinusSignString(String minusSignString) {
if (minusSignString == null) {
throw new NullPointerException("The input minus sign is null");
}
this.minusString = minusSignString;
if (minusSignString.length() == 1) {
this.minusSign = minusSignString.charAt(0);
} else {
// Use the default minus sign as fallback
this.minusSign = DEF_MINUS_SIGN;
}
}
|
java
|
public static <C extends Page> String absoluteUrlFor(final Class<C> page,
final PageParameters parameters, final boolean withServerPort)
{
final StringBuilder url = new StringBuilder();
url.append(WicketUrlExtensions.getDomainUrl(withServerPort));
url.append(WicketUrlExtensions.getBaseUrl(page, parameters).canonical().toString());
return url.toString();
}
|
python
|
def init(self): # pylint: disable=too-many-branches
"""Called by the daemon broker to initialize the module"""
if not self.enabled:
logger.info(" the module is disabled.")
return True
try:
connections = self.test_connection()
except Exception as exp: # pylint: disable=broad-except
logger.error("initialization, test connection failed. Error: %s", str(exp))
if self.influxdb_enabled:
try:
# Check that configured TSDB is existing, else creates...
dbs = self.influx.get_list_database()
for db in dbs:
if db.get('name') == self.influxdb_database:
logger.info("the database %s is existing.", self.influxdb_database)
break
else:
# Create the database
logger.info("creating database %s...", self.influxdb_database)
self.influx.create_database(self.influxdb_database)
# Check that configured TSDB retention is existing, else creates...
if self.influxdb_retention_name:
rps = self.influx.get_list_retention_policies()
for rp in rps:
if rp.get('name') == self.influxdb_retention_name:
logger.info("the retention policy %s is existing.",
self.influxdb_retention_name)
break
else:
# Create a retention policy for this database
logger.info("creating database retention policy: %s - %s - %s...",
self.influxdb_retention_name, self.influxdb_retention_duration,
self.influxdb_retention_replication)
self.influx.create_retention_policy(
self.influxdb_retention_name, self.influxdb_retention_duration,
self.influxdb_retention_replication, database=self.influxdb_database)
# Check that configured TSDB user is existing, else creates...
if self.influxdb_username:
users = self.influx.get_list_users()
for user in users:
if user.get('user') == self.influxdb_username:
logger.info("the user %s is existing.",
self.influxdb_username)
break
else:
# Create a retention policy for this database
logger.info("creating user: %s...", self.influxdb_username)
self.influx.create_user(self.influxdb_username, self.influxdb_password,
admin=False)
connections = connections or True
except Exception as exp: # pylint: disable=broad-except
logger.error("InfluxDB, DB initialization failed. Error: %s", str(exp))
return connections
|
java
|
private void beginTransaction() {
if (currentTransaction == null) {
try {
currentTransaction = StructrApp.getInstance(securityContext).tx(true, false, false);
} catch (FrameworkException fex) {
// transaction can fail here (theoretically...)
logger.warn("Unable to begin transaction.", fex);
}
}
}
|
java
|
public static CommerceTierPriceEntry findByGroupId_First(long groupId,
OrderByComparator<CommerceTierPriceEntry> orderByComparator)
throws com.liferay.commerce.price.list.exception.NoSuchTierPriceEntryException {
return getPersistence().findByGroupId_First(groupId, orderByComparator);
}
|
python
|
def bearing_to_nearest_place(feature, parent):
"""If the impact layer has a distance field, it will return the bearing
to the nearest place in degrees.
e.g. bearing_to_nearest_place() -> 280
"""
_ = feature, parent # NOQA
layer = exposure_summary_layer()
if not layer:
return None
index = layer.fields().lookupField(
bearing_field['field_name'])
if index < 0:
return None
feature = next(layer.getFeatures())
return feature[index]
|
java
|
boolean scanNoParse() {
while (true) {
switch (state) {
case 300:
if (peek() == '#' && next() == '[' && next() == '[') {
state = 301;
continue ;
}
return fail();
case 301:
for (char c=next(); true; c=next()) {
if (c == ']' && buf[forward + 1] == ']' && buf[forward + 2] == '#') {
addTextToken(subBuf(lexemeBegin + 3, forward - 1)); // NoParse 块使用 TextToken
return prepareNextScan(3);
}
if (c == EOF) {
throw new ParseException("The \"no parse\" start block \"#[[\" can not match the end block: \"]]#\"", new Location(fileName, beginRow));
}
}
default :
return fail();
}
}
}
|
java
|
@SuppressWarnings("unchecked")
public boolean tryStart(final ProcessorGraphNode processorGraphNode) {
this.processorLock.lock();
final boolean canStart;
try {
if (isRunning(processorGraphNode) || isFinished(processorGraphNode) ||
!allAreFinished(processorGraphNode.getRequirements())) {
canStart = false;
} else {
started(processorGraphNode);
canStart = true;
}
} finally {
this.processorLock.unlock();
}
return canStart;
}
|
python
|
def var(self, ddof=1, *args, **kwargs):
"""
Compute variance of groups, excluding missing values.
Parameters
----------
ddof : integer, default 1
degrees of freedom
"""
nv.validate_resampler_func('var', args, kwargs)
return self._downsample('var', ddof=ddof)
|
java
|
public void setCharset(String charset) {
if (StringUtil.isEmpty(charset)) return;
this.charset = CharsetUtil.toCharSet(charset.trim());
}
|
java
|
public Set<String> getPropAsCaseInsensitiveSet(String key) {
return ImmutableSortedSet.copyOf(String.CASE_INSENSITIVE_ORDER, LIST_SPLITTER.split(getProp(key)));
}
|
java
|
public Mono<Response<ConfigurationSetting>> getSetting(ConfigurationSetting setting) {
// Validate that setting and key is not null. The key is used in the service URL so it cannot be null.
validateSetting(setting);
return service.getKeyValue(serviceEndpoint, setting.key(), setting.label(), null, null, null, null);
}
|
python
|
def add_rule(self, name, callable_):
"""Makes rule 'name' available to all subsequently loaded Jamfiles.
Calling that rule wil relay to 'callable'."""
assert isinstance(name, basestring)
assert callable(callable_)
self.project_rules_.add_rule(name, callable_)
|
java
|
public Observable<ExpressRouteCircuitsRoutesTableListResultInner> listRoutesTableAsync(String resourceGroupName, String crossConnectionName, String peeringName, String devicePath) {
return listRoutesTableWithServiceResponseAsync(resourceGroupName, crossConnectionName, peeringName, devicePath).map(new Func1<ServiceResponse<ExpressRouteCircuitsRoutesTableListResultInner>, ExpressRouteCircuitsRoutesTableListResultInner>() {
@Override
public ExpressRouteCircuitsRoutesTableListResultInner call(ServiceResponse<ExpressRouteCircuitsRoutesTableListResultInner> response) {
return response.body();
}
});
}
|
python
|
def sel_list_pres(ds_sfc_x):
'''
select proper levels for model level data download
'''
p_min, p_max = ds_sfc_x.sp.min().values, ds_sfc_x.sp.max().values
list_pres_level = [
'1', '2', '3',
'5', '7', '10',
'20', '30', '50',
'70', '100', '125',
'150', '175', '200',
'225', '250', '300',
'350', '400', '450',
'500', '550', '600',
'650', '700', '750',
'775', '800', '825',
'850', '875', '900',
'925', '950', '975',
'1000',
]
ser_pres_level = pd.Series(list_pres_level).map(int)*100
pos_lev_max, pos_lev_min = (
ser_pres_level[ser_pres_level > p_max].idxmin(),
ser_pres_level[ser_pres_level < p_min].idxmax()
)
list_pres_sel = ser_pres_level.loc[pos_lev_min:pos_lev_max]/100
list_pres_sel = list_pres_sel.map(int).map(str).to_list()
return list_pres_sel
|
java
|
public String getPrincipalAttributeValue(final Principal p, final String attributeName) {
val attributes = p.getAttributes();
if (attributes.containsKey(attributeName)) {
return CollectionUtils.toCollection(attributes.get(attributeName)).iterator().next().toString();
}
return null;
}
|
java
|
public static double Sinh(double x, int nTerms) {
if (nTerms < 2) return x;
if (nTerms == 2) {
return x + (x * x * x) / 6D;
} else {
double mult = x * x * x;
double fact = 6;
int factS = 5;
double result = x + mult / fact;
for (int i = 3; i <= nTerms; i++) {
mult *= x * x;
fact *= factS * (factS - 1);
factS += 2;
result += mult / fact;
}
return result;
}
}
|
java
|
public String getMatch(final byte[] content) throws IOException {
final ByteBuffer buf = readBuffer(content);
if (buf == null) {
return null;
}
buf.position(0);
final boolean matches = match(buf);
if (matches) {
final int subLen = this.subEntries.size();
final String myMimeType = getMimeType();
if (subLen > 0) {
String mtype = null;
for (int k = 0; k < subLen; k++) {
final MagicMimeEntry me = this.subEntries.get(k);
mtype = me.getMatch(content);
if (mtype != null) {
return mtype;
}
}
if (myMimeType != null) {
return myMimeType;
}
} else {
return myMimeType;
}
}
return null;
}
|
python
|
def _uncythonized_mb_model(self, beta, mini_batch):
""" Creates the structure of the model
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
mini_batch : int
Size of each mini batch of data
Returns
----------
theta : np.array
Contains the predicted values for the time series
Y : np.array
Contains the length-adjusted time series (accounting for lags)
scores : np.array
Contains the scores for the time series
"""
rand_int = np.random.randint(low=0, high=self.data.shape[0]-mini_batch-self.max_lag+1)
sample = np.arange(start=rand_int, stop=rand_int+mini_batch)
data = self.data[sample]
X = self.X[sample, :]
Y = data[self.max_lag:]
parm = np.array([self.latent_variables.z_list[k].prior.transform(beta[k]) for k in range(beta.shape[0])])
model_scale, model_shape, model_skewness = self._get_scale_and_shape(parm)
theta = np.matmul(X[self.integ+self.max_lag:],parm[self.sc+self.ar:(self.sc+self.ar+len(self.X_names))])
# Loop over time series
theta, self.model_scores = gasx_recursion(parm, theta, self.model_scores, Y, self.ar, self.sc, Y.shape[0], self.family.score_function,
self.link, model_scale, model_shape, model_skewness, self.max_lag)
return np.array(theta), Y, self.model_scores
|
java
|
public ResponseWrapper removeChatRoomMembers(long roomId, Members members)
throws APIConnectionException, APIRequestException {
Preconditions.checkArgument(roomId > 0, "room id is invalid");
Preconditions.checkArgument(members != null, "members should not be empty");
return _httpClient.sendDelete(_baseUrl + mChatRoomPath + "/" + roomId + "/members", members.toString());
}
|
java
|
public static void log( GrayF32 input , GrayF32 output ) {
output.reshape(input.width,input.height);
if( BoofConcurrency.USE_CONCURRENT ) {
ImplPixelMath_MT.log(input,output);
} else {
ImplPixelMath.log(input,output);
}
}
|
java
|
public static <P extends ModelProperty, T extends ModelClass<P>> void buildProperties(Elements elementUtils,
T entity, PropertyFactory<T, P> factoryProperty, AnnotationFilter propertyAnnotationFilter,
PropertyCreatedListener<T, P> listener) {
List<? extends Element> listA = elementUtils.getAllMembers(entity.getElement());
List<Element> list = new ArrayList<Element>(listA);
Map<String, P> propertyMap = new HashMap<>();
if (propertyAnnotationFilter != null) {
AnnotationUtility.forEachAnnotations(entity.getElement(), propertyAnnotationFilter, null);
}
// extract fields directly from class
extractFields(entity, factoryProperty, list, propertyMap);
list = null;
// go up in class hierarchy and extract other fields
String parentClassName = entity.getElement().getSuperclass().toString();
while (parentClassName != null && !Object.class.getCanonicalName().equals(parentClassName)) {
TypeElement parentTypeElement = BaseProcessor.elementUtils.getTypeElement(parentClassName);
if (parentTypeElement != null) {
List<? extends Element> parentList = elementUtils.getAllMembers(parentTypeElement);
list = new ArrayList<>(parentList);
extractFields(entity, factoryProperty, list, propertyMap);
parentClassName = parentTypeElement.getSuperclass().toString();
} else {
// parentTypeElement is null
parentClassName = null;
}
}
// Method Analysis
//
String methodName;
String propertyName = "";
ModelProperty currentKriptonField;
Converter<String, String> converter = CaseFormat.UPPER_CAMEL.converterTo(CaseFormat.LOWER_CAMEL);
int status = 0;
// define property for the entity (must be done before working with
// methods, due to parameters resolver)
for (P p : propertyMap.values()) {
entity.add(p);
}
// int i=0;
// AnnotationProcessorUtilis.printMessage(String.format((i++) + "entity %s ",entity.getName()));
//
// restore original methods and fields
list = new ArrayList<Element>(listA);
for (Element item : list) {
methodName = item.getSimpleName().toString();
// cus
//AnnotationProcessorUtilis.printMessage(String.format((i++) + "item %s type %s modifiers [%s] ", item.getSimpleName().toString(), item.getKind(), item.getModifiers()));
if (item.getKind() == ElementKind.METHOD && item.getModifiers().contains(Modifier.PUBLIC)) {
ExecutableElement method = (ExecutableElement) item;
// this method can not be usefull
if (method.getParameters().size() > 1)
continue;
status = -1;
if (methodName.startsWith(GET_PREFIX)) {
status = 0;
propertyName = methodName.substring(GET_PREFIX.length());
} else if (methodName.startsWith(IS_PREFIX)) {
status = 1;
propertyName = methodName.substring(IS_PREFIX.length());
} else if (methodName.startsWith(SET_PREFIX)) {
status = 2;
propertyName = methodName.substring(SET_PREFIX.length());
}
propertyName = converter.convert(propertyName);
if (propertyMap.containsKey(propertyName)) {
currentKriptonField = propertyMap.get(propertyName);
TypeMirror paramTypeMirror = method.getParameters().size() == 1
? method.getParameters().get(0).asType() : null;
TypeMirror returnTypeMirror = method.getReturnType();
// GET
if (status == 0 && currentKriptonField
.isType(entity.resolveTypeVariable(TypeUtility.typeName(returnTypeMirror)))) {
currentKriptonField.setFieldWithGetter(true);
// IS
} else if (status == 1 && currentKriptonField
.isType(entity.resolveTypeVariable(TypeUtility.typeName(returnTypeMirror)))) {
currentKriptonField.setFieldWithIs(true);
// SET
} else if (status == 2 && currentKriptonField
.isType(entity.resolveTypeVariable(TypeUtility.typeName(paramTypeMirror)))) {
currentKriptonField.setFieldWithSetter(true);
}
}
}
}
if (listener != null) {
List<P> listPropertiesToFilter = new ArrayList<P>(entity.getCollection());
// copy all properties (included the excluded one) into immutable collection
entity.getImmutableCollection().addAll(entity.getCollection());
for (P item : listPropertiesToFilter) {
if (!listener.onProperty(entity, item)) {
entity.getCollection().remove(item);
}
}
}
}
|
java
|
public DescribeTaskSetsRequest withTaskSets(String... taskSets) {
if (this.taskSets == null) {
setTaskSets(new com.amazonaws.internal.SdkInternalList<String>(taskSets.length));
}
for (String ele : taskSets) {
this.taskSets.add(ele);
}
return this;
}
|
java
|
public List<MavenBuild> getAllBuilds() throws IOException {
String path = "/";
try {
List<MavenBuild> builds = client.get(path + "job/" + EncodingUtils.encode(this.getName())
+ "?tree=allBuilds[number[*],url[*],queueId[*]]", AllMavenBuilds.class).getAllBuilds();
if (builds == null) {
return Collections.emptyList();
} else {
return builds.stream()
.map(SET_CLIENT(this.client))
.collect(toList());
}
} catch (HttpResponseException e) {
// TODO: Thinks about a better handling if the job does not exist?
if (e.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
// TODO: Check this if this is necessary or a good idea?
return null;
}
throw e;
}
}
|
java
|
protected Label createLabel(Composite parent, String text, boolean bold) {
Label label= new Label(parent, SWT.NONE);
if (bold)
label.setFont(JFaceResources.getBannerFont());
label.setText(text);
GridData gridData= new GridData(SWT.BEGINNING, SWT.CENTER, false, false);
label.setLayoutData(gridData);
return label;
}
|
java
|
public static int[] unbox (Integer[] list)
{
if (list == null) {
return null;
}
int[] unboxed = new int[list.length];
for (int ii = 0; ii < list.length; ii++) {
unboxed[ii] = list[ii];
}
return unboxed;
}
|
java
|
private void setupTrigger() {
String label = drpTriggerType.getSelected() + " Trigger";
WFieldLayout layout = new WFieldLayout();
layout.setLabelWidth(LABEL_WIDTH);
buildControlPanel.add(layout);
switch ((TriggerType) drpTriggerType.getSelected()) {
case RadioButtonGroup:
trigger = new RadioButtonGroup();
WFieldSet rbSet = new WFieldSet("Select an option");
RadioButtonGroup group = (RadioButtonGroup) trigger;
WRadioButton rb1 = group.addRadioButton("A");
WRadioButton rb2 = group.addRadioButton("B");
WRadioButton rb3 = group.addRadioButton("C");
rbSet.add(group);
rbSet.add(rb1);
rbSet.add(new WLabel("A", rb1));
rbSet.add(new WText("\u00a0"));
rbSet.add(rb2);
rbSet.add(new WLabel("B", rb2));
rbSet.add(new WText("\u00a0"));
rbSet.add(rb3);
rbSet.add(new WLabel("C", rb3));
layout.addField(label, rbSet);
return;
case CheckBox:
trigger = new WCheckBox();
break;
case CheckBoxSelect:
trigger = new WCheckBoxSelect(LOOKUP_TABLE_NAME);
break;
case DateField:
trigger = new WDateField();
break;
case Dropdown:
trigger = new WDropdown(new TableWithNullOption(LOOKUP_TABLE_NAME));
break;
case EmailField:
trigger = new WEmailField();
break;
case MultiSelect:
trigger = new WMultiSelect(LOOKUP_TABLE_NAME);
break;
case MultiSelectPair:
trigger = new WMultiSelectPair(LOOKUP_TABLE_NAME);
break;
case NumberField:
trigger = new WNumberField();
break;
case PartialDateField:
trigger = new WPartialDateField();
break;
case PasswordField:
trigger = new WPasswordField();
break;
case PhoneNumberField:
trigger = new WPhoneNumberField();
break;
case RadioButtonSelect:
trigger = new WRadioButtonSelect(LOOKUP_TABLE_NAME);
break;
case SingleSelect:
trigger = new WSingleSelect(LOOKUP_TABLE_NAME);
break;
case TextArea:
trigger = new WTextArea();
((WTextArea) trigger).setMaxLength(1000);
break;
case TextField:
trigger = new WTextField();
break;
default:
throw new SystemException("Trigger type not valid");
}
layout.addField(label, trigger);
}
|
python
|
def generateLatticeFile(self, beamline, filename=None, format='elegant'):
""" generate simulation files for lattice analysis,
e.g. ".lte" for elegant, ".madx" for madx
input parameters:
:param beamline: keyword for beamline
:param filename: name of lte/mad file,
if None, output to stdout;
if 'sio', output to a string as return value;
other cases, output to filename;
:param format: madx, elegant,
'elegant' by default, generated lattice is for elegant tracking
"""
"""
if not self.isBeamline(beamline):
print("%s is a valid defined beamline, do not process." % (beamline))
return False
"""
if filename is None:
f = sys.stdout
elif filename == 'sio':
f = StringIO()
else:
f = open(os.path.expanduser(filename), 'w')
# write filehead, mainly resolving prefix string lines
cl1 = "This file is automatically generated by 'generateLatticeFile()' method,"
cl2 = 'could be used as ' + format + ' lattice file.'
cl3 = 'Author: Tong Zhang (zhangtong@sinap.ac.cn)'
cl4 = 'Generated Date: ' + time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime())
f.write('!{str1:<73s}!\n'.format(str1='-' * 73))
f.write('!{str1:^73s}!\n'.format(str1=cl1))
f.write('!{str1:^73s}!\n'.format(str1=cl2))
f.write('!{str1:^73s}!\n'.format(str1='-' * 24))
f.write('!{str1:^73s}!\n'.format(str1=cl3))
f.write('!{str1:^73s}!\n'.format(str1=cl4))
f.write('!{str1:<73s}!\n'.format(str1='-' * 73))
f.write('\n')
""" do not need to dump stoed variables now, 2016-03-21
# write global variables
f.write('! {str1:<73s}\n'.format(str1= 'Global variable definitions:'))
f.write('\n'.join(self.all_elements['_prefixstr']))
f.write('\n')
f.write('\n')
"""
# write EPICS control configuration part if contains '_epics' key
if '_epics' in self.all_elements:
f.write('! {str1:<73s}\n'.format(str1='EPICS control definitions:'))
for k, v in self.all_elements['_epics'].items():
f.write('!!epics {k:<10s}:{v:>50s}\n'.format(k=k, v=json.dumps(v)))
f.write('\n')
# write element definitions and lattice
f.write('! {str1:<72s}\n'.format(str1='Element definitions:'))
elelist = self.getFullBeamline(beamline, extend=True)
if self.getElementType(elelist[0]) != 'CHARGE':
elelist.insert(0, self.getChargeElement())
for ele in sorted(set(elelist)):
elestring = self.rinseElement(ele)['name']
f.write(self.formatElement(elestring, format='elegant') + '\n')
# write beamline lattice definition
f.write('\n')
f.write('! {str1:<72s}\n'.format(str1='Beamline definitions:'))
f.write('{bl:<10s}: line = ({lattice})'.format(bl=beamline.upper(),
lattice=', '.join(elelist)))
if filename == 'sio':
retval = f.getvalue()
else:
retval = True
f.close()
# if everything's OK, return True or string ('sio') mode
return retval
|
java
|
public static String exampleCheck(Class<?> entityClass) {
StringBuilder sql = new StringBuilder();
sql.append("<bind name=\"checkExampleEntityClass\" value=\"@tk.mybatis.mapper.util.OGNL@checkExampleEntityClass(_parameter, '");
sql.append(entityClass.getCanonicalName());
sql.append("')\"/>");
return sql.toString();
}
|
java
|
@Override
public void part(String reason) {
Message partMessage = new Message(MessageType.PART, this.channelName, reason);
this.client.getConnection().send(partMessage);
this.joined = new CountDownLatch(1);
}
|
python
|
def validate(
self, nanopub: Mapping[str, Any]
) -> Tuple[bool, List[Tuple[str, str]]]:
"""Validates using the nanopub schema
Args:
nanopub (Mapping[str, Any]): nanopub dict
Returns:
Tuple[bool, List[Tuple[str, str]]]:
bool: Is valid? Yes = True, No = False
List[Tuple[str, str]]: Validation issues, empty if valid, tuple is ('ERROR|WARNING', msg)
e.g. [('WARNING', "Context ID not found")] """
# Validate nanopub
(is_valid, messages) = validate_to_schema(nanopub, self.nanopub_schema)
if not is_valid:
return messages
# Extract BEL Version
if nanopub["nanopub"]["type"]["name"].upper() == "BEL":
bel_version = nanopub["nanopub"]["type"]["version"]
else:
is_valid = False
return (
is_valid,
f"Not a BEL Nanopub according to nanopub.type.name: {nanopub['nanopub']['type']['name']}",
)
all_messages = []
# Validate BEL Statements
bel_obj = bel.lang.belobj.BEL(bel_version, self.endpoint)
for edge in nanopub["nanopub"]["edges"]:
bel_statement = f"{edge['subject']} {edge['relation']} {edge['object']}"
parse_obj = bel_obj.parse(bel_statement)
if not parse_obj.valid:
all_messages.extend(
(
"ERROR",
f"BEL statement parse error {parse_obj.error}, {parse_obj.err_visual}",
)
)
# Validate nanopub.context
for context in nanopub["nanopub"]["context"]:
(is_valid, messages) = self.validate_context(context)
all_messages.extend(messages)
is_valid = True
for _type, msg in all_messages:
if _type == "ERROR":
is_valid = False
return (is_valid, all_messages)
|
python
|
def trocar_codigo_de_ativacao(self, novo_codigo_ativacao,
opcao=constantes.CODIGO_ATIVACAO_REGULAR,
codigo_emergencia=None):
"""Função ``TrocarCodigoDeAtivacao`` conforme ER SAT, item 6.1.15.
Troca do código de ativação do equipamento SAT.
:param str novo_codigo_ativacao: O novo código de ativação escolhido
pelo contribuinte.
:param int opcao: Indica se deverá ser utilizado o código de ativação
atualmente configurado, que é um código de ativação regular,
definido pelo contribuinte, ou se deverá ser usado um código de
emergência. Deverá ser o valor de uma das constantes
:attr:`satcomum.constantes.CODIGO_ATIVACAO_REGULAR` (padrão) ou
:attr:`satcomum.constantes.CODIGO_ATIVACAO_EMERGENCIA`.
Nenhuma validação será realizada antes que a função seja
efetivamente invocada. Entretanto, se opção de código de ativação
indicada for ``CODIGO_ATIVACAO_EMERGENCIA``, então o argumento que
informa o ``codigo_emergencia`` será checado e deverá avaliar como
verdadeiro.
:param str codigo_emergencia: O código de ativação de emergência, que
é definido pelo fabricante do equipamento SAT. Este código deverá
ser usado quando o usuário perder o código de ativação regular, e
precisar definir um novo código de ativação. Note que, o argumento
``opcao`` deverá ser informado com o valor
:attr:`satcomum.constantes.CODIGO_ATIVACAO_EMERGENCIA` para que
este código de emergência seja considerado.
:return: Retorna *verbatim* a resposta da função SAT.
:rtype: string
:raises ValueError: Se o novo código de ativação avaliar como falso
(possuir uma string nula por exemplo) ou se o código de emergencia
avaliar como falso quando a opção for pelo código de ativação de
emergência.
.. warning::
Os argumentos da função ``TrocarCodigoDeAtivacao`` requerem que o
novo código de ativação seja especificado duas vezes (dois
argumentos com o mesmo conteúdo, como confirmação). Este método irá
simplesmente informar duas vezes o argumento
``novo_codigo_ativacao`` na função SAT, mantendo a confirmação do
código de ativação fora do escopo desta API.
"""
if not novo_codigo_ativacao:
raise ValueError('Novo codigo de ativacao invalido: {!r}'.format(
novo_codigo_ativacao))
codigo_ativacao = self._codigo_ativacao
if opcao == constantes.CODIGO_ATIVACAO_EMERGENCIA:
if codigo_emergencia:
codigo_ativacao = codigo_emergencia
else:
raise ValueError('Codigo de ativacao de emergencia invalido: '
'{!r} (opcao={!r})'.format(codigo_emergencia, opcao))
return self.invocar__TrocarCodigoDeAtivacao(
self.gerar_numero_sessao(), codigo_ativacao, opcao,
novo_codigo_ativacao, novo_codigo_ativacao)
|
python
|
def to_best_int_float(val):
"""Get best type for value between int and float
:param val: value
:type val:
:return: int(float(val)) if int(float(val)) == float(val), else float(val)
:rtype: int | float
>>> to_best_int_float("20.1")
20.1
>>> to_best_int_float("20.0")
20
>>> to_best_int_float("20")
20
"""
integer = int(float(val))
flt = float(val)
# If the f is a .0 value,
# best match is int
if integer == flt:
return integer
return flt
|
python
|
def top(self, z: float = 0.0) -> Location:
"""
:param z: the z distance in mm
:return: a Point corresponding to the absolute position of the
top-center of the well relative to the deck (with the
front-left corner of slot 1 as (0,0,0)). If z is specified,
returns a point offset by z mm from top-center
"""
return Location(self._position + Point(0, 0, z), self)
|
java
|
public static String getRequiredStringParameter(UimaContext context,
String parameter)
throws ResourceInitializationException {
String value = getOptionalStringParameter(context, parameter);
checkForNull(value, parameter);
return value;
}
|
java
|
public static void xmlGlobalExistent(Class<?> aClass) {
throw new XmlMappingGlobalExistException(MSG.INSTANCE.message(xmlMappingGlobalExistException, aClass.getSimpleName()));
}
|
java
|
public final EObject ruleXFeatureCall() throws RecognitionException {
EObject current = null;
Token otherlv_1=null;
Token otherlv_3=null;
Token otherlv_5=null;
Token lv_explicitOperationCall_7_0=null;
Token otherlv_10=null;
Token otherlv_12=null;
EObject lv_typeArguments_2_0 = null;
EObject lv_typeArguments_4_0 = null;
EObject lv_featureCallArguments_8_0 = null;
EObject lv_featureCallArguments_9_0 = null;
EObject lv_featureCallArguments_11_0 = null;
EObject lv_featureCallArguments_13_0 = null;
enterRule();
try {
// InternalXbaseWithAnnotations.g:4599:2: ( ( () (otherlv_1= '<' ( (lv_typeArguments_2_0= ruleJvmArgumentTypeReference ) ) (otherlv_3= ',' ( (lv_typeArguments_4_0= ruleJvmArgumentTypeReference ) ) )* otherlv_5= '>' )? ( ( ruleIdOrSuper ) ) ( ( ( ( '(' ) )=> (lv_explicitOperationCall_7_0= '(' ) ) ( ( ( ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )=> (lv_featureCallArguments_8_0= ruleXShortClosure ) ) | ( ( (lv_featureCallArguments_9_0= ruleXExpression ) ) (otherlv_10= ',' ( (lv_featureCallArguments_11_0= ruleXExpression ) ) )* ) )? otherlv_12= ')' )? ( ( ( () '[' ) )=> (lv_featureCallArguments_13_0= ruleXClosure ) )? ) )
// InternalXbaseWithAnnotations.g:4600:2: ( () (otherlv_1= '<' ( (lv_typeArguments_2_0= ruleJvmArgumentTypeReference ) ) (otherlv_3= ',' ( (lv_typeArguments_4_0= ruleJvmArgumentTypeReference ) ) )* otherlv_5= '>' )? ( ( ruleIdOrSuper ) ) ( ( ( ( '(' ) )=> (lv_explicitOperationCall_7_0= '(' ) ) ( ( ( ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )=> (lv_featureCallArguments_8_0= ruleXShortClosure ) ) | ( ( (lv_featureCallArguments_9_0= ruleXExpression ) ) (otherlv_10= ',' ( (lv_featureCallArguments_11_0= ruleXExpression ) ) )* ) )? otherlv_12= ')' )? ( ( ( () '[' ) )=> (lv_featureCallArguments_13_0= ruleXClosure ) )? )
{
// InternalXbaseWithAnnotations.g:4600:2: ( () (otherlv_1= '<' ( (lv_typeArguments_2_0= ruleJvmArgumentTypeReference ) ) (otherlv_3= ',' ( (lv_typeArguments_4_0= ruleJvmArgumentTypeReference ) ) )* otherlv_5= '>' )? ( ( ruleIdOrSuper ) ) ( ( ( ( '(' ) )=> (lv_explicitOperationCall_7_0= '(' ) ) ( ( ( ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )=> (lv_featureCallArguments_8_0= ruleXShortClosure ) ) | ( ( (lv_featureCallArguments_9_0= ruleXExpression ) ) (otherlv_10= ',' ( (lv_featureCallArguments_11_0= ruleXExpression ) ) )* ) )? otherlv_12= ')' )? ( ( ( () '[' ) )=> (lv_featureCallArguments_13_0= ruleXClosure ) )? )
// InternalXbaseWithAnnotations.g:4601:3: () (otherlv_1= '<' ( (lv_typeArguments_2_0= ruleJvmArgumentTypeReference ) ) (otherlv_3= ',' ( (lv_typeArguments_4_0= ruleJvmArgumentTypeReference ) ) )* otherlv_5= '>' )? ( ( ruleIdOrSuper ) ) ( ( ( ( '(' ) )=> (lv_explicitOperationCall_7_0= '(' ) ) ( ( ( ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )=> (lv_featureCallArguments_8_0= ruleXShortClosure ) ) | ( ( (lv_featureCallArguments_9_0= ruleXExpression ) ) (otherlv_10= ',' ( (lv_featureCallArguments_11_0= ruleXExpression ) ) )* ) )? otherlv_12= ')' )? ( ( ( () '[' ) )=> (lv_featureCallArguments_13_0= ruleXClosure ) )?
{
// InternalXbaseWithAnnotations.g:4601:3: ()
// InternalXbaseWithAnnotations.g:4602:4:
{
if ( state.backtracking==0 ) {
current = forceCreateModelElement(
grammarAccess.getXFeatureCallAccess().getXFeatureCallAction_0(),
current);
}
}
// InternalXbaseWithAnnotations.g:4608:3: (otherlv_1= '<' ( (lv_typeArguments_2_0= ruleJvmArgumentTypeReference ) ) (otherlv_3= ',' ( (lv_typeArguments_4_0= ruleJvmArgumentTypeReference ) ) )* otherlv_5= '>' )?
int alt80=2;
int LA80_0 = input.LA(1);
if ( (LA80_0==26) ) {
alt80=1;
}
switch (alt80) {
case 1 :
// InternalXbaseWithAnnotations.g:4609:4: otherlv_1= '<' ( (lv_typeArguments_2_0= ruleJvmArgumentTypeReference ) ) (otherlv_3= ',' ( (lv_typeArguments_4_0= ruleJvmArgumentTypeReference ) ) )* otherlv_5= '>'
{
otherlv_1=(Token)match(input,26,FOLLOW_34); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_1, grammarAccess.getXFeatureCallAccess().getLessThanSignKeyword_1_0());
}
// InternalXbaseWithAnnotations.g:4613:4: ( (lv_typeArguments_2_0= ruleJvmArgumentTypeReference ) )
// InternalXbaseWithAnnotations.g:4614:5: (lv_typeArguments_2_0= ruleJvmArgumentTypeReference )
{
// InternalXbaseWithAnnotations.g:4614:5: (lv_typeArguments_2_0= ruleJvmArgumentTypeReference )
// InternalXbaseWithAnnotations.g:4615:6: lv_typeArguments_2_0= ruleJvmArgumentTypeReference
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXFeatureCallAccess().getTypeArgumentsJvmArgumentTypeReferenceParserRuleCall_1_1_0());
}
pushFollow(FOLLOW_35);
lv_typeArguments_2_0=ruleJvmArgumentTypeReference();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElementForParent(grammarAccess.getXFeatureCallRule());
}
add(
current,
"typeArguments",
lv_typeArguments_2_0,
"org.eclipse.xtext.xbase.Xtype.JvmArgumentTypeReference");
afterParserOrEnumRuleCall();
}
}
}
// InternalXbaseWithAnnotations.g:4632:4: (otherlv_3= ',' ( (lv_typeArguments_4_0= ruleJvmArgumentTypeReference ) ) )*
loop79:
do {
int alt79=2;
int LA79_0 = input.LA(1);
if ( (LA79_0==15) ) {
alt79=1;
}
switch (alt79) {
case 1 :
// InternalXbaseWithAnnotations.g:4633:5: otherlv_3= ',' ( (lv_typeArguments_4_0= ruleJvmArgumentTypeReference ) )
{
otherlv_3=(Token)match(input,15,FOLLOW_34); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_3, grammarAccess.getXFeatureCallAccess().getCommaKeyword_1_2_0());
}
// InternalXbaseWithAnnotations.g:4637:5: ( (lv_typeArguments_4_0= ruleJvmArgumentTypeReference ) )
// InternalXbaseWithAnnotations.g:4638:6: (lv_typeArguments_4_0= ruleJvmArgumentTypeReference )
{
// InternalXbaseWithAnnotations.g:4638:6: (lv_typeArguments_4_0= ruleJvmArgumentTypeReference )
// InternalXbaseWithAnnotations.g:4639:7: lv_typeArguments_4_0= ruleJvmArgumentTypeReference
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXFeatureCallAccess().getTypeArgumentsJvmArgumentTypeReferenceParserRuleCall_1_2_1_0());
}
pushFollow(FOLLOW_35);
lv_typeArguments_4_0=ruleJvmArgumentTypeReference();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElementForParent(grammarAccess.getXFeatureCallRule());
}
add(
current,
"typeArguments",
lv_typeArguments_4_0,
"org.eclipse.xtext.xbase.Xtype.JvmArgumentTypeReference");
afterParserOrEnumRuleCall();
}
}
}
}
break;
default :
break loop79;
}
} while (true);
otherlv_5=(Token)match(input,27,FOLLOW_33); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_5, grammarAccess.getXFeatureCallAccess().getGreaterThanSignKeyword_1_3());
}
}
break;
}
// InternalXbaseWithAnnotations.g:4662:3: ( ( ruleIdOrSuper ) )
// InternalXbaseWithAnnotations.g:4663:4: ( ruleIdOrSuper )
{
// InternalXbaseWithAnnotations.g:4663:4: ( ruleIdOrSuper )
// InternalXbaseWithAnnotations.g:4664:5: ruleIdOrSuper
{
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElement(grammarAccess.getXFeatureCallRule());
}
}
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXFeatureCallAccess().getFeatureJvmIdentifiableElementCrossReference_2_0());
}
pushFollow(FOLLOW_65);
ruleIdOrSuper();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
afterParserOrEnumRuleCall();
}
}
}
// InternalXbaseWithAnnotations.g:4678:3: ( ( ( ( '(' ) )=> (lv_explicitOperationCall_7_0= '(' ) ) ( ( ( ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )=> (lv_featureCallArguments_8_0= ruleXShortClosure ) ) | ( ( (lv_featureCallArguments_9_0= ruleXExpression ) ) (otherlv_10= ',' ( (lv_featureCallArguments_11_0= ruleXExpression ) ) )* ) )? otherlv_12= ')' )?
int alt83=2;
alt83 = dfa83.predict(input);
switch (alt83) {
case 1 :
// InternalXbaseWithAnnotations.g:4679:4: ( ( ( '(' ) )=> (lv_explicitOperationCall_7_0= '(' ) ) ( ( ( ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )=> (lv_featureCallArguments_8_0= ruleXShortClosure ) ) | ( ( (lv_featureCallArguments_9_0= ruleXExpression ) ) (otherlv_10= ',' ( (lv_featureCallArguments_11_0= ruleXExpression ) ) )* ) )? otherlv_12= ')'
{
// InternalXbaseWithAnnotations.g:4679:4: ( ( ( '(' ) )=> (lv_explicitOperationCall_7_0= '(' ) )
// InternalXbaseWithAnnotations.g:4680:5: ( ( '(' ) )=> (lv_explicitOperationCall_7_0= '(' )
{
// InternalXbaseWithAnnotations.g:4684:5: (lv_explicitOperationCall_7_0= '(' )
// InternalXbaseWithAnnotations.g:4685:6: lv_explicitOperationCall_7_0= '('
{
lv_explicitOperationCall_7_0=(Token)match(input,14,FOLLOW_37); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(lv_explicitOperationCall_7_0, grammarAccess.getXFeatureCallAccess().getExplicitOperationCallLeftParenthesisKeyword_3_0_0());
}
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElement(grammarAccess.getXFeatureCallRule());
}
setWithLastConsumed(current, "explicitOperationCall", true, "(");
}
}
}
// InternalXbaseWithAnnotations.g:4697:4: ( ( ( ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )=> (lv_featureCallArguments_8_0= ruleXShortClosure ) ) | ( ( (lv_featureCallArguments_9_0= ruleXExpression ) ) (otherlv_10= ',' ( (lv_featureCallArguments_11_0= ruleXExpression ) ) )* ) )?
int alt82=3;
alt82 = dfa82.predict(input);
switch (alt82) {
case 1 :
// InternalXbaseWithAnnotations.g:4698:5: ( ( ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )=> (lv_featureCallArguments_8_0= ruleXShortClosure ) )
{
// InternalXbaseWithAnnotations.g:4698:5: ( ( ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )=> (lv_featureCallArguments_8_0= ruleXShortClosure ) )
// InternalXbaseWithAnnotations.g:4699:6: ( ( () ( ( ( ruleJvmFormalParameter ) ) ( ',' ( ( ruleJvmFormalParameter ) ) )* )? ( ( '|' ) ) ) )=> (lv_featureCallArguments_8_0= ruleXShortClosure )
{
// InternalXbaseWithAnnotations.g:4724:6: (lv_featureCallArguments_8_0= ruleXShortClosure )
// InternalXbaseWithAnnotations.g:4725:7: lv_featureCallArguments_8_0= ruleXShortClosure
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXFeatureCallAccess().getFeatureCallArgumentsXShortClosureParserRuleCall_3_1_0_0());
}
pushFollow(FOLLOW_7);
lv_featureCallArguments_8_0=ruleXShortClosure();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElementForParent(grammarAccess.getXFeatureCallRule());
}
add(
current,
"featureCallArguments",
lv_featureCallArguments_8_0,
"org.eclipse.xtext.xbase.Xbase.XShortClosure");
afterParserOrEnumRuleCall();
}
}
}
}
break;
case 2 :
// InternalXbaseWithAnnotations.g:4743:5: ( ( (lv_featureCallArguments_9_0= ruleXExpression ) ) (otherlv_10= ',' ( (lv_featureCallArguments_11_0= ruleXExpression ) ) )* )
{
// InternalXbaseWithAnnotations.g:4743:5: ( ( (lv_featureCallArguments_9_0= ruleXExpression ) ) (otherlv_10= ',' ( (lv_featureCallArguments_11_0= ruleXExpression ) ) )* )
// InternalXbaseWithAnnotations.g:4744:6: ( (lv_featureCallArguments_9_0= ruleXExpression ) ) (otherlv_10= ',' ( (lv_featureCallArguments_11_0= ruleXExpression ) ) )*
{
// InternalXbaseWithAnnotations.g:4744:6: ( (lv_featureCallArguments_9_0= ruleXExpression ) )
// InternalXbaseWithAnnotations.g:4745:7: (lv_featureCallArguments_9_0= ruleXExpression )
{
// InternalXbaseWithAnnotations.g:4745:7: (lv_featureCallArguments_9_0= ruleXExpression )
// InternalXbaseWithAnnotations.g:4746:8: lv_featureCallArguments_9_0= ruleXExpression
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXFeatureCallAccess().getFeatureCallArgumentsXExpressionParserRuleCall_3_1_1_0_0());
}
pushFollow(FOLLOW_6);
lv_featureCallArguments_9_0=ruleXExpression();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElementForParent(grammarAccess.getXFeatureCallRule());
}
add(
current,
"featureCallArguments",
lv_featureCallArguments_9_0,
"org.eclipse.xtext.xbase.Xbase.XExpression");
afterParserOrEnumRuleCall();
}
}
}
// InternalXbaseWithAnnotations.g:4763:6: (otherlv_10= ',' ( (lv_featureCallArguments_11_0= ruleXExpression ) ) )*
loop81:
do {
int alt81=2;
int LA81_0 = input.LA(1);
if ( (LA81_0==15) ) {
alt81=1;
}
switch (alt81) {
case 1 :
// InternalXbaseWithAnnotations.g:4764:7: otherlv_10= ',' ( (lv_featureCallArguments_11_0= ruleXExpression ) )
{
otherlv_10=(Token)match(input,15,FOLLOW_9); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_10, grammarAccess.getXFeatureCallAccess().getCommaKeyword_3_1_1_1_0());
}
// InternalXbaseWithAnnotations.g:4768:7: ( (lv_featureCallArguments_11_0= ruleXExpression ) )
// InternalXbaseWithAnnotations.g:4769:8: (lv_featureCallArguments_11_0= ruleXExpression )
{
// InternalXbaseWithAnnotations.g:4769:8: (lv_featureCallArguments_11_0= ruleXExpression )
// InternalXbaseWithAnnotations.g:4770:9: lv_featureCallArguments_11_0= ruleXExpression
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXFeatureCallAccess().getFeatureCallArgumentsXExpressionParserRuleCall_3_1_1_1_1_0());
}
pushFollow(FOLLOW_6);
lv_featureCallArguments_11_0=ruleXExpression();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElementForParent(grammarAccess.getXFeatureCallRule());
}
add(
current,
"featureCallArguments",
lv_featureCallArguments_11_0,
"org.eclipse.xtext.xbase.Xbase.XExpression");
afterParserOrEnumRuleCall();
}
}
}
}
break;
default :
break loop81;
}
} while (true);
}
}
break;
}
otherlv_12=(Token)match(input,16,FOLLOW_66); if (state.failed) return current;
if ( state.backtracking==0 ) {
newLeafNode(otherlv_12, grammarAccess.getXFeatureCallAccess().getRightParenthesisKeyword_3_2());
}
}
break;
}
// InternalXbaseWithAnnotations.g:4795:3: ( ( ( () '[' ) )=> (lv_featureCallArguments_13_0= ruleXClosure ) )?
int alt84=2;
alt84 = dfa84.predict(input);
switch (alt84) {
case 1 :
// InternalXbaseWithAnnotations.g:4796:4: ( ( () '[' ) )=> (lv_featureCallArguments_13_0= ruleXClosure )
{
// InternalXbaseWithAnnotations.g:4802:4: (lv_featureCallArguments_13_0= ruleXClosure )
// InternalXbaseWithAnnotations.g:4803:5: lv_featureCallArguments_13_0= ruleXClosure
{
if ( state.backtracking==0 ) {
newCompositeNode(grammarAccess.getXFeatureCallAccess().getFeatureCallArgumentsXClosureParserRuleCall_4_0());
}
pushFollow(FOLLOW_2);
lv_featureCallArguments_13_0=ruleXClosure();
state._fsp--;
if (state.failed) return current;
if ( state.backtracking==0 ) {
if (current==null) {
current = createModelElementForParent(grammarAccess.getXFeatureCallRule());
}
add(
current,
"featureCallArguments",
lv_featureCallArguments_13_0,
"org.eclipse.xtext.xbase.Xbase.XClosure");
afterParserOrEnumRuleCall();
}
}
}
break;
}
}
}
if ( state.backtracking==0 ) {
leaveRule();
}
}
catch (RecognitionException re) {
recover(input,re);
appendSkippedTokens();
}
finally {
}
return current;
}
|
java
|
public BatchGetAggregateResourceConfigResult withUnprocessedResourceIdentifiers(AggregateResourceIdentifier... unprocessedResourceIdentifiers) {
if (this.unprocessedResourceIdentifiers == null) {
setUnprocessedResourceIdentifiers(new com.amazonaws.internal.SdkInternalList<AggregateResourceIdentifier>(unprocessedResourceIdentifiers.length));
}
for (AggregateResourceIdentifier ele : unprocessedResourceIdentifiers) {
this.unprocessedResourceIdentifiers.add(ele);
}
return this;
}
|
java
|
@BetaApi
public final TargetPool getTargetPool(ProjectRegionTargetPoolName targetPool) {
GetTargetPoolHttpRequest request =
GetTargetPoolHttpRequest.newBuilder()
.setTargetPool(targetPool == null ? null : targetPool.toString())
.build();
return getTargetPool(request);
}
|
java
|
@Override
public Double unmarshal(String object) {
return Double.valueOf(Double.parseDouble(object));
}
|
java
|
protected boolean parseDefaultClause( DdlTokenStream tokens,
AstNode columnNode ) throws ParsingException {
assert tokens != null;
assert columnNode != null;
// defaultClause
// : defaultOption
// ;
// defaultOption : <literal> | datetimeValueFunction
// | USER | CURRENT_USER | SESSION_USER | SYSTEM_USER | NULL;
//
// <datetime value function> ::=
// <current date value function>
// | <current time value function>
// | <current timestamp value function>
//
// <current date value function> ::= CURRENT_DATE
//
// <current time value function> ::=
// CURRENT_TIME [ <left paren> <time precision> <right paren> ]
//
// <current timestamp value function> ::=
// CURRENT_TIMESTAMP [ <left paren> <timestamp precision> <right paren> ]
String defaultValue = "";
if (tokens.canConsume("DEFAULT")) {
String optionID;
int precision = -1;
if (tokens.canConsume("CURRENT_DATE") || tokens.canConsume("'CURRENT_DATE'")) {
optionID = DEFAULT_ID_DATETIME;
defaultValue = "CURRENT_DATE";
} else if (tokens.canConsume("CURRENT_TIME") || tokens.canConsume("'CURRENT_TIME'")) {
optionID = DEFAULT_ID_DATETIME;
defaultValue = "CURRENT_TIME";
if (tokens.canConsume(L_PAREN)) {
// EXPECT INTEGER
precision = integer(tokens.consume());
tokens.canConsume(R_PAREN);
}
} else if (tokens.canConsume("CURRENT_TIMESTAMP") || tokens.canConsume("'CURRENT_TIMESTAMP'")) {
optionID = DEFAULT_ID_DATETIME;
defaultValue = "CURRENT_TIMESTAMP";
if (tokens.canConsume(L_PAREN)) {
// EXPECT INTEGER
precision = integer(tokens.consume());
tokens.canConsume(R_PAREN);
}
} else if (tokens.canConsume("USER") || tokens.canConsume("'USER'")) {
optionID = DEFAULT_ID_USER;
defaultValue = "USER";
} else if (tokens.canConsume("CURRENT_USER") || tokens.canConsume("'CURRENT_USER'")) {
optionID = DEFAULT_ID_CURRENT_USER;
defaultValue = "CURRENT_USER";
} else if (tokens.canConsume("SESSION_USER") || tokens.canConsume("'SESSION_USER'")) {
optionID = DEFAULT_ID_SESSION_USER;
defaultValue = "SESSION_USER";
} else if (tokens.canConsume("SYSTEM_USER") || tokens.canConsume("'SYSTEM_USER'")) {
optionID = DEFAULT_ID_SYSTEM_USER;
defaultValue = "SYSTEM_USER";
} else if (tokens.canConsume("NULL") || tokens.canConsume("NULL")) {
optionID = DEFAULT_ID_NULL;
defaultValue = "NULL";
} else if (tokens.canConsume(L_PAREN)) {
optionID = DEFAULT_ID_LITERAL;
while (!tokens.canConsume(R_PAREN)) {
defaultValue = defaultValue + tokens.consume();
}
} else {
optionID = DEFAULT_ID_LITERAL;
// Assume default was EMPTY or ''
defaultValue = tokens.consume();
// strip quotes if necessary
if (defaultValue.startsWith("'") && defaultValue.endsWith("'")) {
if (defaultValue.length() > 2) {
defaultValue = defaultValue.substring(1, defaultValue.lastIndexOf('\''));
} else {
defaultValue = "";
}
}
// NOTE: default value could be a Real number as well as an integer, so
// 1000.00 is valid
if (tokens.canConsume(".")) {
defaultValue = defaultValue + '.' + tokens.consume();
}
}
columnNode.setProperty(DEFAULT_OPTION, optionID);
columnNode.setProperty(DEFAULT_VALUE, defaultValue);
if (precision > -1) {
columnNode.setProperty(DEFAULT_PRECISION, precision);
}
return true;
}
return false;
}
|
java
|
public void marshall(ProvisioningArtifactProperties provisioningArtifactProperties, ProtocolMarshaller protocolMarshaller) {
if (provisioningArtifactProperties == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(provisioningArtifactProperties.getName(), NAME_BINDING);
protocolMarshaller.marshall(provisioningArtifactProperties.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(provisioningArtifactProperties.getInfo(), INFO_BINDING);
protocolMarshaller.marshall(provisioningArtifactProperties.getType(), TYPE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
|
python
|
def _merge_by_type(lhs, rhs, type_):
"""Helper for '_merge_chunk'."""
merger = _MERGE_BY_TYPE[type_.code]
return merger(lhs, rhs, type_)
|
python
|
def read_vocab_file(file_path):
"""Reads a vocab file to memeory.
Args:
file_path: Each line of the vocab is in the form "token,example_count"
Returns:
Two lists, one for the vocab, and one for just the example counts.
"""
with file_io.FileIO(file_path, 'r') as f:
vocab_pd = pd.read_csv(
f,
header=None,
names=['vocab', 'count'],
dtype=str, # Prevent pd from converting numerical categories.
na_filter=False) # Prevent pd from converting 'NA' to a NaN.
vocab = vocab_pd['vocab'].tolist()
ex_count = vocab_pd['count'].astype(int).tolist()
return vocab, ex_count
|
java
|
@Override
public Appendable normalize(CharSequence src, Appendable dest) {
if(dest==src) {
throw new IllegalArgumentException();
}
return normalize(src, dest, UnicodeSet.SpanCondition.SIMPLE);
}
|
python
|
def add(self, resource, replace=False):
"""Add a resource or an iterable collection of resources.
Will throw a ValueError if the resource (ie. same uri) already
exists in the ResourceList, unless replace=True.
"""
if isinstance(resource, collections.Iterable):
for r in resource:
self.resources.add(r, replace)
else:
self.resources.add(resource, replace)
|
python
|
def when(string, timezone='UTC', prefer_dates_from='current_period'):
""""Returns a MayaDT instance for the human moment specified.
Powered by dateparser. Useful for scraping websites.
Examples:
'next week', 'now', 'tomorrow', '300 years ago', 'August 14, 2015'
Keyword Arguments:
string -- string to be parsed
timezone -- timezone referenced from (default: 'UTC')
prefer_dates_from -- what dates are prefered when `string` is ambigous.
options are 'past', 'future', and 'current_period'
(default: 'current_period'). see: [1]
Reference:
[1] dateparser.readthedocs.io/en/latest/usage.html#handling-incomplete-dates
"""
settings = {
'TIMEZONE': timezone,
'RETURN_AS_TIMEZONE_AWARE': True,
'TO_TIMEZONE': 'UTC',
'PREFER_DATES_FROM': prefer_dates_from,
}
dt = dateparser.parse(string, settings=settings)
if dt is None:
raise ValueError('invalid datetime input specified.')
return MayaDT.from_datetime(dt)
|
java
|
public void setThingGroupNames(java.util.Collection<String> thingGroupNames) {
if (thingGroupNames == null) {
this.thingGroupNames = null;
return;
}
this.thingGroupNames = new java.util.ArrayList<String>(thingGroupNames);
}
|
java
|
@Override
public EClass getIfcIndexedPolyCurve() {
if (ifcIndexedPolyCurveEClass == null) {
ifcIndexedPolyCurveEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(319);
}
return ifcIndexedPolyCurveEClass;
}
|
java
|
protected String get_asynch_idl_cmd(Request request, String idl_cmd) {
return deviceProxyDAO.get_asynch_idl_cmd(this, request, idl_cmd);
}
|
java
|
public void startLink(final VertexContext startVertex) {
if (startVertex == null) {
return;
}
final AbstractLayout<Object, JobGraphLink> graphLayout = _graphContext.getGraphLayout();
final int x = (int) graphLayout.getX(startVertex.getVertex());
final int y = (int) graphLayout.getY(startVertex.getVertex());
logger.debug("startLink({})", startVertex);
_startVertex = startVertex;
_startPoint = new Point(x, y);
transformEdgeShape(_startPoint, _startPoint);
_graphContext.getVisualizationViewer().addPostRenderPaintable(_edgePaintable);
transformArrowShape(_startPoint, _startPoint);
_graphContext.getVisualizationViewer().addPostRenderPaintable(_arrowPaintable);
}
|
python
|
def _dump_crawl_stats(self):
'''
Dumps flattened crawling stats so the spiders do not have to
'''
extras = {}
spiders = {}
spider_set = set()
total_spider_count = 0
keys = self.redis_conn.keys('stats:crawler:*:*:*')
for key in keys:
# we only care about the spider
elements = key.split(":")
spider = elements[3]
if spider not in spiders:
spiders[spider] = 0
if len(elements) == 6:
# got a time based stat
response = elements[4]
end = elements[5]
final = '{s}_{r}_{e}'.format(s=spider, r=response, e=end)
if end == 'lifetime':
value = self.redis_conn.execute_command("PFCOUNT", key)
else:
value = self.redis_conn.zcard(key)
extras[final] = value
elif len(elements) == 5:
# got a spider identifier
spiders[spider] += 1
total_spider_count += 1
spider_set.add(spider)
else:
self.logger.warn("Unknown crawler stat key", {"key":key})
# simple counts
extras['unique_spider_count'] = len(spider_set)
extras['total_spider_count'] = total_spider_count
for spider in spiders:
extras['{k}_spider_count'.format(k=spider)] = spiders[spider]
if not self.logger.json:
self.logger.info('Crawler Stats Dump:\n{0}'.format(
json.dumps(extras, indent=4, sort_keys=True)))
else:
self.logger.info('Crawler Stats Dump', extra=extras)
|
python
|
def compile(self):
"""
Compile this expression into an ODPS SQL
:return: compiled DAG
:rtype: str
"""
from ..engines import get_default_engine
engine = get_default_engine(self)
return engine.compile(self)
|
java
|
public static <T> List<String> sortByPinyin(Collection<String> collection) {
return sort(collection, new PinyinComparator());
}
|
java
|
public List<Interval> filterIntervals(String columnId) {
List<Interval> selected = columnSelectionMap.get(columnId);
if (selected == null) {
return new ArrayList<>();
}
return selected;
}
|
java
|
Integer getColBufLen(int i) {
int size;
int type;
ColumnSchema column;
column = table.getColumn(i);
type = column.getDataType().getJDBCTypeCode();
switch (type) {
case Types.SQL_CHAR :
case Types.SQL_CLOB :
case Types.VARCHAR_IGNORECASE :
case Types.SQL_VARCHAR : {
size = column.getDataType().precision > Integer.MAX_VALUE
? Integer.MAX_VALUE
: (int) column.getDataType().precision;
if (size == 0) {}
else if (size > HALF_MAX_INT) {
size = 0;
} else {
size = 2 * size;
}
break;
}
case Types.SQL_BINARY :
case Types.SQL_BLOB :
case Types.SQL_VARBINARY : {
size = column.getDataType().precision > Integer.MAX_VALUE
? Integer.MAX_VALUE
: (int) column.getDataType().precision;
break;
}
case Types.SQL_BIGINT :
case Types.SQL_DOUBLE :
case Types.SQL_FLOAT :
case Types.SQL_DATE :
case Types.SQL_REAL :
case Types.SQL_TIME_WITH_TIME_ZONE :
case Types.SQL_TIME : {
size = 8;
break;
}
case Types.SQL_TIMESTAMP_WITH_TIME_ZONE :
case Types.SQL_TIMESTAMP : {
size = 12;
break;
}
case Types.SQL_INTEGER :
case Types.SQL_SMALLINT :
case Types.TINYINT : {
size = 4;
break;
}
case Types.SQL_BOOLEAN : {
size = 1;
break;
}
default : {
size = 0;
break;
}
}
return (size > 0) ? ValuePool.getInt(size)
: null;
}
|
python
|
def copy(self):
"""Return a deep copy"""
result = Vector3(self.size, self.deriv)
result.x.v = self.x.v
result.y.v = self.y.v
result.z.v = self.z.v
if self.deriv > 0:
result.x.d[:] = self.x.d
result.y.d[:] = self.y.d
result.z.d[:] = self.z.d
if self.deriv > 1:
result.x.dd[:] = self.x.dd
result.y.dd[:] = self.y.dd
result.z.dd[:] = self.z.dd
return result
|
python
|
def scan_results(self):
"""Return the scan result."""
bsses = self._wifi_ctrl.scan_results(self._raw_obj)
if self._logger.isEnabledFor(logging.INFO):
for bss in bsses:
self._logger.info("Find bss:")
self._logger.info("\tbssid: %s", bss.bssid)
self._logger.info("\tssid: %s", bss.ssid)
self._logger.info("\tfreq: %d", bss.freq)
self._logger.info("\tauth: %s", bss.auth)
self._logger.info("\takm: %s", bss.akm)
self._logger.info("\tsignal: %d", bss.signal)
return bsses
|
python
|
def applet_get_details(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /applet-xxxx/getDetails API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Details-and-Links#API-method%3A-%2Fclass-xxxx%2FgetDetails
"""
return DXHTTPRequest('/%s/getDetails' % object_id, input_params, always_retry=always_retry, **kwargs)
|
java
|
@RequirePOST
public User doCreateAccount(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
return _doCreateAccount(req, rsp, "signup.jelly");
}
|
java
|
public List<CmsAccessControlEntry> getAllAccessControlEntries(CmsRequestContext context) throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
List<CmsAccessControlEntry> result = null;
try {
result = m_driverManager.getAllAccessControlEntries(dbc);
} catch (Exception e) {
dbc.report(null, Messages.get().container(Messages.ERR_GET_ACL_ENTRIES_1, "<all resources>"), e);
} finally {
dbc.clear();
}
return result;
}
|
python
|
def _recv(self, line):
"""Invoked by the connection manager to process incoming data."""
if line == '':
return
# Only handle query response messages, which are also sent on remote status
# updates (e.g. user manually pressed a keypad button)
if line[0] != Lutron.OP_RESPONSE:
_LOGGER.debug("ignoring %s" % line)
return
parts = line[1:].split(',')
cmd_type = parts[0]
integration_id = int(parts[1])
args = parts[2:]
if cmd_type not in self._ids:
_LOGGER.info("Unknown cmd %s (%s)" % (cmd_type, line))
return
ids = self._ids[cmd_type]
if integration_id not in ids:
_LOGGER.warning("Unknown id %d (%s)" % (integration_id, line))
return
obj = ids[integration_id]
handled = obj.handle_update(args)
|
java
|
public IllegalStateException asJDKException() {
IllegalStateException e = new IllegalStateException(getMessage()) {
@Override
public synchronized Throwable fillInStackTrace() {
return this;
}
};
e.setStackTrace(getStackTrace());
return e;
}
|
python
|
def date(f, *args, **kwargs):
"""Automatically log progress on function entry and exit with date- and
time- stamp. Default logging value: info.
*Logging with values contained in the parameters of the decorated function*
Message (args[0]) may be a string to be formatted with parameters passed to
the decorated function. Each '{varname}' will be replaced by the value of
the parameter of the same name.
*Keyword parameters*
- log :: integer
- Specifies a custom level of logging to pass to the active logger.
- Default: INFO
*Exceptions:*
- IndexError and ValueError
- will be returned if *args contains a string that does not correspond to
a parameter name of the decorated function, or if there are more '{}'s
than there are *args.
"""
kwargs.update({'print_time': True})
return _stump(f, *args, **kwargs)
|
python
|
def set_pane_position(self, config_id):
"""Adjusts the position of a GTK Pane to a value stored in the runtime config file. If there was no value
stored, the pane's position is set to a default value.
:param config_id: The pane identifier saved in the runtime config file
"""
default_pos = constants.DEFAULT_PANE_POS[config_id]
position = global_runtime_config.get_config_value(config_id, default_pos)
pane_id = constants.PANE_ID[config_id]
self.view[pane_id].set_position(position)
|
java
|
private void parseJSON(JsonObject jsonObject) {
for (JsonObject.Member member : jsonObject) {
JsonValue value = member.getValue();
if (value.isNull()) {
continue;
}
try {
String memberName = member.getName();
if (memberName.equals("id")) {
this.versionID = value.asString();
} else if (memberName.equals("sha1")) {
this.sha1 = value.asString();
} else if (memberName.equals("name")) {
this.name = value.asString();
} else if (memberName.equals("size")) {
this.size = Double.valueOf(value.toString()).longValue();
} else if (memberName.equals("created_at")) {
this.createdAt = BoxDateFormat.parse(value.asString());
} else if (memberName.equals("modified_at")) {
this.modifiedAt = BoxDateFormat.parse(value.asString());
} else if (memberName.equals("trashed_at")) {
this.trashedAt = BoxDateFormat.parse(value.asString());
} else if (memberName.equals("modified_by")) {
JsonObject userJSON = value.asObject();
String userID = userJSON.get("id").asString();
BoxUser user = new BoxUser(getAPI(), userID);
this.modifiedBy = user.new Info(userJSON);
}
} catch (ParseException e) {
assert false : "A ParseException indicates a bug in the SDK.";
}
}
}
|
java
|
public static MethodParameter forMethodOrConstructor(Object methodOrConstructor, int parameterIndex) {
if (methodOrConstructor instanceof Method) {
return new MethodParameter((Method) methodOrConstructor, parameterIndex);
} else if (methodOrConstructor instanceof Constructor) {
return new MethodParameter((Constructor<?>) methodOrConstructor, parameterIndex);
} else {
throw new IllegalArgumentException(
"Given object [" + methodOrConstructor + "] is neither a Method nor a Constructor");
}
}
|
python
|
def Runtime_setCustomObjectFormatterEnabled(self, enabled):
"""
Function path: Runtime.setCustomObjectFormatterEnabled
Domain: Runtime
Method name: setCustomObjectFormatterEnabled
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'enabled' (type: boolean) -> No description
No return value.
"""
assert isinstance(enabled, (bool,)
), "Argument 'enabled' must be of type '['bool']'. Received type: '%s'" % type(
enabled)
subdom_funcs = self.synchronous_command(
'Runtime.setCustomObjectFormatterEnabled', enabled=enabled)
return subdom_funcs
|
java
|
public void fillMeasures(String measure, JSONObject jsonContent, Pattern pattern, HashMap<String,Double> i){
String tem = (String)jsonContent.get(measure);
if(tem != null){
Matcher tM = pattern.matcher(tem);
if(tM.find() && !tM.group(1).isEmpty()){
try{
i.put(measure, Double.valueOf(tM.group(1)));
}catch(NumberFormatException e){
e.printStackTrace();
}
}
}
}
|
java
|
@Override
public ResourceSet<CompositionHook> read(final TwilioRestClient client) {
return new ResourceSet<>(this, client, firstPage(client));
}
|
java
|
public synchronized void remoteServerRegistrations(RESTRequest request) {
Iterator<Entry<NotificationTargetInformation, List<ServerNotification>>> serverNotificationsIter = serverNotifications.entrySet().iterator();
while (serverNotificationsIter.hasNext()) {
Entry<NotificationTargetInformation, List<ServerNotification>> entry = serverNotificationsIter.next();
NotificationTargetInformation nti = entry.getKey();
// Check whether the producer of the notification is local or remote.
if (nti.getRoutingInformation() == null) {
//Traverse the list for that ObjectName
ObjectName objName = RESTHelper.objectNameConverter(nti.getNameAsString(), false, null);
if (MBeanServerHelper.isRegistered(objName)) {
for (ServerNotification notification : entry.getValue()) {
MBeanServerHelper.removeServerNotification(objName,
notification.listener,
(NotificationFilter) getObject(notification.filter, null, null),
getObject(notification.handback, null, null),
null);
}
}
else {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "The MBean is not registered with the MBean server.");
}
}
} else {
// Remove the notification listener from the Target-Client Manager through EventAdmin
MBeanRoutedNotificationHelper helper = MBeanRoutedNotificationHelper.getMBeanRoutedNotificationHelper();
for (ServerNotification notification : entry.getValue()) {
helper.removeRoutedServerNotificationListener(nti,
notification.listener,
(NotificationFilter) getObject(notification.filter, null, null),
getObject(notification.handback, null, null),
null);
}
}
}
//Clear the map
serverNotifications.clear();
//We don't have any more server notifications, so we can clear our library
clearObjectLibrary();
}
|
python
|
def _graphics_equal(gfx1, gfx2):
'''
Test if two graphics devices should be considered the same device
'''
def _filter_graphics(gfx):
'''
When the domain is running, the graphics element may contain additional properties
with the default values. This function will strip down the default values.
'''
gfx_copy = copy.deepcopy(gfx)
defaults = [{'node': '.', 'attrib': 'port', 'values': ['5900', '-1']},
{'node': '.', 'attrib': 'address', 'values': ['127.0.0.1']},
{'node': 'listen', 'attrib': 'address', 'values': ['127.0.0.1']}]
for default in defaults:
node = gfx_copy.find(default['node'])
attrib = default['attrib']
if node is not None and (attrib not in node.attrib or node.attrib[attrib] in default['values']):
node.set(attrib, default['values'][0])
return gfx_copy
return ElementTree.tostring(_filter_graphics(gfx1)) == ElementTree.tostring(_filter_graphics(gfx2))
|
java
|
static void export(String path, List<Queue> queueList, DbConn cnx) throws JqmXmlException
{
// Argument tests
if (path == null)
{
throw new IllegalArgumentException("file path cannot be null");
}
if (queueList == null || queueList.isEmpty())
{
throw new IllegalArgumentException("queue list cannot be null or empty");
}
if (cnx == null)
{
throw new IllegalArgumentException("database connection cannot be null");
}
// Create XML document
Element root = new Element("jqm");
Document document = new Document(root);
Element queues = new Element("queues");
root.addContent(queues);
for (Queue q : queueList)
{
Element queue = getQueueElement(q, cnx);
queues.addContent(queue);
}
// Done: save the file
try
{
XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
out.output(document, new FileOutputStream(path));
}
catch (java.io.IOException e)
{
throw new JqmXmlException("Coul npot save the XML file", e);
}
}
|
python
|
def prepare_kernel_string(kernel_name, kernel_string, params, grid, threads, block_size_names):
""" prepare kernel string for compilation
Prepends the kernel with a series of C preprocessor defines specific
to this kernel instance:
* the thread block dimensions
* the grid dimensions
* tunable parameters
Additionally the name of kernel is replace with an instance specific name. This
is done to prevent that the kernel compilation could be skipped by PyCUDA and/or PyOpenCL,
which may use caching to save compilation time. This feature could lead to strange bugs
in the source code if the name of the kernel is also used for other stuff.
:param kernel_name: Name of the kernel.
:type kernel_name: string
:param kernel_string: One of the source files of the kernel as a string containing code.
:type kernel_string: string
:param params: A dictionary containing the tunable parameters specific to this instance.
:type params: dict
:param grid: A tuple with the grid dimensions for this specific instance.
:type grid: tuple(x,y,z)
:param threads: A tuple with the thread block dimensions for this specific instance.
:type threads: tuple(x,y,z)
:param block_size_names: A tuple with the names of the thread block dimensions used
in the code. By default this is ["block_size_x", ...], but the user
may supply different names if they prefer.
:type block_size_names: tuple(string)
:returns: A string containing the source code made specific to this kernel instance.
:rtype: string
"""
logging.debug('prepare_kernel_string called for %s', kernel_name)
grid_dim_names = ["grid_size_x", "grid_size_y", "grid_size_z"]
for i, g in enumerate(grid):
kernel_string = "#define " + grid_dim_names[i] + " " + str(g) + "\n" + kernel_string
for i, g in enumerate(threads):
kernel_string = "#define " + block_size_names[i] + " " + str(g) + "\n" + kernel_string
for k, v in params.items():
if k not in block_size_names:
kernel_string = "#define " + k + " " + str(v) + "\n" + kernel_string
name = kernel_name
#name = kernel_name + "_" + get_instance_string(params)
#kernel_string = kernel_string.replace(kernel_name, name)
return name, kernel_string
|
java
|
private void putPlaceholdersIntoMap(
MsgNode originalMsg,
Iterable<? extends SoyMsgPart> parts,
Map<String, Function<Expression, Statement>> placeholderNameToPutStatement) {
for (SoyMsgPart child : parts) {
if (child instanceof SoyMsgRawTextPart || child instanceof SoyMsgPluralRemainderPart) {
// raw text doesn't have placeholders and remainders use the same placeholder as plural they
// are a member of.
continue;
}
if (child instanceof SoyMsgPluralPart) {
putPluralPartIntoMap(originalMsg, placeholderNameToPutStatement, (SoyMsgPluralPart) child);
} else if (child instanceof SoyMsgSelectPart) {
putSelectPartIntoMap(originalMsg, placeholderNameToPutStatement, (SoyMsgSelectPart) child);
} else if (child instanceof SoyMsgPlaceholderPart) {
putPlaceholderIntoMap(
originalMsg, placeholderNameToPutStatement, (SoyMsgPlaceholderPart) child);
} else {
throw new AssertionError("unexpected child: " + child);
}
}
}
|
java
|
protected void connectToJMS(String clientId) throws MessagingException {
// Check to see if already connected
//
if (connected == true) return;
try {
// Get a JMS Connection
//
connection = getConnection();
if(clientId != null) {
connection.setClientID(clientId);
}
connection.start();
connected = true;
logger.debug("connectToJMS - connected");
} catch (JMSException e) {
connected = false;
logger.error("JMSManager.connectToJMS - Exception occurred:");
throw new MessagingException(e.getMessage(), e);
}
}
|
java
|
@Override
public Collection<String> getCliqueFeatures(PaddedList<IN> cInfo, int loc, Clique clique) {
Collection<String> features = new HashSet<String>();
boolean doFE = cInfo.get(0).containsKey(DomainAnnotation.class);
String domain = (doFE ? cInfo.get(0).get(DomainAnnotation.class) : null);
// System.err.println(doFE+"\t"+domain);
if (clique == cliqueC) {
//200710: tried making this clique null; didn't improve performance (rafferty)
Collection<String> c = featuresC(cInfo, loc);
addAllInterningAndSuffixing(features, c, "C");
if (doFE) {
addAllInterningAndSuffixing(features, c, domain+"-C");
}
} else if (clique == cliqueCpC) {
Collection<String> c = featuresCpC(cInfo, loc);
addAllInterningAndSuffixing(features, c, "CpC");
if (doFE) {
addAllInterningAndSuffixing(features, c, domain+"-CpC");
}
c = featuresCnC(cInfo, loc-1);
addAllInterningAndSuffixing(features, c, "CnC");
if (doFE) {
addAllInterningAndSuffixing(features, c, domain+"-CnC");
}
} else if (clique == cliqueCp2C) {
Collection<String> c = featuresCp2C(cInfo, loc);
addAllInterningAndSuffixing(features, c, "Cp2C");
if (doFE) {
addAllInterningAndSuffixing(features, c, domain+"-Cp2C");
}
} else if (clique == cliqueCp3C) {
Collection<String> c = featuresCp3C(cInfo, loc);
addAllInterningAndSuffixing(features, c, "Cp3C");
if (doFE) {
addAllInterningAndSuffixing(features, c, domain+"-Cp3C");
}
} else if (clique == cliqueCp4C) {
Collection<String> c = featuresCp4C(cInfo, loc);
addAllInterningAndSuffixing(features, c, "Cp4C");
if (doFE) {
addAllInterningAndSuffixing(features, c, domain+"-Cp4C");
}
} else if (clique == cliqueCp5C) {
Collection<String> c = featuresCp5C(cInfo, loc);
addAllInterningAndSuffixing(features, c, "Cp5C");
if (doFE) {
addAllInterningAndSuffixing(features, c, domain+"-Cp5C");
}
} else if (clique == cliqueCpCp2C) {
Collection<String> c = featuresCpCp2C(cInfo, loc);
addAllInterningAndSuffixing(features, c, "CpCp2C");
if (doFE) {
addAllInterningAndSuffixing(features, c, domain+"-CpCp2C");
}
c = featuresCpCnC(cInfo, loc-1);
addAllInterningAndSuffixing(features, c, "CpCnC");
if (doFE) {
addAllInterningAndSuffixing(features, c, domain+"-CpCnC");
}
} else if (clique == cliqueCpCp2Cp3C) {
Collection<String> c = featuresCpCp2Cp3C(cInfo, loc);
addAllInterningAndSuffixing(features, c, "CpCp2Cp3C");
if (doFE) {
addAllInterningAndSuffixing(features, c, domain+"-CpCp2Cp3C");
}
} else if (clique == cliqueCpCp2Cp3Cp4C) {
Collection<String> c = featuresCpCp2Cp3Cp4C(cInfo, loc);
addAllInterningAndSuffixing(features, c, "CpCp2Cp3Cp4C");
if (doFE) {
addAllInterningAndSuffixing(features, c, domain+"-CpCp2Cp3Cp4C");
}
}
// System.err.println(StringUtils.join(features,"\n")+"\n");
return features;
}
|
python
|
def register(self, module, *args, **kwargs):
"""
Register a new module.
:param module: Either a string module name, or a module class,
or a module instance (in which case args and kwargs are
invalid).
:param kwargs: Settings for the module.
:returns: module instance
"""
from i3pystatus.text import Text
if not module:
return
# Merge the module's hints with the default hints
# and overwrite any duplicates with the hint from the module
hints = self.default_hints.copy() if self.default_hints else {}
hints.update(kwargs.get('hints', {}))
if hints:
kwargs['hints'] = hints
try:
return self.modules.append(module, *args, **kwargs)
except Exception as e:
log.exception(e)
return self.modules.append(Text(
color="#FF0000",
text="{i3py_mod}: Fatal Error - {ex}({msg})".format(
i3py_mod=module,
ex=e.__class__.__name__,
msg=e
)
))
|
java
|
public static Window display(final String title, final int width,
final int height,
final Picture picture) {
return play(title, width, height, new Animation() {
@Override
public Picture getPicture() {
return picture;
}
@Override
public void update(final double time, final double delta) {
// do nothing, the picture is static.
}
});
}
|
python
|
def tr(text, context='@default'):
"""We define a tr function alias here since the utilities implementation
below is not a class and does not inherit from QObject.
.. note:: see http://tinyurl.com/pyqt-differences
:param text: String to be translated
:type text: str, unicode
:param context: A context for the translation. Since a same can be
translated to different text depends on the context.
:type context: str
:returns: Translated version of the given string if available, otherwise
the original string.
:rtype: str, unicode
"""
# noinspection PyCallByClass,PyTypeChecker,PyArgumentList
if type(text) != str:
text = str(text)
translated_text = QCoreApplication.translate(context, text)
# Check if there is missing container. If so, return the original text.
# See #3164
if text.count('%') == translated_text.count('%'):
return translated_text
else:
content = (
'There is a problem in the translation text.\n'
'The original text: "%s".\n'
'The translation: "%s".\n'
'The number of %% character does not match (%s and %s).'
'Please check the translation in transifex for %s.' % (
text,
translated_text,
text.count('%'),
translated_text.count('%s'),
locale()
))
LOGGER.warning(content)
return text
|
java
|
@Override
public EClass getMessagingSerializerPluginConfiguration() {
if (messagingSerializerPluginConfigurationEClass == null) {
messagingSerializerPluginConfigurationEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(StorePackage.eNS_URI).getEClassifiers().get(99);
}
return messagingSerializerPluginConfigurationEClass;
}
|
python
|
def is_expired_token(self, client):
"""
For a given client will test whether or not the token
has expired.
This is for testing a client object and does not look up
from client_id. You can use _get_client_from_cache() to
lookup a client from client_id.
"""
if 'expires' not in client:
return True
expires = dateutil.parser.parse(client['expires'])
if expires < datetime.datetime.now():
return True
return False
|
java
|
public static BitmapDescriptor vectorToBitmap(@DrawableRes int drawableRes, @ColorRes int colorRes) {
Drawable vectorDrawable = VectorDrawableCompat.create(AbstractApplication.get().getResources(), drawableRes, null);
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
DrawableCompat.setTint(vectorDrawable, AbstractApplication.get().getResources().getColor(colorRes));
vectorDrawable.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
|
python
|
def get_snapshot_table(account):
"""Generates a table for printing account summary data"""
table = formatting.KeyValueTable(["Name", "Value"], title="Account Snapshot")
table.align['Name'] = 'r'
table.align['Value'] = 'l'
table.add_row(['Company Name', account.get('companyName', '-')])
table.add_row(['Balance', utils.lookup(account, 'pendingInvoice', 'startingBalance')])
table.add_row(['Upcoming Invoice', utils.lookup(account, 'pendingInvoice', 'invoiceTotalAmount')])
table.add_row(['Image Templates', account.get('blockDeviceTemplateGroupCount', '-')])
table.add_row(['Dedicated Hosts', account.get('dedicatedHostCount', '-')])
table.add_row(['Hardware', account.get('hardwareCount', '-')])
table.add_row(['Virtual Guests', account.get('virtualGuestCount', '-')])
table.add_row(['Domains', account.get('domainCount', '-')])
table.add_row(['Network Storage Volumes', account.get('networkStorageCount', '-')])
table.add_row(['Open Tickets', account.get('openTicketCount', '-')])
table.add_row(['Network Vlans', account.get('networkVlanCount', '-')])
table.add_row(['Subnets', account.get('subnetCount', '-')])
table.add_row(['Users', account.get('userCount', '-')])
return table
|
python
|
def _validate(self):
"""
Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object.
"""
# disable methods matching before validation
self._disable_patching = True
# validation by Invariant.validate
self._validate_base(self)
# enable methods matching after validation
self._disable_patching = False
|
java
|
public double getBucketMinimum(int i) {
if (i > 0) {
return bucketLimits[i - 1];
} else if (getBucketCount(i) == 0) {
// Edge case -- first bucket, but it is empty
return Double.MIN_VALUE;
} else {
// First bucket is non-empty
return getMinimum();
}
}
|
java
|
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case AfplibPackage.GSMT__MCPT:
return MCPT_EDEFAULT == null ? mcpt != null : !MCPT_EDEFAULT.equals(mcpt);
}
return super.eIsSet(featureID);
}
|
python
|
def extract_spans(html_string):
"""
Creates a list of the spanned cell groups of [row, column] pairs.
Parameters
----------
html_string : str
Returns
-------
list of lists of lists of int
"""
try:
from bs4 import BeautifulSoup
except ImportError:
print("ERROR: You must have BeautifulSoup to use html2data")
return
soup = BeautifulSoup(html_string, 'html.parser')
table = soup.find('table')
if not table:
return []
trs = table.findAll('tr')
if len(trs) == 0:
return []
spans = []
for tr in range(len(trs)):
if tr == 0:
ths = trs[tr].findAll('th')
if len(ths) == 0:
ths = trs[tr].findAll('td')
tds = ths
else:
tds = trs[tr].findAll('td')
column = 0
for td in tds:
r_span_count = 1
c_span_count = 1
current_column = column
if td.has_attr('rowspan'):
r_span_count = int(td['rowspan'])
if td.has_attr('colspan'):
c_span_count = int(td['colspan'])
column += c_span_count
else:
column += 1
new_span = []
for r_index in range(tr, tr + r_span_count):
for c_index in range(current_column, column):
if not get_span(spans, r_index, c_index):
new_span.append([r_index, c_index])
if len(new_span) > 0:
spans.append(new_span)
return spans
|
java
|
public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
throws IOException {
// Get the MediaService.
MediaServiceInterface mediaService = adWordsServices.get(session, MediaServiceInterface.class);
// Create HTML5 media.
byte[] html5Zip =
com.google.api.ads.common.lib.utils.Media.getMediaDataFromUrl("https://goo.gl/9Y7qI2");
// Create a media bundle containing the zip file with all the HTML5 components.
MediaBundle mediaBundle = new MediaBundle();
mediaBundle.setData(html5Zip);
mediaBundle.setType(MediaMediaType.MEDIA_BUNDLE);
// Upload HTML5 zip.
mediaBundle = (MediaBundle) mediaService.upload(new Media[] {mediaBundle})[0];
// Display HTML5 zip.
Map<MediaSize, Dimensions> dimensions = Maps.toMap(mediaBundle.getDimensions());
System.out.printf(
"HTML5 media with ID %d, dimensions '%dx%d', and MIME type '%s' "
+ "was uploaded.%n",
mediaBundle.getMediaId(), dimensions.get(MediaSize.FULL).getWidth(),
dimensions.get(MediaSize.FULL).getHeight(), mediaBundle.getMimeType());
}
|
python
|
def platform_information(_linux_distribution=None):
""" detect platform information from remote host """
linux_distribution = _linux_distribution or platform.linux_distribution
distro, release, codename = linux_distribution()
if not distro:
distro, release, codename = parse_os_release()
if not codename and 'debian' in distro.lower(): # this could be an empty string in Debian
debian_codenames = {
'10': 'buster',
'9': 'stretch',
'8': 'jessie',
'7': 'wheezy',
'6': 'squeeze',
}
major_version = release.split('.')[0]
codename = debian_codenames.get(major_version, '')
# In order to support newer jessie/sid or wheezy/sid strings we test this
# if sid is buried in the minor, we should use sid anyway.
if not codename and '/' in release:
major, minor = release.split('/')
if minor == 'sid':
codename = minor
else:
codename = major
if not codename and 'oracle' in distro.lower(): # this could be an empty string in Oracle linux
codename = 'oracle'
if not codename and 'virtuozzo linux' in distro.lower(): # this could be an empty string in Virtuozzo linux
codename = 'virtuozzo'
if not codename and 'arch' in distro.lower(): # this could be an empty string in Arch linux
codename = 'arch'
return (
str(distro).rstrip(),
str(release).rstrip(),
str(codename).rstrip()
)
|
java
|
@Override
public double[] getVotesForInstance(Instance inst) {
if (m_weights == null) {
return new double[inst.numClasses()];
}
double[] result = (inst.classAttribute().isNominal())
? new double[inst.numClasses()]
: new double[1];
if (inst.classAttribute().isNumeric()) {
double wx = dotProd(inst, m_weights[0], inst.classIndex());// * m_wScale;
double z = (wx + m_bias[0]);
result[0] = z;
return result;
}
for (int i = 0; i < m_weights.length; i++){
double wx = dotProd(inst, m_weights[i], inst.classIndex());// * m_wScale;
double z = (wx + m_bias[i]);
if (z <= 0) {
// z = 0;
if (m_loss == LOGLOSS) {
//result[0] = 1.0 / (1.0 + Math.exp(z));
//result[1] = 1.0 - result[0];
result[i] = 1.0 - 1.0 / (1.0 + Math.exp(z));
} else {
//result[0] = 1;
result[i] = 0;
}
} else {
if (m_loss == LOGLOSS) {
//result[1] = 1.0 / (1.0 + Math.exp(-z));
//result[0] = 1.0 - result[1];
result[i] = 1.0 / (1.0 + Math.exp(-z));
} else {
//result[1] = 1;
result[i] = 1;
}
}
}
return result;
}
|
python
|
def _set_current(self, new_current):
"""
Change the current default prefix, for internal usage
Args:
new_current(str): Name of the new current prefix, it must already
exist
Returns:
None
Raises:
PrefixNotFound: if the given prefix name does not exist in the
workdir
"""
new_cur_full_path = self.join(new_current)
if not os.path.exists(new_cur_full_path):
raise PrefixNotFound(
'Prefix "%s" does not exist in workdir %s' %
(new_current, self.path)
)
if os.path.lexists(self.join('current')):
os.unlink(self.join('current'))
os.symlink(new_current, self.join('current'))
self.current = new_current
|
java
|
@Override
public String handleEventMessage(String msg, Object msgdoc,
Map<String, String> metainfo) throws EventHandlerException {
return null;
}
|
python
|
def bands(self):
"""
An iterable of all bands in this scale
"""
if self._bands is None:
self._bands = self._compute_bands()
return self._bands
|
python
|
def encodeAA(seq_vec, maxlen=None, seq_align="start", encode_type="one_hot"):
"""Convert the Amino-acid sequence into 1-hot-encoding numpy array
# Arguments
seq_vec: List of strings/amino-acid sequences
maxlen: Maximum sequence length. See `pad_sequences` for more detail
seq_align: How to align the sequences of variable lengths. See `pad_sequences` for more detail
encode_type: can be `"one_hot"` or `token` for token encoding of codons (incremental integer ).
# Returns
numpy.ndarray of shape `(len(seq_vec), maxlen, 22)`
"""
return encodeSequence(seq_vec,
vocab=AMINO_ACIDS,
neutral_vocab="_",
maxlen=maxlen,
seq_align=seq_align,
pad_value="_",
encode_type=encode_type)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.