language
stringclasses 2
values | func_code_string
stringlengths 63
466k
|
---|---|
java | public void setTrueValue(String trueValue) {
this.trueValue = trueValue;
this.trueValueChars = trueValue.toCharArray();
this.trueValueBytes = toBytes(trueValue, trueValue);
} |
java | public Method findAnnotatedMethod(Class<?> clazz, Class<? extends Annotation> anno) {
for (Method meth : clazz.getMethods()) {
if (meth.isAnnotationPresent(anno)) {
return meth;
}
}
return null;
} |
java | protected final QB generateQuery(final Map<String, List<Object>> query) {
QB queryBuilder = null;
if (this.queryAttributeMapping != null) {
for (final Map.Entry<String, Set<String>> queryAttrEntry : this.queryAttributeMapping.entrySet()) {
final String queryAttr = queryAttrEntry.getKey();
final List<Object> queryValues = query.get(queryAttr);
if (queryValues != null) {
final Set<String> dataAttributes = queryAttrEntry.getValue();
if (dataAttributes == null) {
queryBuilder = this.appendCanonicalizedAttributeToQuery(queryBuilder, queryAttr, null, queryValues);
} else {
for (final String dataAttribute : dataAttributes) {
queryBuilder = this.appendCanonicalizedAttributeToQuery(queryBuilder, queryAttr, dataAttribute, queryValues);
}
}
} else if (this.requireAllQueryAttributes) {
this.logger.debug("Query " + query + " does not contain all nessesary attributes as specified by queryAttributeMapping " + this.queryAttributeMapping + ", null will be returned for the queryBuilder");
return null;
}
}
} else if (this.useAllQueryAttributes) {
for (final Map.Entry<String, List<Object>> queryAttrEntry : query.entrySet()) {
final String queryKey = queryAttrEntry.getKey();
final List<Object> queryValues = queryAttrEntry.getValue();
queryBuilder = this.appendCanonicalizedAttributeToQuery(queryBuilder, queryKey, queryKey, queryValues);
}
}
if (this.logger.isDebugEnabled()) {
this.logger.debug("Generated query builder '" + queryBuilder + "' from query Map " + query + ".");
}
return queryBuilder;
} |
python | def BROKER_TYPE(self):
"""Custom setting allowing switch between rabbitmq, redis"""
broker_type = get('BROKER_TYPE', DEFAULT_BROKER_TYPE)
if broker_type not in SUPPORTED_BROKER_TYPES:
log.warn("Specified BROKER_TYPE {} not supported. Backing to default {}".format(
broker_type, DEFAULT_BROKER_TYPE))
return DEFAULT_BROKER_TYPE
else:
return broker_type |
python | def load(self, host, exact_host_match=False):
""" Load a config for a hostname or url.
This method calls :func:`ftr_get_config` and :meth`append`
internally. Refer to their docs for details on parameters.
"""
# Can raise a SiteConfigNotFound, intentionally bubbled.
config_string, host_string = ftr_get_config(host, exact_host_match)
if config_string is None:
LOGGER.error(u'Error while loading configuration.',
extra={'siteconfig': host_string})
return
self.append(ftr_string_to_instance(config_string)) |
java | public BidiRun getLogicalRun(int logicalPosition)
{
verifyValidParaOrLine();
verifyRange(logicalPosition, 0, length);
return BidiLine.getLogicalRun(this, logicalPosition);
} |
python | def as_dict(config):
"""
Converts a ConfigParser object into a dictionary.
The resulting dictionary has sections as keys which point to a dict of the
sections options as key => value pairs.
"""
settings = defaultdict(lambda: {})
for section in config.sections():
for key, val in config.items(section):
settings[section][key] = val
return settings |
java | private void fireUserInputChange() {
if (!internallySettingText && (this.listeners != null)) {
for (Iterator it = this.listeners.iterator(); it.hasNext();) {
UserInputListener userInputListener = (UserInputListener) it.next();
userInputListener.update(this);
}
}
} |
python | def get_pose_error(target_pose, current_pose):
"""
Computes the error corresponding to target pose - current pose as a 6-dim vector.
The first 3 components correspond to translational error while the last 3 components
correspond to the rotational error.
Args:
target_pose: a 4x4 homogenous matrix for the target pose
current_pose: a 4x4 homogenous matrix for the current pose
Returns:
A 6-dim numpy array for the pose error.
"""
error = np.zeros(6)
# compute translational error
target_pos = target_pose[:3, 3]
current_pos = current_pose[:3, 3]
pos_err = target_pos - current_pos
# compute rotational error
r1 = current_pose[:3, 0]
r2 = current_pose[:3, 1]
r3 = current_pose[:3, 2]
r1d = target_pose[:3, 0]
r2d = target_pose[:3, 1]
r3d = target_pose[:3, 2]
rot_err = 0.5 * (np.cross(r1, r1d) + np.cross(r2, r2d) + np.cross(r3, r3d))
error[:3] = pos_err
error[3:] = rot_err
return error |
python | def path(self, value):
"""
Setter for **self.__path** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format("path", value)
self.__path = value |
python | def populate_tree(self, parentItem, children_list):
"""Recursive method to create each item (and associated data) in the tree."""
for child_key in children_list:
self.item_depth += 1
(filename, line_number, function_name, file_and_line, node_type
) = self.function_info(child_key)
((total_calls, total_calls_dif), (loc_time, loc_time_dif), (cum_time,
cum_time_dif)) = self.format_output(child_key)
child_item = TreeWidgetItem(parentItem)
self.item_list.append(child_item)
self.set_item_data(child_item, filename, line_number)
# FIXME: indexes to data should be defined by a dictionary on init
child_item.setToolTip(0, _('Function or module name'))
child_item.setData(0, Qt.DisplayRole, function_name)
child_item.setIcon(0, self.icon_list[node_type])
child_item.setToolTip(1, _('Time in function '\
'(including sub-functions)'))
child_item.setData(1, Qt.DisplayRole, cum_time)
child_item.setTextAlignment(1, Qt.AlignRight)
child_item.setData(2, Qt.DisplayRole, cum_time_dif[0])
child_item.setForeground(2, QColor(cum_time_dif[1]))
child_item.setTextAlignment(2, Qt.AlignLeft)
child_item.setToolTip(3, _('Local time in function '\
'(not in sub-functions)'))
child_item.setData(3, Qt.DisplayRole, loc_time)
child_item.setTextAlignment(3, Qt.AlignRight)
child_item.setData(4, Qt.DisplayRole, loc_time_dif[0])
child_item.setForeground(4, QColor(loc_time_dif[1]))
child_item.setTextAlignment(4, Qt.AlignLeft)
child_item.setToolTip(5, _('Total number of calls '\
'(including recursion)'))
child_item.setData(5, Qt.DisplayRole, total_calls)
child_item.setTextAlignment(5, Qt.AlignRight)
child_item.setData(6, Qt.DisplayRole, total_calls_dif[0])
child_item.setForeground(6, QColor(total_calls_dif[1]))
child_item.setTextAlignment(6, Qt.AlignLeft)
child_item.setToolTip(7, _('File:line '\
'where function is defined'))
child_item.setData(7, Qt.DisplayRole, file_and_line)
#child_item.setExpanded(True)
if self.is_recursive(child_item):
child_item.setData(7, Qt.DisplayRole, '(%s)' % _('recursion'))
child_item.setDisabled(True)
else:
callees = self.find_callees(child_key)
if self.item_depth < 3:
self.populate_tree(child_item, callees)
elif callees:
child_item.setChildIndicatorPolicy(child_item.ShowIndicator)
self.items_to_be_shown[id(child_item)] = callees
self.item_depth -= 1 |
java | @SuppressWarnings("rawtypes")
@Override
public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {
annotation.setInvocationCount(StringUtils.countMatches(getBrowser(), ",") + 1);
} |
java | public void dispatchEvent(final ManagerEvent event)
{
if (logger.isDebugEnabled())
{
logger.debug("dispatch=" + event.toString()); //$NON-NLS-1$
}
// take a copy of the listeners so they can be modified whilst we
// iterate over them
// The iteration may call some long running processes.
final List<FilteredManagerListenerWrapper> listenerCopy;
synchronized (this.listeners)
{
listenerCopy = this.listeners.getCopyAsList();
}
try
{
final LogTime totalTime = new LogTime();
CountDownLatch latch = new CountDownLatch(listenerCopy.size());
for (final FilteredManagerListenerWrapper filter : listenerCopy)
{
if (filter.requiredEvents.contains(event.getClass()))
{
dispatchEventOnThread(event, filter, latch);
}
else
{
// this listener didn't want the event, so just decrease the
// countdown
latch.countDown();
}
}
latch.await();
if (totalTime.timeTaken() > 500)
{
logger.warn("Too long to process event " + event + " time taken: " + totalTime.timeTaken()); //$NON-NLS-1$ //$NON-NLS-2$
}
}
catch (InterruptedException e)
{
Thread.interrupted();
}
} |
python | def dead_links(self):
"""Generate the coordinates of all dead links leaving working chips.
Any link leading to a dead chip will also be included in the list of
dead links. In non-torroidal SpiNNaker sysmtes (e.g. single SpiNN-5
boards), links on the periphery of the system will be marked as dead.
Yields
------
(x, y, :py:class:`rig.links.Links`)
A working link leaving a chip from the perspective of the chip. For
example ``(0, 0, Links.north)`` would be the link going north from
chip (0, 0) to chip (0, 1).
"""
for (x, y), chip_info in iteritems(self):
for link in Links:
if link not in chip_info.working_links:
yield (x, y, link) |
java | public String getFirst(String name, String defaultValue)
{
String value = getFirst(name);
if (value == null) {
value = defaultValue;
}
return value;
} |
python | def _parse_binary(v, header_d):
""" Parses binary string.
Note:
<str> for py2 and <binary> for py3.
"""
# This is often a no-op, but it ocassionally converts numbers into strings
v = nullify(v)
if v is None:
return None
if six.PY2:
try:
return six.binary_type(v).strip()
except UnicodeEncodeError:
return six.text_type(v).strip()
else:
# py3
try:
return six.binary_type(v, 'utf-8').strip()
except UnicodeEncodeError:
return six.text_type(v).strip() |
java | public boolean isEquivalent(CompilationUnit other) {
if (!destination.getAbsoluteFile().equals(other.destination.getAbsoluteFile())) return false;
if (encoding != null ? !encoding.equals(other.encoding) : other.encoding != null) return false;
if (resourceReader != null ? !resourceReader.equals(other.resourceReader) : other.resourceReader != null)
return false;
if (!options.equals(other.options)) return false;
if (sourceMapFile != null ? !sourceMapFile.equals(other.sourceMapFile) : other.sourceMapFile != null)
return false;
return sourceLocation.equals(other.sourceLocation);
} |
java | private void getExecutionIdsHelper(final List<Integer> allIds,
final Collection<Pair<ExecutionReference, ExecutableFlow>> collection) {
collection.stream().forEach(ref -> allIds.add(ref.getSecond().getExecutionId()));
Collections.sort(allIds);
} |
python | def circuit_to_pdf_using_qcircuit_via_tex(circuit: circuits.Circuit,
filepath: str,
pdf_kwargs=None,
qcircuit_kwargs=None,
clean_ext=('dvi', 'ps'),
documentclass='article'):
"""Compiles the QCircuit-based latex diagram of the given circuit.
Args:
circuit: The circuit to produce a pdf of.
filepath: Where to output the pdf.
pdf_kwargs: The arguments to pass to generate_pdf.
qcircuit_kwargs: The arguments to pass to
circuit_to_latex_using_qcircuit.
clean_ext: The file extensions to clean up after compilation. By
default, latexmk is used with the '-pdfps' flag, which produces
intermediary dvi and ps files.
documentclass: The documentclass of the latex file.
"""
pdf_kwargs = {'compiler': 'latexmk', 'compiler_args': ['-pdfps'],
**({} if pdf_kwargs is None else pdf_kwargs)}
qcircuit_kwargs = {} if qcircuit_kwargs is None else qcircuit_kwargs
tex = circuit_to_latex_using_qcircuit(circuit, **qcircuit_kwargs)
doc = Document(documentclass=documentclass, document_options='dvips')
doc.packages.append(Package('amsmath'))
doc.packages.append(Package('qcircuit'))
doc.append(NoEscape(tex))
doc.generate_pdf(filepath, **pdf_kwargs)
for ext in clean_ext:
try:
os.remove(filepath + '.' + ext)
except (OSError, IOError) as e:
if e.errno != errno.ENOENT:
raise |
java | public com.google.api.ads.adwords.axis.v201809.cm.AssetLink getMandatoryAdText() {
return mandatoryAdText;
} |
python | def _import_next_layer(self, proto, length):
"""Import next layer extractor.
Positional arguments:
* proto -- str, next layer protocol name
* length -- int, valid (not padding) length
Returns:
* bool -- flag if extraction of next layer succeeded
* Info -- info of next layer
* ProtoChain -- protocol chain of next layer
* str -- alias of next layer
"""
if self._exproto == 'null' and self._exlayer == 'None':
from pcapkit.protocols.raw import Raw as NextLayer
else:
from pcapkit.foundation.analysis import analyse as NextLayer
# from pcapkit.foundation.analysis import analyse as NextLayer
if length == 0:
next_ = NoPayload()
elif self._onerror:
next_ = beholder_ng(NextLayer)(self._file, length, _termination=self._sigterm)
else:
next_ = NextLayer(self._file, length, _termination=self._sigterm)
return next_ |
java | @Requires({
"kind != null",
"kind.isOld()",
"list != null"
})
protected void invokeOldValues(ContractKind kind, List<Integer> list) {
List<MethodContractHandle> olds =
contracts.getMethodHandles(kind, methodName, methodDesc, 0);
if (olds.isEmpty()) {
return;
}
for (MethodContractHandle h : olds) {
MethodNode contractMethod = injectContractMethod(h);
int k = h.getKey();
if (!statik) {
loadThis();
}
loadArgs();
invokeContractMethod(contractMethod);
storeLocal(list.get(k));
}
} |
python | def _flush(self):
"""
Decorator for flushing handlers with an lock, catching exceptions
"""
if not self.enabled:
return
try:
try:
self.lock.acquire()
self.flush()
except Exception:
self.log.error(traceback.format_exc())
finally:
if self.lock.locked():
self.lock.release() |
java | @Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case AfplibPackage.GBOX__RES:
return RES_EDEFAULT == null ? res != null : !RES_EDEFAULT.equals(res);
case AfplibPackage.GBOX__XPOS0:
return XPOS0_EDEFAULT == null ? xpos0 != null : !XPOS0_EDEFAULT.equals(xpos0);
case AfplibPackage.GBOX__YPOS0:
return YPOS0_EDEFAULT == null ? ypos0 != null : !YPOS0_EDEFAULT.equals(ypos0);
case AfplibPackage.GBOX__XPOS1:
return XPOS1_EDEFAULT == null ? xpos1 != null : !XPOS1_EDEFAULT.equals(xpos1);
case AfplibPackage.GBOX__YPOS1:
return YPOS1_EDEFAULT == null ? ypos1 != null : !YPOS1_EDEFAULT.equals(ypos1);
case AfplibPackage.GBOX__HAXIS:
return HAXIS_EDEFAULT == null ? haxis != null : !HAXIS_EDEFAULT.equals(haxis);
case AfplibPackage.GBOX__VAXIS:
return VAXIS_EDEFAULT == null ? vaxis != null : !VAXIS_EDEFAULT.equals(vaxis);
}
return super.eIsSet(featureID);
} |
java | private static SqlInfo buildNewSqlInfo(String nameSpace, Node node, Object paramObj) {
return buildSqlInfo(nameSpace, SqlInfo.newInstance(), node, paramObj);
} |
java | public static void main(String[] args) throws Exception {
String datapath = "../data";
String allfile = datapath + "/FNLPDATA/all.seg";
String testfile = datapath + "/FNLPDATA/test.seg";
String trainfile = datapath + "/FNLPDATA/train.seg";
MyFiles.delete(testfile);
MyFiles.delete(trainfile);
MyFiles.delete(allfile);
String dictfile = datapath + "/FNLPDATA/dict.seg";
String segfile = datapath + "/FNLPDATA/temp.seg";
//清理
MyFiles.delete(dictfile);
MyFiles.delete(segfile);
FNLPCorpus corpus = new FNLPCorpus();
//读自有数据
corpus.readOurCorpus(datapath + "/ourdata",".txt","UTF8");
//读分词文件
corpus.readCWS(datapath + "/FNLPDATA/seg",".txt","UTF8");
//读分词+词性文件
corpus.readPOS(datapath + "/FNLPDATA/pos",".txt","UTF8");
//读FNLP数据
corpus.read(datapath + "/FNLPDATA/ctb7.dat", null);
corpus.read(datapath + "/FNLPDATA/WeiboFTB(v1.0)-train.dat", null);
FNLP2BMES.w2BMES(corpus,segfile);
//FNLP2BMES.w2BMES(corpus,segfile_w); //?
//词典转BMES
//搜狗词典
DICT dict = new DICT();
String sougou = datapath + "/FNLPDATA/dict/SogouLabDic.dic.raw";
// dict.readSougou(sougou,2,3,"sougou");
//互动词典
String hudong = datapath + "/FNLPDATA/dict/hudong.dic.all";
// dict.readSougou(hudong,2,3,"");
//添加其他词典
dict.readDictionary(datapath + "/FNLPDATA/dict",".dic");
//添加其他词典
// dict.readDictionaryWithFrequency(datapath + "/FNLPDATA/dict",".dic.freq");
//添加词性字典
dict.readPOSDICT(datapath + "/FNLPDATA/词性字典", ".txt");
dict.readPOSDICT(datapath + "/FNLPDATA/dict-sogou-input/txt", ".txt");
dict.toBMES(dictfile,3);
new File(dictfile).deleteOnExit();
//合并训练文件
List<File> files = MyFiles.getAllFiles(datapath + "/FNLPDATA/", ".seg");
MyFiles.combine(trainfile,files.toArray(new File[files.size()]));
//生成新字典
String dicfile = datapath + "/FNLPDATA/train.dict";
DICT.BMES2DICT(trainfile,dicfile);
//处理测试数据
FNLPCorpus corpust = new FNLPCorpus();
//读自有数据
corpust.read(datapath + "/FNLPDATA/WeiboFTB(v1.0)-test.dat", null);
FNLP2BMES.w2BMES(corpust,testfile);
System.out.println(new Date().toString());
System.out.println("Done!");
} |
java | public static void close(@Nullable Connection con) throws SQLException {
if (con != null && !con.isClosed()) {
if (!con.getAutoCommit()) {
con.rollback();
con.setAutoCommit(true);
}
con.close();
}
} |
java | public OvhUserWithPassword serviceName_user_userId_changePassword_POST(String serviceName, String userId) throws IOException {
String qPath = "/dbaas/queue/{serviceName}/user/{userId}/changePassword";
StringBuilder sb = path(qPath, serviceName, userId);
String resp = exec(qPath, "POST", sb.toString(), null);
return convertTo(resp, OvhUserWithPassword.class);
} |
python | def W(self):
"ISO-8601 week number of year, weeks starting on Monday"
# Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt
week_number = None
jan1_weekday = self.data.replace(month=1, day=1).weekday() + 1
weekday = self.data.weekday() + 1
day_of_year = self.z()
if day_of_year <= (8 - jan1_weekday) and jan1_weekday > 4:
if jan1_weekday == 5 or (jan1_weekday == 6 and calendar.isleap(self.data.year-1)):
week_number = 53
else:
week_number = 52
else:
if calendar.isleap(self.data.year):
i = 366
else:
i = 365
if (i - day_of_year) < (4 - weekday):
week_number = 1
else:
j = day_of_year + (7 - weekday) + (jan1_weekday - 1)
week_number = j // 7
if jan1_weekday > 4:
week_number -= 1
return week_number |
java | public void start(String name)
{
GVRAnimator anim = findAnimation(name);
if (name.equals(anim.getName()))
{
start(anim);
return;
}
} |
python | def getActorLimits(self):
""" Returns a list of 2-tuples, e.g. [(-3.14, 3.14), (-0.001, 0.001)],
one tuple per parameter, giving min and max for that parameter.
"""
generators = [g for g in self.env.case.online_generators
if g.bus.type != REFERENCE]
limits = []
for g in generators:
limits.append((g.p_min, g.p_max))
logger.info("Actor limits: %s" % limits)
return limits |
java | public void marshall(DevEndpoint devEndpoint, ProtocolMarshaller protocolMarshaller) {
if (devEndpoint == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(devEndpoint.getEndpointName(), ENDPOINTNAME_BINDING);
protocolMarshaller.marshall(devEndpoint.getRoleArn(), ROLEARN_BINDING);
protocolMarshaller.marshall(devEndpoint.getSecurityGroupIds(), SECURITYGROUPIDS_BINDING);
protocolMarshaller.marshall(devEndpoint.getSubnetId(), SUBNETID_BINDING);
protocolMarshaller.marshall(devEndpoint.getYarnEndpointAddress(), YARNENDPOINTADDRESS_BINDING);
protocolMarshaller.marshall(devEndpoint.getPrivateAddress(), PRIVATEADDRESS_BINDING);
protocolMarshaller.marshall(devEndpoint.getZeppelinRemoteSparkInterpreterPort(), ZEPPELINREMOTESPARKINTERPRETERPORT_BINDING);
protocolMarshaller.marshall(devEndpoint.getPublicAddress(), PUBLICADDRESS_BINDING);
protocolMarshaller.marshall(devEndpoint.getStatus(), STATUS_BINDING);
protocolMarshaller.marshall(devEndpoint.getNumberOfNodes(), NUMBEROFNODES_BINDING);
protocolMarshaller.marshall(devEndpoint.getAvailabilityZone(), AVAILABILITYZONE_BINDING);
protocolMarshaller.marshall(devEndpoint.getVpcId(), VPCID_BINDING);
protocolMarshaller.marshall(devEndpoint.getExtraPythonLibsS3Path(), EXTRAPYTHONLIBSS3PATH_BINDING);
protocolMarshaller.marshall(devEndpoint.getExtraJarsS3Path(), EXTRAJARSS3PATH_BINDING);
protocolMarshaller.marshall(devEndpoint.getFailureReason(), FAILUREREASON_BINDING);
protocolMarshaller.marshall(devEndpoint.getLastUpdateStatus(), LASTUPDATESTATUS_BINDING);
protocolMarshaller.marshall(devEndpoint.getCreatedTimestamp(), CREATEDTIMESTAMP_BINDING);
protocolMarshaller.marshall(devEndpoint.getLastModifiedTimestamp(), LASTMODIFIEDTIMESTAMP_BINDING);
protocolMarshaller.marshall(devEndpoint.getPublicKey(), PUBLICKEY_BINDING);
protocolMarshaller.marshall(devEndpoint.getPublicKeys(), PUBLICKEYS_BINDING);
protocolMarshaller.marshall(devEndpoint.getSecurityConfiguration(), SECURITYCONFIGURATION_BINDING);
protocolMarshaller.marshall(devEndpoint.getArguments(), ARGUMENTS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
java | public static <T, E extends Exception> ShortList mapToShort(final T[] a, final int fromIndex, final int toIndex,
final Try.ToShortFunction<? super T, E> func) throws E {
checkFromToIndex(fromIndex, toIndex, len(a));
N.checkArgNotNull(func);
if (N.isNullOrEmpty(a)) {
return new ShortList();
}
final ShortList result = new ShortList(toIndex - fromIndex);
for (int i = fromIndex; i < toIndex; i++) {
result.add(func.applyAsShort(a[i]));
}
return result;
} |
java | protected static Attributes buildAttributes(final Map attributes) {
final AttributesImpl attr = new AttributesImpl();
for (Object o : attributes.entrySet()) {
final Map.Entry entry = (Map.Entry) o;
final String attributeName = (String) entry.getKey();
final String attributeValue = String.valueOf(entry.getValue());
attr.addAttribute(null, attributeName, attributeName, "CDATA", attributeValue);
}
return attr;
} |
java | private boolean isInteger(String columnOrConstant, List<String> tableNames, boolean debugPrint) {
return isIntegerConstant(columnOrConstant) || isIntegerColumn(columnOrConstant, tableNames, debugPrint);
} |
python | def robot_wireless(max_iters=100, kernel=None, optimize=True, plot=True):
"""Predict the location of a robot given wirelss signal strength readings."""
try:import pods
except ImportError:
print('pods unavailable, see https://github.com/sods/ods for example datasets')
return
data = pods.datasets.robot_wireless()
# create simple GP Model
m = GPy.models.GPRegression(data['Y'], data['X'], kernel=kernel)
# optimize
if optimize:
m.optimize(max_iters=max_iters)
Xpredict = m.predict(data['Ytest'])[0]
if plot:
pb.plot(data['Xtest'][:, 0], data['Xtest'][:, 1], 'r-')
pb.plot(Xpredict[:, 0], Xpredict[:, 1], 'b-')
pb.axis('equal')
pb.title('WiFi Localization with Gaussian Processes')
pb.legend(('True Location', 'Predicted Location'))
sse = ((data['Xtest'] - Xpredict)**2).sum()
print(('Sum of squares error on test data: ' + str(sse)))
return m |
python | def ccid_xfr_block(self, data, timeout=0.1):
"""Encapsulate host command *data* into an PC/SC Escape command to
send to the device and extract the chip response if received
within *timeout* seconds.
"""
frame = struct.pack("<BI5B", 0x6F, len(data), 0, 0, 0, 0, 0) + data
self.transport.write(bytearray(frame))
frame = self.transport.read(int(timeout * 1000))
if not frame or len(frame) < 10:
log.error("insufficient data for decoding ccid response")
raise IOError(errno.EIO, os.strerror(errno.EIO))
if frame[0] != 0x80:
log.error("expected a RDR_to_PC_DataBlock")
raise IOError(errno.EIO, os.strerror(errno.EIO))
# if len(frame) != 10 + struct.unpack("<I", buffer(frame, 1, 4))[0]:
if len(frame) != 10 + struct.unpack("<I", frame[1:5])[0]:
log.error("RDR_to_PC_DataBlock length mismatch")
raise IOError(errno.EIO, os.strerror(errno.EIO))
return frame[10:] |
java | public void setParamTabEdButtonStyle(String value) {
try {
m_userSettings.setEditorButtonStyle(Integer.parseInt(value));
} catch (Throwable t) {
// should usually never happen
}
} |
python | def items(cls):
"""
All values for this enum
:return: list of str
"""
return [
cls.GREEN,
cls.BLACK_AND_WHITE,
cls.CONTRAST_SHIFTED,
cls.CONTRAST_CONTINUOUS
] |
java | public static <T> SerializedCheckpointData[] fromDeque(
ArrayDeque<Tuple2<Long, Set<T>>> checkpoints,
TypeSerializer<T> serializer,
DataOutputSerializer outputBuffer) throws IOException {
SerializedCheckpointData[] serializedCheckpoints = new SerializedCheckpointData[checkpoints.size()];
int pos = 0;
for (Tuple2<Long, Set<T>> checkpoint : checkpoints) {
outputBuffer.clear();
Set<T> checkpointIds = checkpoint.f1;
for (T id : checkpointIds) {
serializer.serialize(id, outputBuffer);
}
serializedCheckpoints[pos++] = new SerializedCheckpointData(
checkpoint.f0, outputBuffer.getCopyOfBuffer(), checkpointIds.size());
}
return serializedCheckpoints;
} |
java | public static final void debug(TraceComponent tc, String msg, Object... objs) {
TrConfigurator.getDelegate().debug(tc, msg, objs);
} |
java | public final DateList getDates(final Date seed, final Period period,
final Value value) {
return getDates(seed, period.getStart(), period.getEnd(), value, -1);
} |
python | def getNextEyeLocation(self, currentEyeLoc):
"""
Generate next eye location based on current eye location.
@param currentEyeLoc (numpy.array)
Current coordinate describing the eye location in the world.
@return (tuple) Contains:
nextEyeLoc (numpy.array)
Coordinate of the next eye location.
eyeDiff (numpy.array)
Vector describing change from currentEyeLoc to nextEyeLoc.
"""
possibleEyeLocs = []
for loc in self.spatialConfig:
shift = abs(max(loc - currentEyeLoc))
if self.minDisplacement <= shift <= self.maxDisplacement:
possibleEyeLocs.append(loc)
nextEyeLoc = self.nupicRandomChoice(possibleEyeLocs)
eyeDiff = nextEyeLoc - currentEyeLoc
return nextEyeLoc, eyeDiff |
python | def get_tiles(self):
"""Get all TileCoordinates contained in the region"""
for x, y in griditer(self.root_tile.x, self.root_tile.y, ncol=self.tiles_per_row):
yield TileCoordinate(self.root_tile.zoom, x, y) |
java | final Expression then(final Expression expression) {
return new Expression(expression.resultType(), expression.features()) {
@Override
protected void doGen(CodeBuilder adapter) {
Statement.this.gen(adapter);
expression.gen(adapter);
}
};
} |
python | def verify_images(path:PathOrStr, delete:bool=True, max_workers:int=4, max_size:Union[int]=None, recurse:bool=False,
dest:PathOrStr='.', n_channels:int=3, interp=PIL.Image.BILINEAR, ext:str=None, img_format:str=None,
resume:bool=None, **kwargs):
"Check if the images in `path` aren't broken, maybe resize them and copy it in `dest`."
path = Path(path)
if resume is None and dest == '.': resume=False
dest = path/Path(dest)
os.makedirs(dest, exist_ok=True)
files = get_image_files(path, recurse=recurse)
func = partial(verify_image, delete=delete, max_size=max_size, dest=dest, n_channels=n_channels, interp=interp,
ext=ext, img_format=img_format, resume=resume, **kwargs)
parallel(func, files, max_workers=max_workers) |
java | public Optional<ZonedDateTime> nextExecution(final ZonedDateTime date) {
Preconditions.checkNotNull(date);
try {
ZonedDateTime nextMatch = nextClosestMatch(date);
if (nextMatch.equals(date)) {
nextMatch = nextClosestMatch(date.plusSeconds(1));
}
return Optional.of(nextMatch);
} catch (final NoSuchValueException e) {
return Optional.empty();
}
} |
python | def follow(self):
""" Follow a user."
"""
data = json.dumps({"action": "follow"})
r = requests.post(
"https://kippt.com/api/users/%s/relationship" % (self.id),
headers=self.kippt.header,
data=data
)
return (r.json()) |
python | def validate(self, instance, value):
"""Check shape and dtype of vector and scales it to given length"""
value = super(BaseVector, self).validate(instance, value)
if self.length is not None:
try:
value.length = self._length_array(value)
except ZeroDivisionError:
self.error(
instance, value,
error_class=ZeroDivValidationError,
extra='The vector must have a length specified.'
)
return value |
java | public static boolean isNegative(ZMatrixD1 a, ZMatrixD1 b, double tol) {
if( a.numRows != b.numRows || a.numCols != b.numCols )
throw new IllegalArgumentException("Matrix dimensions must match");
int length = a.getNumElements()*2;
for( int i = 0; i < length; i++ ) {
if( !(Math.abs(a.data[i]+b.data[i]) <= tol) )
return false;
}
return true;
} |
python | def delete(self, path_list, **kwargs):
"""
删除文件或文件夹
:param path_list: 待删除的文件或文件夹列表,每一项为服务器路径
:type path_list: list
"""
data = {
'filelist': json.dumps([path for path in path_list])
}
url = 'http://{0}/api/filemanager?opera=delete'.format(BAIDUPAN_SERVER)
return self._request('filemanager', 'delete', url=url, data=data, **kwargs) |
java | public OvhOrder dedicatedCloud_serviceName_vdi_POST(String serviceName, Long datacenterId, String firstPublicIpAddress, String secondPublicIpAddress) throws IOException {
String qPath = "/order/dedicatedCloud/{serviceName}/vdi";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "datacenterId", datacenterId);
addBody(o, "firstPublicIpAddress", firstPublicIpAddress);
addBody(o, "secondPublicIpAddress", secondPublicIpAddress);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhOrder.class);
} |
python | def obfn_g1(self, Y1):
r"""Compute :math:`g_1(\mathbf{y_1})` component of ADMM objective
function.
"""
return np.linalg.norm((self.wl1 * Y1).ravel(), 1) |
java | public FireableEventType getEventId(EventLookupFacility eventLookupFacility,
Request request, boolean inDialogActivity) {
final String requestMethod = request.getMethod();
// Cancel is always the same.
if (requestMethod.equals(Request.CANCEL))
inDialogActivity = false;
FireableEventType eventID = null;
if (inDialogActivity) {
eventID = getEventId(eventLookupFacility,
new StringBuilder(INDIALOG_REQUEST_EVENT_PREFIX).append(requestMethod).toString());
if (eventID == null) {
eventID = getEventId(eventLookupFacility,
new StringBuilder(INDIALOG_REQUEST_EVENT_PREFIX).append(SIP_EXTENSION_REQUEST_EVENT_NAME_SUFIX).toString());
}
} else {
eventID = getEventId(eventLookupFacility,
new StringBuilder(OUT_OF_DIALOG_REQUEST_EVENT_PREFIX).append(requestMethod).toString());
if (eventID == null) {
eventID = getEventId(eventLookupFacility,
new StringBuilder(OUT_OF_DIALOG_REQUEST_EVENT_PREFIX).append(SIP_EXTENSION_REQUEST_EVENT_NAME_SUFIX).toString());
}
}
return eventID;
} |
python | def clear(self):
"""
Clear the cache, setting it to its initial state.
"""
self.name.clear()
self.path.clear()
self.generated = False |
java | public void updateThroughput(long currentTime) {
synchronized (throughputCalculationLock) {
int interval = (int) (currentTime - lastThroughputCalculationTime);
long minInterval = getThroughputCalculationIntervalInMillis();
if (minInterval == 0 || interval < minInterval) {
return;
}
long readBytes = this.readBytes.get();
long writtenBytes = this.writtenBytes.get();
long readMessages = this.readMessages.get();
long writtenMessages = this.writtenMessages.get();
readBytesThroughput = (readBytes - lastReadBytes) * 1000.0
/ interval;
writtenBytesThroughput = (writtenBytes - lastWrittenBytes) * 1000.0
/ interval;
readMessagesThroughput = (readMessages - lastReadMessages) * 1000.0
/ interval;
writtenMessagesThroughput = (writtenMessages - lastWrittenMessages)
* 1000.0 / interval;
if (readBytesThroughput > largestReadBytesThroughput) {
largestReadBytesThroughput = readBytesThroughput;
}
if (writtenBytesThroughput > largestWrittenBytesThroughput) {
largestWrittenBytesThroughput = writtenBytesThroughput;
}
if (readMessagesThroughput > largestReadMessagesThroughput) {
largestReadMessagesThroughput = readMessagesThroughput;
}
if (writtenMessagesThroughput > largestWrittenMessagesThroughput) {
largestWrittenMessagesThroughput = writtenMessagesThroughput;
}
lastReadBytes = readBytes;
lastWrittenBytes = writtenBytes;
lastReadMessages = readMessages;
lastWrittenMessages = writtenMessages;
lastThroughputCalculationTime = currentTime;
}
} |
java | static Shape shapeOf(List<Point2D> points) {
Path2D path = new Path2D.Double();
if (!points.isEmpty()) {
path.moveTo(points.get(0).getX(), points.get(0).getY());
for (Point2D point : points)
path.lineTo(point.getX(), point.getY());
path.closePath();
}
return path;
} |
java | private boolean isSupported(Class<?> t)
{
if (Boolean.class.equals(t) || boolean.class.equals(t) ||
Byte.class.equals(t) || byte.class.equals(t) ||
Short.class.equals(t) || short.class.equals(t) ||
Integer.class.equals(t) || int.class.equals(t) ||
Long.class.equals(t) || long.class.equals(t) ||
Float.class.equals(t) || float.class.equals(t) ||
Double.class.equals(t) || double.class.equals(t) ||
Character.class.equals(t) || char.class.equals(t) ||
String.class.equals(t))
return true;
return false;
} |
java | public void clean() throws BackupException
{
File storageDir = new File(PrivilegedSystemHelper.getProperty("java.io.tmpdir"));
WorkspaceQuotaRestore wqr = new WorkspaceQuotaRestore(this, storageDir);
wqr.clean();
} |
java | private void addShardStart(TableDefinition tableDef, int shardNumber, Date shardDate) {
SpiderTransaction spiderTran = new SpiderTransaction();
spiderTran.addShardStart(tableDef, shardNumber, shardDate);
Tenant tenant = Tenant.getTenant(tableDef);
DBTransaction dbTran = DBService.instance(tenant).startTransaction();
spiderTran.applyUpdates(dbTran);
DBService.instance(tenant).commit(dbTran);
synchronized (this) {
cacheShardValue(tableDef, shardNumber, shardDate);
}
} |
java | public float[] getFieldPositions(String name) {
Item item = getFieldItem(name);
if (item == null)
return null;
float ret[] = new float[item.size() * 5];
int ptr = 0;
for (int k = 0; k < item.size(); ++k) {
try {
PdfDictionary wd = item.getWidget(k);
PdfArray rect = wd.getAsArray(PdfName.RECT);
if (rect == null)
continue;
Rectangle r = PdfReader.getNormalizedRectangle(rect);
int page = item.getPage(k).intValue();
int rotation = reader.getPageRotation(page);
ret[ptr++] = page;
if (rotation != 0) {
Rectangle pageSize = reader.getPageSize(page);
switch (rotation) {
case 270:
r = new Rectangle(
pageSize.getTop() - r.getBottom(),
r.getLeft(),
pageSize.getTop() - r.getTop(),
r.getRight());
break;
case 180:
r = new Rectangle(
pageSize.getRight() - r.getLeft(),
pageSize.getTop() - r.getBottom(),
pageSize.getRight() - r.getRight(),
pageSize.getTop() - r.getTop());
break;
case 90:
r = new Rectangle(
r.getBottom(),
pageSize.getRight() - r.getLeft(),
r.getTop(),
pageSize.getRight() - r.getRight());
break;
}
r.normalize();
}
ret[ptr++] = r.getLeft();
ret[ptr++] = r.getBottom();
ret[ptr++] = r.getRight();
ret[ptr++] = r.getTop();
}
catch (Exception e) {
// empty on purpose
}
}
if (ptr < ret.length) {
float ret2[] = new float[ptr];
System.arraycopy(ret, 0, ret2, 0, ptr);
return ret2;
}
return ret;
} |
java | @Override
public void eUnset(int featureID) {
switch (featureID) {
case AfplibPackage.PTD__XPBASE:
setXPBASE(XPBASE_EDEFAULT);
return;
case AfplibPackage.PTD__YPBASE:
setYPBASE(YPBASE_EDEFAULT);
return;
case AfplibPackage.PTD__XPUNITVL:
setXPUNITVL(XPUNITVL_EDEFAULT);
return;
case AfplibPackage.PTD__YPUNITVL:
setYPUNITVL(YPUNITVL_EDEFAULT);
return;
case AfplibPackage.PTD__XPEXTENT:
setXPEXTENT(XPEXTENT_EDEFAULT);
return;
case AfplibPackage.PTD__YPEXTENT:
setYPEXTENT(YPEXTENT_EDEFAULT);
return;
case AfplibPackage.PTD__RESERVED:
setRESERVED(RESERVED_EDEFAULT);
return;
case AfplibPackage.PTD__CS:
getCS().clear();
return;
}
super.eUnset(featureID);
} |
java | @Override // defined by AbstractDoclet
protected void generateClassFiles(SortedSet<TypeElement> arr, ClassTree classtree)
throws DocletException {
List<TypeElement> list = new ArrayList<>(arr);
ListIterator<TypeElement> iterator = list.listIterator();
TypeElement klass = null;
while (iterator.hasNext()) {
TypeElement prev = iterator.hasPrevious() ? klass : null;
klass = iterator.next();
TypeElement next = iterator.nextIndex() == list.size()
? null : list.get(iterator.nextIndex());
if (utils.isHidden(klass) ||
!(configuration.isGeneratedDoc(klass) && utils.isIncluded(klass))) {
continue;
}
if (utils.isAnnotationType(klass)) {
AbstractBuilder annotationTypeBuilder =
configuration.getBuilderFactory()
.getAnnotationTypeBuilder(klass,
prev == null ? null : prev.asType(),
next == null ? null : next.asType());
annotationTypeBuilder.build();
} else {
AbstractBuilder classBuilder =
configuration.getBuilderFactory().getClassBuilder(klass,
prev, next, classtree);
classBuilder.build();
}
}
} |
python | def poly_curve(x, *a):
"""
Arbitrary dimension polynomial.
"""
output = 0.0
for n in range(0, len(a)):
output += a[n]*x**n
return output |
java | public Observable<ProjectInner> getAsync(String groupName, String serviceName, String projectName) {
return getWithServiceResponseAsync(groupName, serviceName, projectName).map(new Func1<ServiceResponse<ProjectInner>, ProjectInner>() {
@Override
public ProjectInner call(ServiceResponse<ProjectInner> response) {
return response.body();
}
});
} |
java | public final void listenInline(AsyncWorkListener<T,TError> listener) {
synchronized (this) {
if (!unblocked || listenersInline != null) {
if (listenersInline == null) listenersInline = new ArrayList<>(5);
listenersInline.add(listener);
return;
}
}
if (error != null) listener.error(error);
else if (cancel != null) listener.cancelled(cancel);
else listener.ready(result);
} |
python | def _dist_obs_oracle(oracle, query, trn_list):
"""A helper function calculating distances between a feature and frames in oracle."""
a = np.subtract(query, [oracle.f_array[t] for t in trn_list])
return (a * a).sum(axis=1) |
python | def write_fits(self, filename, moctool=''):
"""
Write a fits file representing the MOC of this region.
Parameters
----------
filename : str
File to write
moctool : str
String to be written to fits header with key "MOCTOOL".
Default = ''
"""
datafile = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data', 'MOC.fits')
hdulist = fits.open(datafile)
cols = fits.Column(name='NPIX', array=self._uniq(), format='1K')
tbhdu = fits.BinTableHDU.from_columns([cols])
hdulist[1] = tbhdu
hdulist[1].header['PIXTYPE'] = ('HEALPIX ', 'HEALPix magic code')
hdulist[1].header['ORDERING'] = ('NUNIQ ', 'NUNIQ coding method')
hdulist[1].header['COORDSYS'] = ('C ', 'ICRS reference frame')
hdulist[1].header['MOCORDER'] = (self.maxdepth, 'MOC resolution (best order)')
hdulist[1].header['MOCTOOL'] = (moctool, 'Name of the MOC generator')
hdulist[1].header['MOCTYPE'] = ('CATALOG', 'Source type (IMAGE or CATALOG)')
hdulist[1].header['MOCID'] = (' ', 'Identifier of the collection')
hdulist[1].header['ORIGIN'] = (' ', 'MOC origin')
time = datetime.datetime.utcnow()
hdulist[1].header['DATE'] = (datetime.datetime.strftime(time, format="%Y-%m-%dT%H:%m:%SZ"), 'MOC creation date')
hdulist.writeto(filename, overwrite=True)
return |
python | def __sum(self, line):
"""Return the IRQ sum number.
IRQ line samples:
1: 44487 341 44 72 IO-APIC 1-edge i8042
LOC: 33549868 22394684 32474570 21855077 Local timer interrupts
FIQ: usb_fiq
"""
splitted_line = line.split()
try:
ret = sum(map(int, splitted_line[1:(self.cpu_number + 1)]))
except ValueError:
# Correct issue #1007 on some conf (Raspberry Pi with Raspbian)
ret = 0
return ret |
python | def unlike(self, id, reblog_key):
"""
Unlike the post of the given blog
:param id: an int, the id of the post you want to like
:param reblog_key: a string, the reblog key of the post
:returns: a dict created from the JSON response
"""
url = "/v2/user/unlike"
params = {'id': id, 'reblog_key': reblog_key}
return self.send_api_request("post", url, params, ['id', 'reblog_key']) |
python | def dbmax_mean(self, value=None):
""" Corresponds to IDD Field `dbmax_mean`
Mean of extreme annual maximum dry-bulb temperature
Args:
value (float): value for IDD Field `dbmax_mean`
Unit: C
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `value` is not a valid value
"""
if value is not None:
try:
value = float(value)
except ValueError:
raise ValueError('value {} need to be of type float '
'for field `dbmax_mean`'.format(value))
self._dbmax_mean = value |
java | public TableBuilder addInnerBorder(BorderStyle style) {
this.addBorder(0, 0, model.getRowCount(), model.getColumnCount(), INNER, style);
return this;
} |
python | def split_datetime(self, column_name_prefix = "X", limit=None, timezone=False):
"""
Splits an SArray of datetime type to multiple columns, return a
new SFrame that contains expanded columns. A SArray of datetime will be
split by default into an SFrame of 6 columns, one for each
year/month/day/hour/minute/second element.
**Column Naming**
When splitting a SArray of datetime type, new columns are named:
prefix.year, prefix.month, etc. The prefix is set by the parameter
"column_name_prefix" and defaults to 'X'. If column_name_prefix is
None or empty, then no prefix is used.
**Timezone Column**
If timezone parameter is True, then timezone information is represented
as one additional column which is a float shows the offset from
GMT(0.0) or from UTC.
Parameters
----------
column_name_prefix: str, optional
If provided, expanded column names would start with the given prefix.
Defaults to "X".
limit: list[str], optional
Limits the set of datetime elements to expand.
Possible values are 'year','month','day','hour','minute','second',
'weekday', 'isoweekday', 'tmweekday', and 'us'.
If not provided, only ['year','month','day','hour','minute','second']
are expanded.
- 'year': The year number
- 'month': A value between 1 and 12 where 1 is January.
- 'day': Day of the months. Begins at 1.
- 'hour': Hours since midnight.
- 'minute': Minutes after the hour.
- 'second': Seconds after the minute.
- 'us': Microseconds after the second. Between 0 and 999,999.
- 'weekday': A value between 0 and 6 where 0 is Monday.
- 'isoweekday': A value between 1 and 7 where 1 is Monday.
- 'tmweekday': A value between 0 and 7 where 0 is Sunday
timezone: bool, optional
A boolean parameter that determines whether to show timezone column or not.
Defaults to False.
Returns
-------
out : SFrame
A new SFrame that contains all expanded columns
Examples
--------
To expand only day and year elements of a datetime SArray
>>> sa = SArray(
[datetime(2011, 1, 21, 7, 7, 21, tzinfo=GMT(0)),
datetime(2010, 2, 5, 7, 8, 21, tzinfo=GMT(4.5)])
>>> sa.split_datetime(column_name_prefix=None,limit=['day','year'])
Columns:
day int
year int
Rows: 2
Data:
+-------+--------+
| day | year |
+-------+--------+
| 21 | 2011 |
| 5 | 2010 |
+-------+--------+
[2 rows x 2 columns]
To expand only year and timezone elements of a datetime SArray
with timezone column represented as a string. Columns are named with prefix:
'Y.column_name'.
>>> sa.split_datetime(column_name_prefix="Y",limit=['year'],timezone=True)
Columns:
Y.year int
Y.timezone float
Rows: 2
Data:
+----------+---------+
| Y.year | Y.timezone |
+----------+---------+
| 2011 | 0.0 |
| 2010 | 4.5 |
+----------+---------+
[2 rows x 2 columns]
"""
from .sframe import SFrame as _SFrame
if self.dtype != datetime.datetime:
raise TypeError("Only column of datetime type is supported.")
if column_name_prefix is None:
column_name_prefix = ""
if six.PY2 and type(column_name_prefix) == unicode:
column_name_prefix = column_name_prefix.encode('utf-8')
if type(column_name_prefix) != str:
raise TypeError("'column_name_prefix' must be a string")
# convert limit to column_keys
if limit is not None:
if not _is_non_string_iterable(limit):
raise TypeError("'limit' must be a list")
name_types = set([type(i) for i in limit])
if (len(name_types) != 1):
raise TypeError("'limit' contains values that are different types")
if (name_types.pop() != str):
raise TypeError("'limit' must contain string values.")
if len(set(limit)) != len(limit):
raise ValueError("'limit' contains duplicate values")
column_types = []
if(limit is None):
limit = ['year','month','day','hour','minute','second']
column_types = [int] * len(limit)
if(timezone == True):
limit += ['timezone']
column_types += [float]
with cython_context():
return _SFrame(_proxy=self.__proxy__.expand(column_name_prefix, limit, column_types)) |
java | public static <T,K,V> List<T> collect(Map<K,V> self, @ClosureParams(MapEntryOrKeyValue.class) Closure<T> transform) {
return (List<T>) collect(self, new ArrayList<T>(self.size()), transform);
} |
java | @SuppressWarnings("unchecked")
@Override
public void publishEvent(ApplicationEvent event) {
if (event instanceof MappingContextEvent) {
this.schmeaCreator
.onApplicationEvent((MappingContextEvent<SolrPersistentEntity<?>, SolrPersistentProperty>) event);
}
} |
java | public static boolean recoverWeight(ProviderInfo providerInfo, int weight) {
providerInfo.setStatus(ProviderStatus.RECOVERING);
providerInfo.setWeight(weight);
return true;
} |
java | @Override
public Identifier toPhysicalColumnName(Identifier columnIdentifier, JdbcEnvironment context) {
return convertToLimitedLowerCase(context, columnIdentifier, null);
} |
java | private static Object castObject(
Class<?> toType, Class<?> fromType, Object fromValue,
int operation, boolean checkOnly )
throws UtilEvalError
{
/*
Lots of preconditions checked here...
Once things are running smoothly we might comment these out
(That's what assertions are for).
*/
if ( checkOnly && fromValue != null )
throw new InterpreterError("bad cast params 1");
if ( !checkOnly && fromValue == null )
throw new InterpreterError("bad cast params 2");
if ( fromType == Primitive.class )
throw new InterpreterError("bad from Type, need to unwrap");
if ( fromValue == Primitive.NULL && fromType != null )
throw new InterpreterError("inconsistent args 1");
if ( fromValue == Primitive.VOID && fromType != Void.TYPE )
throw new InterpreterError("inconsistent args 2");
if ( toType == Void.TYPE )
throw new InterpreterError("loose toType should be null");
// assignment to loose type, void type, or exactly same type
if ( toType == null || arrayElementType(toType) == arrayElementType(fromType) )
return checkOnly ? VALID_CAST :
fromValue;
if ( null != fromType && fromType.isArray() )
if ( operation == Types.CAST
|| isJavaAssignable(Collection.class, toType)
|| isJavaAssignable(Map.class, toType) )
return checkOnly ? VALID_CAST : BshArray.castArray(
toType, fromType, fromValue );
// Casting to primitive type
if ( toType.isPrimitive() )
{
if ( fromType == Void.TYPE || fromType == null
|| fromType.isPrimitive() )
{
// Both primitives, do primitive cast
return Primitive.castPrimitive(
toType, fromType, (Primitive)fromValue,
checkOnly, operation );
} else
{
if ( Primitive.isWrapperType( fromType ) )
{
// wrapper to primitive
// Convert value to Primitive and check/cast it.
//Object r = checkOnly ? VALID_CAST :
Class unboxedFromType = Primitive.unboxType( fromType );
Primitive primFromValue;
if ( checkOnly )
primFromValue = null; // must be null in checkOnly
else
primFromValue = (Primitive)Primitive.wrap(
fromValue, unboxedFromType );
return Primitive.castPrimitive(
toType, unboxedFromType, primFromValue,
checkOnly, operation );
} else
{
// Cannot cast from arbitrary object to primitive
if ( checkOnly )
return INVALID_CAST;
else
throw castError( toType, fromType, operation );
}
}
}
// Else, casting to reference type
// Casting from primitive or void (to reference type)
if ( fromType == Void.TYPE || fromType == null
|| fromType.isPrimitive() )
{
// cast from primitive to wrapper type
if ( Primitive.isWrapperType( toType )
&& fromType != Void.TYPE && fromType != null )
{
// primitive to wrapper type
return checkOnly ? VALID_CAST :
Primitive.castWrapper(
Primitive.unboxType(toType),
((Primitive)fromValue).getValue() );
}
// Primitive (not null or void) to Object.class type
if ( toType == Object.class
&& fromType != Void.TYPE && fromType != null )
{
// box it
return checkOnly ? VALID_CAST :
((Primitive)fromValue).getValue();
}
// Primitive to arbitrary object type.
// Allow Primitive.castToType() to handle it as well as cases of
// Primitive.NULL and Primitive.VOID
return Primitive.castPrimitive(
toType, fromType, (Primitive)fromValue, checkOnly, operation );
}
// If type already assignable no cast necessary
// We do this last to allow various errors above to be caught.
// e.g cast Primitive.Void to Object would pass this
if ( toType.isAssignableFrom( fromType ) )
return checkOnly ? VALID_CAST :
fromValue;
// Can we use the proxy mechanism to cast a bsh.This to
// the correct interface?
if ( toType.isInterface()
&& bsh.This.class.isAssignableFrom( fromType )
)
return checkOnly ? VALID_CAST :
((bsh.This)fromValue).getInterface( toType );
// Both numeric wrapper types?
// Try numeric style promotion wrapper cast
if ( Primitive.isWrapperType( toType )
&& Primitive.isWrapperType( fromType ) )
return checkOnly ? VALID_CAST :
Primitive.castWrapper( toType, fromValue );
if ( checkOnly )
return INVALID_CAST;
else
throw castError( toType, fromType , operation );
} |
python | def parse(self, text):
"""Do the parsing."""
text = tounicode(text, encoding="utf-8")
result, i = self._parse(text, 0)
if text[i:].strip():
self._fail("Unexpected trailing content", text, i)
return result |
python | def get(self):
"""
Get current user info.
Returns :class:`User` object.
:Example:
user = client.user.get()
"""
response, instance = self.request("GET", self.uri)
return self.load_instance(instance) |
python | def ghostedDistArrayFactory(BaseClass):
"""
Returns a ghosted distributed array class that derives from BaseClass
@param BaseClass base class, e.g. DistArray or MaskedDistArray
@return ghosted dist array class
"""
class GhostedDistArrayAny(BaseClass):
"""
Ghosted distributed array. Each process owns data and exposes the
halo region to other processes. These are accessed with tuples
such (1, 0) for north, (-1, 0) for south, etc.
"""
def __init__(self, shape, dtype):
"""
Constructor
@param shape shape of the array
@param dtype numpy data type
@param numGhosts the width of the halo
"""
# call the parent Ctor
BaseClass.__init__(self, shape, dtype)
def setNumberOfGhosts(self, numGhosts):
"""
Set the width of the ghost halo
@param numGhosts halo thickness
"""
# expose each window to other PE domains
ndim = len(self.shape)
for dim in range(ndim):
for drect in (-1, 1):
# the window id uniquely specifies the
# location of the window. we use 0's to indicate
# a slab extending over the entire length for a
# given direction, a 1 represents a layer of
# thickness numGhosts on the high index side,
# -1 on the low index side.
winId = tuple([0 for i in range(dim)] +
[drect] +
[0 for i in range(dim+1, ndim)])
slce = slice(0, numGhosts)
if drect == 1:
slce = slice(self.shape[dim] -
numGhosts, self.shape[dim])
slab = self.getSlab(dim, slce)
# expose MPI window
self.expose(slab, winId)
def getSlab(self, dim, slce):
"""
Get slab. A slab is a multi-dimensional slice extending in
all directions except along dim where slce applies
@param dim dimension (0=first index, 1=2nd index...)
@param slce python slice object along dimension dim
@return slab
"""
shape = self.shape
ndim = len(shape)
slab = [slice(0, shape[i]) for i in range(dim)] + \
[slce] + [slice(0, shape[i]) for i in range(dim+1, ndim)]
return slab
def getEllipsis(self, winID):
"""
Get the ellipsis for a given halo side
@param winID a tuple of zeros and one +1 or -1. To access
the "north" side for instance, set side=(1, 0),
(-1, 0) to access the south side, (0, 1) the east
side, etc. This does not involve any communication.
@return None if halo was not exposed (bad winID)
"""
if winID in self.windows:
return self.windows[winID]['slice']
else:
return None
return GhostedDistArrayAny |
java | public CMAArray<CMAContentType> fetchAll(
String spaceId,
String environmentId,
Map<String, String> query) {
assertNotNull(spaceId, "spaceId");
DefaultQueryParameter.putIfNotSet(query, DefaultQueryParameter.FETCH);
return service.fetchAll(spaceId, environmentId, query).blockingFirst();
} |
python | def _ensure_folders(self, *paths):
"""
Ensure that paths to folder(s) exist.
Some command-line tools will not attempt to create folder(s) needed
for output path to exist. They instead assume that they already are
present and will fail if that assumption does not hold.
:param Iterable[str] paths: Collection of path for which
"""
for p in paths:
# Only provide assurance for absolute paths.
if not p or not os.path.isabs(p):
continue
# See if what we're assuring is file- or folder-like.
fpath, fname = os.path.split(p)
base, ext = os.path.splitext(fname)
# If there's no extension, ensure that we have the whole path.
# Otherwise, just ensure that we have path to file's folder.
self.make_dir(fpath if ext else p) |
java | public SDVariable eq(SDVariable x, SDVariable y) {
return eq(null, x, y);
} |
python | def load(fileobj):
"""Load the submission from a file-like object
:param fileobj: File-like object
:return: the loaded submission
"""
with gzip.GzipFile(fileobj=fileobj, mode='r') as z:
submission = Submission(metadata=json.loads(z.readline()))
for line in z:
token_id, token = json.loads(line)
submission['tokens'][token_id] = token
return submission |
java | public static List<Fodselsnummer> getManyDNumberFodselsnummerForDate(Date date) {
if (date == null) {
throw new IllegalArgumentException();
}
DateFormat df = new SimpleDateFormat("ddMMyy");
String centuryString = getCentury(date);
String dateString = df.format(date);
dateString = new StringBuilder()
.append(Character.toChars(dateString.charAt(0) + 4)[0])
.append(dateString.substring(1))
.toString();
return generateFodselsnummerForDate(dateString, centuryString);
} |
java | public ResultSet getBestRowIdentifier(String catalog, String schema,
String table, int scope, boolean nullable) throws SQLException {
if (table == null) {
throw Util.nullArgument("table");
}
String scopeIn;
switch (scope) {
case bestRowTemporary :
scopeIn = BRI_TEMPORARY_SCOPE_IN_LIST;
break;
case bestRowTransaction :
scopeIn = BRI_TRANSACTION_SCOPE_IN_LIST;
break;
case bestRowSession :
scopeIn = BRI_SESSION_SCOPE_IN_LIST;
break;
default :
throw Util.invalidArgument("scope");
}
schema = translateSchema(schema);
Integer Nullable = (nullable) ? null
: INT_COLUMNS_NO_NULLS;
StringBuffer select =
toQueryPrefix("SYSTEM_BESTROWIDENTIFIER").append(and("TABLE_CAT",
"=", catalog)).append(and("TABLE_SCHEM", "=",
schema)).append(and("TABLE_NAME", "=",
table)).append(and("NULLABLE", "=",
Nullable)).append(" AND SCOPE IN "
+ scopeIn);
// By default, query already returns rows in contract order.
// However, the way things are set up, there should never be
// a result where there is > 1 distinct scope value: most requests
// will want only one table and the system table producer (for
// now) guarantees that a maximum of one BRI scope column set is
// produced for each table
return execute(select.toString());
} |
java | public Map<String,String> parse(final char[] chars, char separator) {
if (chars == null) {
return new HashMap<String,String>();
}
return parse(chars, 0, chars.length, separator);
} |
java | public void createWithDepth(int allowableDepth, TreeGP manager, TGPInitializationStrategy initializationStrategy){
final int constantCount = manager.getConstants().size();
for(int i=0; i < constantCount; ++i){
constantSet.add(new Terminal("c" + i, manager.constant(i), manager.constantText(i), true), manager.constantWeight(i));
}
final int registerCount = manager.getVariableCount();
for(int i=0; i < registerCount; ++i) {
variableSet.add(new Terminal("v" + i, 0.0, "", false), 1.0);
}
final int operatorCount = manager.getOperatorSet().size();
for(int i=0; i < operatorCount; ++i) {
Primitive operator = manager.getOperatorSet().get(i);
operatorSet.add(operator, manager.getOperatorSet().getWeight(i));
}
root = TreeGenerator.createWithDepth(this, allowableDepth, manager, initializationStrategy);
calcLength();
calcDepth();
} |
java | public boolean validateCVC() {
if (StripeTextUtils.isBlank(cvc)) {
return false;
}
String cvcValue = cvc.trim();
String updatedType = getBrand();
boolean validLength =
(updatedType == null && cvcValue.length() >= 3 && cvcValue.length() <= 4)
|| (AMERICAN_EXPRESS.equals(updatedType) && cvcValue.length() == 4)
|| cvcValue.length() == 3;
return ModelUtils.isWholePositiveNumber(cvcValue) && validLength;
} |
java | public SubscribeData subscribe(Collection<Statistic> statistics) throws WorkspaceApiException {
try {
StatisticsSubscribeData subscribeData = new StatisticsSubscribeData();
StatisticsSubscribeDataData data = new StatisticsSubscribeDataData();
data.setStatistics(new ArrayList<>(statistics));
subscribeData.setData(data);
InlineResponse2002 resp = api.subscribe(subscribeData);
Util.throwIfNotOk(resp.getStatus());
InlineResponse2002Data respData = resp.getData();
if(respData == null) {
throw new WorkspaceApiException("Response data is empty");
}
SubscribeData result = new SubscribeData();
result.setSubscriptionId(respData.getSubscriptionId());
result.setStatistics(respData.getStatistics());
return result;
}
catch(ApiException ex) {
throw new WorkspaceApiException("Cannot subscribe", ex);
}
} |
python | def get_poll_option_formset(self, formset_class):
""" Returns an instance of the poll option formset to be used in the view. """
if self.request.forum_permission_handler.can_create_polls(
self.get_forum(), self.request.user,
):
return formset_class(**self.get_poll_option_formset_kwargs()) |
python | def meta_get(self, key, metafield, default=None):
''' Return the value of a meta field for a key. '''
return self._meta.get(key, {}).get(metafield, default) |
java | private Integer listCorruptFileBlocks(String dir, int limit, String baseUrl)
throws IOException {
int errCode = -1;
int numCorrupt = 0;
int cookie = 0;
String lastBlock = null;
final String noCorruptLine = "has no CORRUPT files";
final String noMoreCorruptLine = "has no more CORRUPT files";
final String cookiePrefix = "Cookie:";
boolean allDone = false;
while (!allDone) {
final StringBuffer url = new StringBuffer(baseUrl);
if (cookie > 0) {
url.append("&startblockafterIndex=").append(String.valueOf(cookie));
} else if (lastBlock != null) { // for backwards compatibility purpose
url.append("&startblockafter=").append(lastBlock);
}
URL path = new URL(url.toString());
// SecurityUtil.fetchServiceTicket(path);
URLConnection connection = path.openConnection();
InputStream stream = connection.getInputStream();
BufferedReader input = new BufferedReader(new InputStreamReader(stream,
"UTF-8"));
try {
String line = null;
while ((line = input.readLine()) != null) {
if (line.startsWith(cookiePrefix)){
try{
cookie = Integer.parseInt(line.split("\t")[1]);
} catch (Exception e){
allDone = true;
break;
}
continue;
}
if ((line.endsWith(noCorruptLine)) ||
(line.endsWith(noMoreCorruptLine)) ||
(line.endsWith(NamenodeFsck.HEALTHY_STATUS)) ||
(line.endsWith(NamenodeFsck.NONEXISTENT_STATUS)) ||
numCorrupt >= limit) {
allDone = true;
break;
}
if ((line.isEmpty())
|| (line.startsWith("FSCK started by"))
|| (line.startsWith("Unable to locate any corrupt files under"))
|| (line.startsWith("The filesystem under path")))
continue;
numCorrupt++;
if (numCorrupt == 1) {
out.println("The list of corrupt files under path '"
+ dir + "' are:");
}
out.println(line);
try {
// Get the block # that we need to send in next call
lastBlock = line.split("\t")[0];
} catch (Exception e) {
allDone = true;
break;
}
}
} finally {
input.close();
}
}
out.println("The filesystem under path '" + dir + "' has "
+ numCorrupt + " CORRUPT files");
if (numCorrupt == 0)
errCode = 0;
return errCode;
} |
java | private List<Pair<String, StandardCredentials>> getGitClientCredentials() {
List<Pair<String, StandardCredentials>> credentialsList = new ArrayList<>();
GitSCM gitScm = getJenkinsScm();
for (UserRemoteConfig uc : gitScm.getUserRemoteConfigs()) {
String url = uc.getUrl();
// In case overriding credentials are defined, we will use it for this URL
if (this.credentials != null) {
credentialsList.add(Pair.of(url, this.credentials));
continue;
}
// Get credentials from jenkins credentials plugin
if (uc.getCredentialsId() != null) {
StandardUsernameCredentials credentials = CredentialsMatchers.firstOrNull(
CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class,
build.getProject(), ACL.SYSTEM, URIRequirementBuilder.fromUri(url).build()),
CredentialsMatchers.allOf(CredentialsMatchers.withId(uc.getCredentialsId()),
GitClient.CREDENTIALS_MATCHER));
if (credentials != null) {
credentialsList.add(Pair.of(url, (StandardCredentials)credentials));
}
}
}
return credentialsList;
} |
python | def parse_member(
cls,
obj: dict,
collection: "DtsCollection",
direction: str,
**additional_parameters) -> List["DtsCollection"]:
""" Parse the member value of a Collection response
and returns the list of object while setting the graph
relationship based on `direction`
:param obj: PyLD parsed JSON+LD
:param collection: Collection attached to the member property
:param direction: Direction of the member (children, parent)
"""
members = []
for member in obj.get(str(_hyd.member), []):
subcollection = cls.parse(member, **additional_parameters)
if direction == "children":
subcollection.parents.update({collection})
members.append(subcollection)
return members |
java | public void refresh(String vaultName, String resourceGroupName, String fabricName, String filter) {
refreshWithServiceResponseAsync(vaultName, resourceGroupName, fabricName, filter).toBlocking().single().body();
} |
python | def _create_fw_fab_dev(self, tenant_id, drvr_name, fw_dict):
"""This routine calls the Tenant Edge routine if FW Type is TE. """
if fw_dict.get('fw_type') == fw_constants.FW_TENANT_EDGE:
self._create_fw_fab_dev_te(tenant_id, drvr_name, fw_dict) |
python | def iter_emails(self, number=-1, etag=None):
"""Iterate over email addresses for the authenticated user.
:param int number: (optional), number of email addresses to return.
Default: -1 returns all available email addresses
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of dicts
"""
url = self._build_url('user', 'emails')
return self._iter(int(number), url, dict, etag=etag) |
java | protected <OBJ> OBJ filterIfSimpleText(OBJ value, FormMappingOption option, String propertyName, Class<?> propertyType) {
if (value == null) {
return null;
}
if (value instanceof String) {
final String str = (String) value;
if (option.getSimpleTextParameterFilter().isPresent()) { // basically false
// not use map() to avoid many new instances at main route (not here)
final FormSimpleTextParameterFilter filter = option.getSimpleTextParameterFilter().get();
final FormSimpleTextParameterMeta meta = createFormSimpleTextParameterMeta(propertyName, propertyType);
@SuppressWarnings("unchecked")
final OBJ filtered = (OBJ) filter.filter(str, meta);
return filtered;
} else { // mainly here
return value;
}
} else if (value instanceof String[]) {
final String[] ary = (String[]) value;
option.getSimpleTextParameterFilter().ifPresent(filter -> {
final FormSimpleTextParameterMeta meta = createFormSimpleTextParameterMeta(propertyName, propertyType);
int index = 0;
for (String element : ary) {
if (element != null) { // just in case
ary[index] = filter.filter(element, meta);
}
++index;
}
});
@SuppressWarnings("unchecked")
final OBJ resultObj = (OBJ) ary;
return resultObj;
} else {
return value;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.