language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def CNOT(control, target):
"""Produces a controlled-NOT (controlled-X) gate::
CNOT = [[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 0, 1, 0]]
This gate applies to two qubit arguments to produce the controlled-not gate instruction.
:param control: Th... |
python | def primitive(self):
"""
Returns a primitive object representation for this container (which is a dict).
WARNING: The returned container does not contain any markup or formatting metadata.
"""
raw_container = raw.to_raw(self._navigable)
# Collapsing the anonymous table ... |
python | def nDims(self):
""" The number of dimensions of the index. Will always be 1.
"""
result = self._index.ndim
assert result == 1, "Expected index to be 1D, got: {}D".format(result)
return result |
java | public void setServices(java.util.Collection<FaultRootCauseService> services) {
if (services == null) {
this.services = null;
return;
}
this.services = new java.util.ArrayList<FaultRootCauseService>(services);
} |
python | def _set_defaults(self, namespace, optional_cfg_files):
""" Set default values in the given dict.
"""
# Add current configuration directory
namespace["config_dir"] = self.config_dir
# Load defaults
for idx, cfg_file in enumerate([self.CONFIG_INI] + optional_cfg_files):
... |
java | public LiveOutputInner create(String resourceGroupName, String accountName, String liveEventName, String liveOutputName, LiveOutputInner parameters) {
return createWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, liveOutputName, parameters).toBlocking().last().body();
} |
java | public Observable<ServiceResponse<Page<ElasticPoolInner>>> listByServerNextWithServiceResponseAsync(final String nextPageLink) {
return listByServerNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<ElasticPoolInner>>, Observable<ServiceResponse<Page<ElasticPoolInner>>>>() {... |
python | def _rest_post(self, suburi, request_headers, request_body):
"""REST POST operation.
The response body after the operation could be the new resource, or
ExtendedError, or it could be empty.
"""
return self._rest_op('POST', suburi, request_headers, request_body) |
java | public static void rotate(File imageFile, int degree, File outFile) throws IORuntimeException {
rotate(read(imageFile), degree, outFile);
} |
python | def list(self, request, *args, **kwargs):
"""
To get a list of supported resources' actions, run **OPTIONS** against
*/api/<resource_url>/* as an authenticated user.
It is possible to filter and order by resource-specific fields, but this filters will be applied only to
resource... |
java | public final EObject ruleXMultiplicativeExpression() throws RecognitionException {
EObject current = null;
EObject this_XUnaryOperation_0 = null;
EObject lv_rightOperand_3_0 = null;
enterRule();
try {
// InternalXbaseWithAnnotations.g:1716:2: ( (this_XUnaryOper... |
java | public boolean isExistingPipeline(String pipelineName) throws IOException {
logger.debug("is existing pipeline [{}]", pipelineName);
try {
Response restResponse = lowLevelClient.performRequest("GET", "/_ingest/pipeline/" + pipelineName);
logger.trace("get pipeline metadata respo... |
java | public UpdateReturnState update(final double datum) {
final double d = (datum == 0.0) ? 0.0 : datum; // canonicalize -0.0, 0.0
final long[] data = { Double.doubleToLongBits(d) };// canonicalize all NaN forms
return hashUpdate(hash(data, getSeed())[0] >>> 1);
} |
java | public static Expression join(final Expression e1, final Expression e2) {
return new RepeatDelimiter(EQ, e1, e2);
} |
python | def precheck():
"""
Pre-run dependency check
"""
binaries = ['make']
for bin in binaries:
if not which(bin):
msg = 'Dependency fail -- Unable to locate rquired binary: '
stdout_message('%s: %s' % (msg, ACCENT + bin + RESET))
return False
elif not r... |
python | def _legacy_write(self, sock_info, name, cmd, op_id,
bypass_doc_val, func, *args):
"""Internal legacy unacknowledged write helper."""
# Cannot have both unacknowledged write and bypass document validation.
if bypass_doc_val and sock_info.max_wire_version >= 4:
r... |
java | public TypeMirror getLocalType(String name)
{
VariableElement lv = getLocalVariable(name);
return lv.asType();
} |
python | def not_found(entity_id=None, message='Entity not found'):
"""
Build a response to indicate that the requested entity was not found.
:param string message:
An optional message, defaults to 'Entity not found'
:param string entity_id:
An option ID of the entity req... |
java | @Override
public Collection<Object> values() {
Collection<Object> values = new ArrayList<Object>();
for (Property property : getProperties(_scope)) {
values.add(property.getValue());
}
return values;
} |
python | def _compute_suftab(self, string):
"""Computes the suffix array of a string in O(n).
The code is based on that from the pysuffix library (https://code.google.com/p/pysuffix/).
Kärkkäinen & Sanders (2003).
"""
n = len(string)
string += (unichr(1) * 3)
suftab = np... |
java | public void closeAllPaths() {
_touch();
if (m_bPolygon || isEmptyImpl())
return;
m_bPathStarted = false;
for (int ipath = 0, npart = m_paths.size() - 1; ipath < npart; ipath++) {
if (isClosedPath(ipath))
continue;
byte pf = m_pathFlags.read(ipath);
m_pathFlags.write(ipath, (byte) (pf | PathFl... |
python | def search(self, matchStr, numSyllables=None, wordInitial='ok',
wordFinal='ok', spanSyllable='ok', stressedSyllable='ok',
multiword='ok', pos=None):
'''
for help on isletool.LexicalTool.search(), see see isletool.search()
'''
return search(self.data.items(),... |
java | private void remove(int index) {
Validate.isFalse(index >= size);
int shifted = size - index - 1;
if (shifted > 0) {
System.arraycopy(keys, index + 1, keys, index, shifted);
System.arraycopy(vals, index + 1, vals, index, shifted);
}
size--;
keys[si... |
java | private void addConfiguration(ConfigurableDescriptor configurableDescriptor, Xpp3Dom config, Store store) {
if (null == config) {
return;
}
MavenConfigurationDescriptor configDescriptor = store.create(MavenConfigurationDescriptor.class);
configurableDescriptor.setConfiguratio... |
python | def save_book(self, book_form, *args, **kwargs):
"""Pass through to provider BookAdminSession.update_book"""
# Implemented from kitosid template for -
# osid.resource.BinAdminSession.update_bin
if book_form.is_for_update():
return self.update_book(book_form, *args, **kwargs)
... |
java | public boolean isAvailable() {
boolean available = false;
String relativeURL = inputSource.getRelativeURL();
Container container = tcontext.getServletContext().getModuleContainer();
if (container!=null) {
if (options.isDisableJspRuntimeCompilation() == false) {
... |
python | def _import_plugins(self) -> None:
"""
Import and register plugin in the plugin manager.
The pluggy library is used as plugin manager.
"""
logger.debug('Importing plugins')
self._pm = pluggy.PluginManager('sirbot')
self._pm.add_hookspecs(hookspecs)
for p... |
java | public void setPara(char[] chars, byte paraLevel, byte[] embeddingLevels)
{
/* check the argument values */
if (paraLevel < LEVEL_DEFAULT_LTR) {
verifyRange(paraLevel, 0, MAX_EXPLICIT_LEVEL + 1);
}
if (chars == null) {
chars = new char[0];
}
/... |
java | public EClass getIfcTwoDirectionRepeatFactor() {
if (ifcTwoDirectionRepeatFactorEClass == null) {
ifcTwoDirectionRepeatFactorEClass = (EClass) EPackage.Registry.INSTANCE
.getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(625);
}
return ifcTwoDirectionRepeatFactorEClass;
} |
python | def _get_media(media_types):
"""Helper method to map the media types."""
get_mapped_media = (lambda x: maps.VIRTUAL_MEDIA_TYPES_MAP[x]
if x in maps.VIRTUAL_MEDIA_TYPES_MAP else None)
return list(map(get_mapped_media, media_types)) |
python | def _get_full_block(grouped_dicoms):
"""
Generate a full datablock containing all timepoints
"""
# For each slice / mosaic create a data volume block
data_blocks = []
for index in range(0, len(grouped_dicoms)):
logger.info('Creating block %s of %s' % (index + 1, len(grouped_dicoms)))
... |
python | def dijkstra(graph, weight, source=0, target=None):
"""single source shortest paths by Dijkstra
:param graph: directed graph in listlist or listdict format
:param weight: in matrix format or same listdict graph
:assumes: weights are non-negative
:param source: source vertex
:type... |
python | def generate_molecule_object_dict(source, format, values):
"""Generate a dictionary that represents a Squonk MoleculeObject when
written as JSON
:param source: Molecules in molfile or smiles format
:param format: The format of the molecule. Either 'mol' or 'smiles'
:param values: Optional dict of v... |
python | def interp(self, energies, dtheta, scale_fn=None):
"""Evaluate the PSF model at an array of energies and angular
separations.
Parameters
----------
energies : array_like
Array of energies in MeV.
dtheta : array_like
Array of angular separations i... |
python | def stop(self):
"""Use this method to manually stop the Client.
Requires no parameters.
Raises:
``ConnectionError`` in case you try to stop an already stopped Client.
"""
if not self.is_started:
raise ConnectionError("Client is already stopped")
... |
java | public ServiceFuture<VpnConnectionInner> getAsync(String resourceGroupName, String gatewayName, String connectionName, final ServiceCallback<VpnConnectionInner> serviceCallback) {
return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName), serviceCallback);
... |
java | public String popHistory(int quanityToPop, boolean bPopFromBrowser)
{
String strHistory = null;
for (int i = 0; i < quanityToPop; i++)
{
strHistory = null;
if (m_vHistory != null) if (m_vHistory.size() > 0)
strHistory = (String)m_vHistory.remove(m_vHistory.size... |
java | public static <T> Fragment newFragment(final String id, final String markupId,
final MarkupContainer markupProvider, final IModel<T> model)
{
final Fragment fragment = new Fragment(id, markupId, markupProvider, model);
fragment.setOutputMarkupId(true);
return fragment;
} |
java | private int getSerializationSize(final Object obj) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.close();
byte[] bytes = bos.toByteArray();
return bytes.length;
} catch (IOException ex) {
// Unab... |
java | public ServiceFuture<List<MetricDefinitionInner>> listMetricDefinitionsAsync(String resourceGroupName, String serverName, String databaseName, final ServiceCallback<List<MetricDefinitionInner>> serviceCallback) {
return ServiceFuture.fromResponse(listMetricDefinitionsWithServiceResponseAsync(resourceGroupName, ... |
python | def parse_help_text(self, file_path):
''' Load of list of commands and descriptions from a file. '''
with open(file_path) as f:
lines = f.readlines()
# Parse commands and descriptions, which are separated by a multi-space
# (any sequence of two or more space characters in a ... |
java | public SearchRequestBuilder getSearchRequestBuilder(
SearchRequestBuilder searchRequestBuilder,
AggregationBuilder[] aggregationBuilders) {
ifNotNull(aggregationBuilders,
array -> stream(array).filter(getIsNotNull())
.forEach(searchRequestBuilder::... |
java | @Override
public ZoneOffset getOffset(LocalDateTime localDateTime) {
Object info = getOffsetInfo(localDateTime);
if (info instanceof ZoneOffsetTransition) {
return ((ZoneOffsetTransition) info).getOffsetBefore();
}
return (ZoneOffset) info;
} |
java | public static appflowpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{
appflowpolicy_lbvserver_binding obj = new appflowpolicy_lbvserver_binding();
obj.set_name(name);
appflowpolicy_lbvserver_binding response[] = (appflowpolicy_lbvserver_binding[]) obj.get_resources(service);
... |
python | def get_distance_and_image(
self,
frac_coords1: Vector3Like,
frac_coords2: Vector3Like,
jimage: Optional[Union[List[int], np.ndarray]] = None,
) -> Tuple[float, np.ndarray]:
"""
Gets distance between two frac_coords assuming periodic boundary
conditions. If th... |
java | @Override
public void setupKAMCatalogSchema() throws SQLException, IOException {
DBConnection kamDbc = null;
try {
kamDbc = createConnection();
runScripts(kamDbc, "/" + kamDbc.getType() + KAM_CATALOG_SQL_PATH,
getSystemConfiguration().getKamCatalogSchema()... |
python | def to_bb(YY, y="deprecated"):
"""Convert mask YY to a bounding box, assumes 0 as background nonzero object"""
cols,rows = np.nonzero(YY)
if len(cols)==0: return np.zeros(4, dtype=np.float32)
top_row = np.min(rows)
left_col = np.min(cols)
bottom_row = np.max(rows)
right_col = np.max(cols)
... |
java | public SessionConfigType<T> trackingMode(TrackingModeType ... values)
{
if (values != null)
{
for(TrackingModeType name: values)
{
childNode.createChild("tracking-mode").text(name);
}
}
return this;
} |
java | @Override
public Optional<List<CopyRoute>> getPushRoutes(ReplicationConfiguration rc, EndPoint copyFrom) {
if (rc.getCopyMode() == ReplicationCopyMode.PULL)
return Optional.absent();
DataFlowTopology topology = rc.getDataFlowToplogy();
List<DataFlowTopology.DataFlowPath> paths = topology.getDataFlo... |
python | def via_find_packages(self): # type: () -> List[str]
"""
Use find_packages code to find modules. Can find LOTS of modules.
:return:
"""
packages = [] # type: List[str]
source = self.setup_py_source()
if not source:
return packages
for row in ... |
python | def _make_argparser(self):
"""Makes a new argument parser."""
self.argparser = ShellArgumentParser(prog='')
subparsers = self.argparser.add_subparsers()
for name in self.get_names():
if name.startswith('parser_'):
parser = subparsers.add_parser(name[7:])
... |
java | private void eval(List<Tuple> training, List<Tuple> testing, int nfold) {
classifier.train(training);
for (Tuple tuple : testing) {
String actual = classifier.predict(tuple).entrySet().stream()
.max((e1, e2) -> e1.getValue().compareTo(e2.getValue()))
... |
java | public TaskExecutor spawnExecutor(Task task) {
final TaskExecutor executor = new TaskExecutor(this.scheduler, task);
synchronized (this.executors) {
this.executors.add(executor);
}
// 子线程是否为deamon线程取决于父线程,因此此处无需显示调用
// executor.setDaemon(this.scheduler.daemon);
// executor.start();
this.schedule... |
python | def inverse(self, vector, duration=None):
'''Inverse vector transformer'''
ann = jams.Annotation(namespace=self.namespace, duration=duration)
if duration is None:
duration = 0
ann.append(time=0, duration=duration, value=vector)
return ann |
python | def copy_subrange_of_file(input_file, file_start, file_end, output_filehandle):
"""Copies the range (in bytes) between fileStart and fileEnd to the given
output file handle.
"""
with open(input_file, 'r') as fileHandle:
fileHandle.seek(file_start)
data = fileHandle.read(file_end - file_s... |
java | private static void copy(InputStream source, OutputStream sink) throws IOException {
byte[] buf = new byte[8192];
int n;
while ((n = source.read(buf)) > 0) {
sink.write(buf, 0, n);
}
} |
python | def to_madeline(self):
"""
Return a generator with the info in madeline format.
Yields:
An iterator with family info in madeline format
"""
madeline_header = [
'FamilyID',
'IndividualID',
'Gender',
'... |
python | def chunk_by(n, iterable, fillvalue=None):
"""
Iterate over a given ``iterable`` by ``n`` elements at a time.
>>> for x, y in chunk_by(2, [1, 2, 3, 4, 5]):
... # iteration no 1: x=1, y=2
... # iteration no 2: x=3, y=4
... # iteration no 3: x=5, y=None
:param n: (int) a chun... |
python | def textrank(self, sentence, topK=20, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v'), withFlag=False):
"""
Extract keywords from sentence using TextRank algorithm.
Parameter:
- topK: return how many top keywords. `None` for all possible words.
- withWeight: if True, re... |
python | def parse(base_dir: str, timestamp: int = None) -> int:
"""
Parse and update from archived cache files. Only accept new content;
do not overwrite any existing cache content.
:param base_dir: archive base directory
:param timestamp: epoch time of cache serving as subdirectory, de... |
java | public UserInfoCB acceptPK(String id) {
assertObjectNotNull("id", id);
BsUserInfoCB cb = this;
cb.query().docMeta().setId_Equal(id);
return (UserInfoCB) this;
} |
java | public static <E> Distribution<E> simpleGoodTuring(Counter<E> counter, int numberOfKeys) {
// check arguments
validateCounter(counter);
int numUnseen = numberOfKeys - counter.size();
if (numUnseen < 1)
throw new IllegalArgumentException(String.format("ERROR: numberOfKeys %d must be > size o... |
python | def convert_param_to_dirname(param):
""" Helper function to convert a parameter value to a valid directory name. """
if type(param) == types.StringType:
return param
else:
return re.sub("0+$", '0', '%f'%param) |
python | def check_url_warnings(self):
"""Check URL name and length."""
effectiveurl = urlutil.urlunsplit(self.urlparts)
if self.url != effectiveurl:
self.add_warning(_("Effective URL %(url)r.") %
{"url": effectiveurl},
tag=WARN_URL_EF... |
java | @Override
public List<CommerceRegion> findAll(int start, int end) {
return findAll(start, end, null);
} |
java | static Optional<Method> getGetterForSetter(final Method setter, final Class<?> clazz) {
// Attempt to find "getFoo" and then "isFoo"; the parameter type is not
// definitively indicative of get vs is because an Optional wrapped
// boolean can be exposed as get instead of is. Finally, attempt no ... |
java | @Override
public void setMulticastInterface(String mi) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "setMulticastInterface", mi);
jcaManagedConnectionFactory.setMulticastInterface(mi);
if (TraceComponent.isAnyTracingEnabled() && tc.isEn... |
python | def get_network_mode(value):
"""
Generates input for the ``network_mode`` of a Docker host configuration. If it points at a container, the
configuration of the container is returned.
:param value: Network mode input.
:type value: unicode | str | tuple | list | NoneType
:return: Network mode or ... |
java | public @CheckForNull Queue.Executable getCurrentExecutable() {
lock.readLock().lock();
try {
return executable;
} finally {
lock.readLock().unlock();
}
} |
java | public ServiceFuture<List<StorageAccountInfoInner>> listStorageAccountsAsync(final String resourceGroupName, final String accountName, final ListOperationCallback<StorageAccountInfoInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listStorageAccountsSinglePageAsync(resourceGroupN... |
java | public static RedisClusterClient create(ClientResources clientResources, Iterable<RedisURI> redisURIs) {
assertNotNull(clientResources);
assertNotEmpty(redisURIs);
assertSameOptions(redisURIs);
return new RedisClusterClient(clientResources, redisURIs);
} |
python | def modifier_list_id(self, modifier_list_id):
"""
Sets the modifier_list_id of this CatalogItemModifierListInfo.
The ID of the [CatalogModifierList](#type-catalogmodifierlist) controlled by this [CatalogModifierListInfo](#type-catalogmodifierlistinfo).
:param modifier_list_id: The modif... |
java | public static AbstractMolecule getMoleculeForMonomer(final Monomer monomer) throws BuilderMoleculeException, ChemistryException {
String input = getInput(monomer);
if (input != null) {
List<Attachment> listAttachments = monomer.getAttachmentList();
AttachmentList list = new AttachmentList();
... |
python | def generateVectors():
"""Convert the known ra/decs of the channel corners
into unit vectors. This code creates the conents of the
function loadOriginVectors() (below)
"""
ra_deg = 290.66666667
dec_deg = +44.5
#rollAngle_deg = 33.0
rollAngle_deg = +123.
boresight = r.vecFromRaDec(ra... |
python | def image(self):
"""Counts image (`~astropy.io.fits.ImageHDU`)."""
events = self.event_table
skycoord = SkyCoord(events['GLON'], events['GLAT'], unit='deg', frame='galactic')
pixcoord = PixCoord.from_sky(skycoord=skycoord, wcs=self.wcs)
shape = self.config['shape']
bins ... |
java | public static java.lang.reflect.Constructor read(ObjectInput in) throws ClassNotFoundException, IOException, NoSuchMethodException {
Class cl;
Class[] types;
cl = ClassRef.read(in);
if (cl == null) {
return null;
} else {
types = ClassRef.readClasses(in);... |
python | def mousePressEvent(self, event):
"""Reimplement Qt method"""
if event.button() == Qt.LeftButton:
self.__drag_start_pos = QPoint(event.pos())
QTabBar.mousePressEvent(self, event) |
java | public BigInteger calculateFofX(final BigInteger x)
{
// pick up the 0th term directly:
BigInteger ret = coefficients[0];
// for each of the other terms:
for (int term = 1, n = coefficients.length; term < n; term++)
{
// the index of term N is N:
fina... |
java | public static void vertical(Kernel1D_S32 kernel, InterleavedU16 src, InterleavedI16 dst ) {
InputSanityCheck.checkSameShapeB(src, dst);
boolean processed = BOverrideConvolveImageNormalized.invokeNativeVertical(kernel,src,dst);
if( !processed ) {
if( kernel.width >= src.height ) {
ConvolveNormalizedNaiv... |
python | def classify_collection(self, classifier_id, collection, **kwargs):
"""
Classify multiple phrases.
Returns label information for multiple phrases. The status must be `Available`
before you can use the classifier to classify text.
Note that classifying Japanese texts is a beta fe... |
java | public KeyBundle recoverDeletedKey(String vaultBaseUrl, String keyName) {
return recoverDeletedKeyWithServiceResponseAsync(vaultBaseUrl, keyName).toBlocking().single().body();
} |
python | def __get_button_events(self, state, timeval=None):
"""Get the button events from xinput."""
changed_buttons = self.__detect_button_events(state)
events = self.__emulate_buttons(changed_buttons, timeval)
return events |
python | def quaternion_to_rotation_matrix(quaternion):
"""Compute the rotation matrix representated by the quaternion"""
c, x, y, z = quaternion
return np.array([
[c*c + x*x - y*y - z*z, 2*x*y - 2*c*z, 2*x*z + 2*c*y ],
[2*x*y + 2*c*z, c*c - x*x + y*y - z*z, 2*y*z - 2*c*x ... |
python | def bonds(self):
"""Return all bonds in the Compound and sub-Compounds.
Yields
-------
tuple of mb.Compound
The next bond in the Compound
See Also
--------
bond_graph.edges_iter : Iterates over all edges in a BondGraph
"""
if self.ro... |
java | public boolean addAll(Collection<T> items)
{
boolean wasAllAdded = true;
for (T item : items)
{
if(!add(item))
wasAllAdded = false;
}
return wasAllAdded;
} |
java | public static Node getNodeByLineCol(Node ancestor, int lineNo, int columNo) {
checkArgument(ancestor.isScript());
Node current = ancestor;
Node result = null;
while (current != null) {
int currLineNo = current.getLineno();
checkState(current.getLineno() <= lineNo);
Node nextSibling = c... |
java | public <T> void set(String key, T value) {
data.put(key, value);
} |
java | @Override
public void updatePinnedInodes(Set<Long> inodes) {
LOG.debug("updatePinnedInodes: inodes={}", inodes);
synchronized (mPinnedInodes) {
mPinnedInodes.clear();
mPinnedInodes.addAll(Preconditions.checkNotNull(inodes));
}
} |
python | def Smith(x, rhol, rhog):
r'''Calculates void fraction in two-phase flow according to the model of
[1]_, also given in [2]_ and [3]_.
.. math::
\alpha = \left\{1 + \left(\frac{1-x}{x}\right)
\left(\frac{\rho_g}{\rho_l}\right)\left[K+(1-K)
\sqrt{\frac{\frac{\rho_l}{\rho_g} + K\left(... |
java | @Nonnull
private EChange _queueUniqueWorkItem (@Nonnull final IIndexerWorkItem aWorkItem)
{
ValueEnforcer.notNull (aWorkItem, "WorkItem");
// Check for duplicate
m_aRWLock.writeLock ().lock ();
try
{
if (!m_aUniqueItems.add (aWorkItem))
{
LOGGER.info ("Ignoring work item " +... |
java | public Object execute(final Object value, final CsvContext context) {
validateInputNotNull(value, context);
final String stringValue = value.toString();
for( String forbidden : forbiddenSubStrings ) {
if( stringValue.contains(forbidden) ) {
throw new SuperCsvConstraintViolationException(String.format... |
python | def get_user(self):
"""Access basic account information."""
method = 'GET'
endpoint = '/rest/v1/users/{}'.format(self.client.sauce_username)
return self.client.request(method, endpoint) |
java | public String getLocalName(int nodeHandle)
{
int expType = _exptype(makeNodeIdentity(nodeHandle));
if (expType == DTM.PROCESSING_INSTRUCTION_NODE)
{
int dataIndex = _dataOrQName(makeNodeIdentity(nodeHandle));
dataIndex = m_data.elementAt(-dataIndex);
return m_valuesOrPrefixes.indexToStr... |
java | @Nonnull
public static <T1, T2> LBiObjSrtPredicate<T1, T2> biObjSrtPredicateFrom(Consumer<LBiObjSrtPredicateBuilder<T1, T2>> buildingFunction) {
LBiObjSrtPredicateBuilder builder = new LBiObjSrtPredicateBuilder();
buildingFunction.accept(builder);
return builder.build();
} |
python | def push(self, image_id, service_name, tag=None, namespace=None, url=None, username=None, password=None,
repository_prefix=None, **kwargs):
"""
Push an image to a remote registry.
"""
auth_config = {
'username': username,
'password': password
... |
java | public GatewayResponse withResponseTemplates(java.util.Map<String, String> responseTemplates) {
setResponseTemplates(responseTemplates);
return this;
} |
python | def load_bbg_stock(sid_or_accessor, start=None, end=None, dvds=True):
"""terminal and datamgr are mutually exclusive.
:param sid_or_accessor: security identifier or SidAccessor from DataManager
:param start:
:param end:
:param dvds:
:return:
"""
end = end and pd.to_datetime(end) or pd.d... |
python | def nap(self) -> None:
"""
Go to sleep for the duration of self.delay.
:returns: None
"""
self.log.info(f"Sleeping for {self.delay} seconds.")
for _ in progress.bar(range(self.delay)):
time.sleep(1) |
java | public GenericTemplateElementBuilder addPostbackButton(String title,
String payload) {
Button button = ButtonFactory.createPostbackButton(title, payload);
this.element.addButton(button);
return this;
} |
python | def _bse_cli_get_refs(args):
'''Handles the get-refs subcommand'''
return api.get_references(
basis_name=args.basis, elements=args.elements, version=args.version, fmt=args.reffmt, data_dir=args.data_dir) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.