language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def run(self, qc: QuantumComputer, bitstring_map: Dict[str, str]) -> 'BernsteinVazirani':
"""
Runs the Bernstein-Vazirani algorithm.
Given a connection to a QVM or QPU, find the :math:`\\mathbf{a}` and :math:`b` corresponding
to the function represented by the oracle function that will ... |
java | private String validatePath(String path) throws CmsSecurityException {
// Problems with spaces in new folders (default: "Neuer Ordner")
// Solution: translate this to a correct name.
String ret = m_cms.getRequestContext().getFileTranslator().translateResource(path);
// add site root on... |
java | public static String decodeApacheHTTPDLogValue(String input){
if (input == null || input.length() == 0) {
return input;
}
if (!input.contains("\\")) {
return input;
}
StringBuilder sb = new StringBuilder(input.length());
// https://stackoverflow... |
java | public BillDetail<Bill> querySuccess(String deviceInfo, String date){
String data = query(deviceInfo, date, BillType.SUCCESS);
return renderBillDetail(data, BillFields.SUCCESS, Bill.class);
} |
java | public static <T> void isNull(final T object, final String message, final Object... values) {
INSTANCE.isNull(object, message, values);
} |
python | def install_napps(cls, napps):
"""Install local or remote NApps.
This method is recursive, it will install each napps and your
dependencies.
"""
mgr = NAppsManager()
for napp in napps:
mgr.set_napp(*napp)
LOG.info(' NApp %s:', mgr.napp_id)
... |
java | private static Bitmap fractionalDecode(FractionalDecodeShim shim,
Options options, int requestedWidth, int requestedHeight) {
final int rawWidth = options.outWidth;
final int rawHeight = options.outHeight;
final float sampledWidth = (float) rawWidth / options.inSampleSize;
fi... |
java | @Override
public Object onRequest(Object request, Map<String,String> headers) {
if (headers.containsKey(Listener.METAINFO_HTTP_METHOD)) {
Tracing tracing = TraceHelper.getTracing("mdw-service");
HttpTracing httpTracing = HttpTracing.create(tracing);
handler = HttpServerHa... |
python | def buildEmptyDRZ(input, output):
"""
Create an empty DRZ file.
This module creates an empty DRZ file in a valid FITS format so that the HST
pipeline can handle the Multidrizzle zero expossure time exception
where all data has been excluded from processing.
Parameters
----------
input ... |
python | def values():
"""Get the full current set of B3 values.
:return: A dict containing the keys "X-B3-TraceId", "X-B3-ParentSpanId", "X-B3-SpanId", "X-B3-Sampled" and
"X-B3-Flags" for the current span or subspan. NB some of the values are likely be None, but
all keys will be present.
"""
result = {}... |
python | def from_bytes(VarInt, byte_string):
'''
byte-like -> VarInt
accepts arbitrary length input, gets a VarInt off the front
'''
num = byte_string
if num[0] <= 0xfc:
num = num[0:1]
non_compact = False
elif num[0] == 0xfd:
num = num[... |
java | @SdkInternalApi
public static long getPartSize(GetObjectRequest getObjectRequest, AmazonS3 s3, int partNumber) {
ValidationUtils.assertNotNull(s3, "S3 client");
ValidationUtils.assertNotNull(getObjectRequest, "GetObjectRequest");
GetObjectMetadataRequest getObjectMetadataRequest = RequestCo... |
python | def me(self):
"""Similar to :attr:`Client.user` except an instance of :class:`Member`.
This is essentially used to get the member version of yourself.
"""
self_id = self._state.user.id
return self.get_member(self_id) |
python | def _coerce_fields_parameters(self, fields):
"""
Used by values and values_list to get the list of fields to use in the
redis sort command to retrieve fields.
The result is a dict with two lists:
- 'names', with wanted field names
- 'keys', with keys to use in the sor... |
python | def _release_save_states(self):
"""Releases application save states"""
self.saving = False
self.grid.Enable()
wx.EndBusyCursor()
# Mark content as unchanged
try:
post_command_event(self.main_window, self.ContentChangedMsg)
except TypeError:
... |
java | private void processCheckExpandedCustomNodes(final TreeItemIdNode node, final Set<String> expandedRows) {
// Node has no children
if (!node.hasChildren()) {
return;
}
// Check node is expanded
boolean expanded = getExpandMode() == WTree.ExpandMode.CLIENT || expandedRows.contains(node.getItemId());
if (!... |
java | private String classForType(Type type) {
switch (type) {
case ERROR:
return I_CmsLayoutBundle.INSTANCE.notificationCss().notificationError();
case NORMAL:
return I_CmsLayoutBundle.INSTANCE.notificationCss().notificationNormal();
case WARNING:
... |
python | def from_env(parser_modules: t.Optional[t.Union[t.List[str], t.Tuple[str]]] = DEFAULT_PARSER_MODULES,
env: t.Optional[t.Dict[str, str]] = None,
silent: bool = False,
suppress_logs: bool = False,
extra: t.Optional[dict] = None) -> 'ConfigLoader':
... |
java | public int getCurrentPage() {
try {
final int currentPage = _jsonObject.getJSONObject(META_OBJECT_FIELD).getInt("current_page");
return currentPage;
} catch (JSONException ex) {
throw new QuandlRuntimeException("Could not find total_count field in results from Quandl", ex);
}
} |
java | public void start() {
logger.info("----------------------------"); //$NON-NLS-1$
logger.info(Messages.i18n.format("StorageImportDispatcher.StartingImport")); //$NON-NLS-1$
policyDefIndex.clear();
currentOrg = null;
currentPlan = null;
currentApi = null;
currentCl... |
python | def request(self, *args, **kwargs):
""" Partial original request func and run it in a thread. """
func = partial(super().request, *args, **kwargs)
return self.loop.run_in_executor(self.thread_pool, func) |
java | public static boolean isZeros(DMatrixD1 m , double tol )
{
int length = m.getNumElements();
for( int i = 0; i < length; i++ ) {
if( Math.abs(m.get(i)) > tol )
return false;
}
return true;
} |
python | def custom_covariance(self,beta):
""" Creates Covariance Matrix for a given Beta Vector
(Not necessarily the OLS covariance)
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
Returns
----------
... |
python | def stop_main_thread(*args):
"""
CLEAN OF ALL THREADS CREATED WITH THIS LIBRARY
"""
try:
if len(args) and args[0] != _signal.SIGTERM:
Log.warning("exit with {{value}}", value=_describe_exit_codes.get(args[0], args[0]))
except Exception as _:
pass
finally:
MAIN... |
java | @Override
public void onError( WebSocket conn, Exception ex ) {
if( conn != null ) {
log.debug("Error on connection " + conn.getRemoteSocketAddress() + " ", ex);
} else {
log.debug("Error on WebSocketServer ", ex);
}
} |
python | def do_bp(self, arg):
"""
[~process] bp <address> - set a code breakpoint
"""
pid = self.get_process_id_from_prefix()
if not self.debug.is_debugee(pid):
raise CmdError("target process is not being debugged")
process = self.get_process(pid)
token_li... |
java | public String convertPageOverlayConditionalProcessingPgOvTypeToString(EDataType eDataType, Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
} |
java | public static Map makeMap(Mapper mapper, Iterator i, boolean includeNull) {
HashMap h = new HashMap();
for (; i.hasNext();) {
Object k = i.next();
Object v = mapper.map(k);
if (includeNull || v != null) {
h.put(k, v);
}
}
re... |
java | public LogSeqNum append(Constant[] rec) {
logMgrLock.lock();
try {
// two integers that point to the previous and next log records
int recsize = pointerSize * 2;
for (Constant c : rec)
recsize += Page.size(c);
// if the log record doesn't fit, move to the next block
if (currentPos + rec... |
python | def extract_docstring(filename):
""" Extract a module-level docstring, if any
"""
lines = file(filename).readlines()
start_row = 0
if lines[0].startswith('#!'):
lines.pop(0)
start_row = 1
docstring = ''
first_par = ''
tokens = tokenize.generate_tokens(iter(lines).next)
... |
java | private Image loadImage(final String resourceName, final boolean skipImagesFolder) {
Image image = null;
final List<String> imagePaths = skipImagesFolder ? Collections.singletonList("") : ResourceParameters.IMAGE_FOLDER.get();
for (int i = 0; i < imagePaths.size() && image == null; i++) {
... |
java | void deleteCheckpoint(long txId) throws IOException {
for (Iterator<StorageDirectory> it = storage.dirIterator(); it.hasNext();) {
StorageDirectory sd = it.next();
// image file
File imageFile = NNStorage.getImageFile(sd, txId);
if (imageFile.delete())
LOG.info("Delete checkpoint: de... |
python | def del_fields(self, *names):
"""Delete data fields from this struct instance"""
cls = type(self)
self.__class__ = cls
for n in names:
# don't raise error if a field is absent
if isinstance(getattr(cls, n, None), DataField):
if n in self._field_val... |
python | def _get_subplot_number(subplot_val):
"""
Extract the subplot number from a subplot value string.
'x3' -> 3
'polar2' -> 2
'scene' -> 1
'y' -> 1
Note: the absence of a subplot number (e.g. 'y') is treated by plotly as
a subplot number of 1
Parameters
----------
subplot_val:... |
java | @SuppressWarnings("deprecation")
void findItemsWithShortcutForKey(List<MenuItem> items, int keyCode, KeyEvent event) {
final boolean qwerty = isQwertyMode();
final int metaState = event.getMetaState();
final KeyCharacterMap.KeyData possibleChars = new KeyCharacterMap.KeyData();
// Ge... |
python | def _read(self, fp, fpname):
"""A direct copy of the py2.4 version of the super class's _read method
to assure it uses ordered dicts. Had to change one line to make it work.
Future versions have this fixed, but in fact its quite embarrassing for the
guys not to have done it right in the... |
java | public static void registerQueueLengthMetrics(MetricGroup group, SingleInputGate gate) {
InputGateMetrics metrics = new InputGateMetrics(gate);
group.gauge("totalQueueLen", metrics.getTotalQueueLenGauge());
group.gauge("minQueueLen", metrics.getMinQueueLenGauge());
group.gauge("maxQueueLen", metrics.getMaxQueu... |
python | def parse_url(self) -> RequestUrl:
"""
获取url解析对象
"""
if self._URL is None:
current_url = b"%s://%s%s" % (
encode_str(self.schema),
encode_str(self.host),
self._current_url
)
self._URL = RequestUrl(current... |
java | protected String buildOpenCmsButtonRow(int segment, I_CmsWidgetDialog widgetDialog) {
StringBuffer result = new StringBuffer(256);
if (segment == CmsWorkplace.HTML_START) {
// generate line and start row HTML
result.append(widgetDialog.buttonBarHorizontalLine());
re... |
java | @Override
public long executeLargeUpdate(String sql, int[] columnIndexes) throws SQLException {
return executeLargeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
} |
python | def _copy(self, filename, destination):
"""Copy a file or folder to the repository.
Will mount if needed.
Args:
filename: Path to copy.
destination: Remote path to copy file to.
"""
super(MountedRepository, self)._copy(filename, destination) |
java | public final boolean isShowing(LocalDate startDate, LocalDate endDate, ZoneId zoneId) {
return isShowing(this, startDate, endDate, zoneId);
} |
java | public static String checkAuthority(String authority) {
URI uri = authorityToUri(authority);
checkArgument(uri.getHost() != null, "No host in authority '%s'", authority);
checkArgument(uri.getUserInfo() == null,
"Userinfo must not be present on authority: '%s'", authority);
return authority;
} |
java | protected boolean doTypeMappingCheck(EObject source, JvmType type, Procedure3<? super EObject, ? super JvmType, ? super String> errorHandler) {
if (source != null && type != null) {
final ExtraLanguageTypeConverter converter = getTypeConverter();
final String qn = type.getQualifiedName();
if (converter != nu... |
java | @Override
public final void setReportPassMsgId(Boolean value) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "setReportPassMsgId", value);
if (value != null) {
getApi().setField(JsApiAccess.REPORTPASSMSGID_VALUE, value);
}
... |
java | private void injectCloseTag(
HtmlOpenTagNode optionalOpenTag, HtmlTagNode destinationTag, IdGenerator idGenerator) {
StandaloneNode openTagCopy = optionalOpenTag.getTagName().getNode().copy(new CopyState());
HtmlCloseTagNode syntheticClose =
new HtmlCloseTagNode(
idGenerator.genId(),
... |
python | def showOperandLines(rh):
"""
Produce help output related to operands.
Input:
Request Handle
"""
if rh.function == 'HELP':
rh.printLn("N", " For the GetHost function:")
else:
rh.printLn("N", "Sub-Functions(s):")
rh.printLn("N", " diskpoolnames - " +
"Re... |
python | def getinfo(self, type_):
"""Returns general information about the driver and data source
associated with a connection by calling SQLGetInfo and returning its
results. See Microsoft's SQLGetInfo documentation for the types of
information available.
:param type_: int, pyodbc.SQL_... |
java | @Around("anyProducerFactory()")
public Object wrapProducerFactory(ProceedingJoinPoint pjp) throws Throwable {
Producer producer = (Producer) pjp.proceed();
return this.kafkaTracing.producer(producer);
} |
java | private ShareTarget toShareTarget(ResolveInfo resolveInfo) {
if (resolveInfo == null || resolveInfo.activityInfo == null) {
return null;
}
ActivityInfo info = resolveInfo.activityInfo;
ShareTarget target = new ShareTarget(info.loadLabel(mPackageManager), info.loadIcon(mPackag... |
java | @FFDCIgnore(Throwable.class)
void introspectMBeanAttributes(MBeanServer mbeanServer, ObjectName mbean, PrintWriter writer) {
try {
// Dump the description and the canonical form of the object name
writer.println();
writer.print(mbeanServer.getMBeanInfo(mbean).getDescripti... |
python | def embed_MDS(X, ndim=2, how='metric', distance_metric='euclidean',
n_jobs=1, seed=None, verbose=0):
"""Performs classic, metric, and non-metric MDS
Metric MDS is initialized using classic MDS,
non-metric MDS is initialized using metric MDS.
Parameters
----------
X: ndarray [n_sa... |
python | def cleanSystem(cls):
"""
Removes all downloaded, localized resources
"""
resourceRootDirPath = os.environ[cls.rootDirPathEnvName]
os.environ.pop(cls.rootDirPathEnvName)
shutil.rmtree(resourceRootDirPath)
for k, v in list(os.environ.items()):
if k.star... |
python | def unpack_nested_exception(error):
"""
If exception are stacked, return the first one
:param error: A python exception with possible exception embeded within
:return: A python exception with no exception embeded within
"""
i = 0
while True:
if error.args[i:]:
... |
java | private void emitRecordWithTimestampAndPunctuatedWatermark(
T record, KafkaTopicPartitionState<KPH> partitionState, long offset, long kafkaEventTimestamp) {
@SuppressWarnings("unchecked")
final KafkaTopicPartitionStateWithPunctuatedWatermarks<T, KPH> withWatermarksState =
(KafkaTopicPartitionStateWithPunctua... |
python | def copy(self, empty=False):
"""returns an independent copy of the current object."""
# Create an empty object
newobject = self.__new__(self.__class__)
if empty:
return
# And fill it !
for prop in ["_properties","_side_properties",
... |
java | @XmlElementDecl(namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", name = "orderBy", scope = GetCheckedOutDocs.class)
public JAXBElement<String> createGetCheckedOutDocsOrderBy(String value) {
return new JAXBElement<String>(_GetChildrenOrderBy_QNAME, String.class,
GetCheckedOutDocs.class, valu... |
java | public final void setCardViewElevation(final int elevation) {
Condition.INSTANCE.ensureAtLeast(elevation, 0, "The elevation must be at least 0");
Condition.INSTANCE.ensureAtMaximum(elevation, ElevationUtil.MAX_ELEVATION,
"The elevation must be at maximum " + ElevationUtil.MAX_ELEVATION);... |
java | public void setUserManagementEnabled(String value) {
m_showUserGroupIcon = Boolean.valueOf(value).booleanValue();
if (CmsLog.INIT.isInfoEnabled()) {
if (m_showUserGroupIcon) {
CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_USER_MANAGEMENT_ICON_ENABLED_0));
... |
java | public static GrayU8 loadPGM_U8(InputStream inputStream , GrayU8 storage ) throws IOException {
DataInputStream in = new DataInputStream(inputStream);
readLine(in);
String line = readLine(in);
while( line.charAt(0) == '#')
line = readLine(in);
String s[] = line.split(" ");
int w = Integer.parseInt(s[0])... |
java | public Observable<ServiceResponse<BuildGetLogResultInner>> getLogLinkWithServiceResponseAsync(String resourceGroupName, String registryName, String buildId) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot... |
python | def getElementsByAttr(self, attrName, attrValue, root='root'):
'''
getElementsByAttr - Searches the full tree for elements with a given attribute name and value combination. This is always a full scan.
@param attrName <lowercase str> - A lowercase attribute name
... |
python | def update(self, record_id, fields, typecast=False):
"""
Updates a record by its record id.
Only Fields passed are updated, the rest are left as is.
>>> record = airtable.match('Employee Id', 'DD13332454')
>>> fields = {'Status': 'Fired'}
>>> airtable.update(recor... |
java | public Class<?> getClass(final String key, final Class<?> defaultClass) {
if (containsKey(key)) {
return getClass(key);
} else {
return defaultClass;
}
} |
java | @NotNull
public static <T> Comparator<T> reversed(@Nullable Comparator<T> comparator) {
return Collections.reverseOrder(comparator);
} |
python | def argmax(iterable, key=None, both=False):
"""
>>> argmax([4,2,-5])
0
>>> argmax([4,2,-5], key=abs)
2
>>> argmax([4,2,-5], key=abs, both=True)
(2, 5)
"""
if key is not None:
it = imap(key, iterable)
else:
it = iter(iterable)
score, argmax = reduce(max, izip(i... |
java | static void init() {
contextMap = null;
final PropertiesUtil managerProps = PropertiesUtil.getProperties();
disableAll = managerProps.getBooleanProperty(DISABLE_ALL);
useStack = !(managerProps.getBooleanProperty(DISABLE_STACK) || disableAll);
useMap = !(managerProps.getBooleanPro... |
java | @Override
public MediaFormat detectMediaFormat(@Nullable String extension, long fileSize, long width, long height) {
SortedSet<MediaFormat> matchingFormats = detectMediaFormats(extension, fileSize, width, height);
return !matchingFormats.isEmpty() ? matchingFormats.first() : null;
} |
java | public void run(Context context) throws IOException, InterruptedException {
setup(context);
while (context.nextKey()) {
context.progress();
reduce(context.getCurrentKey(), context.getValues(), context);
}
cleanup(context);
} |
java | protected Object getObjectFromResultSet() throws PersistenceBrokerException
{
Object[] result = new Object[columnCount];
for (int i = 0; i < columnCount; i++)
{
try
{
int jdbcType = rsMetaData.getColumnType(i + 1);
Object item =... |
java | public ClassSelector except(String... propertyNames) {
if(ArrayUtils.isEmpty(propertyNames)){
return this;
}
boolean updated = false;
for (String propertyToRemove : propertyNames) {
if (removePropertySelector(propertyToRemove)) {
updated = true;
}
}
if (updated) {
... |
java | @Override
public void eUnset(int featureID) {
switch (featureID) {
case ColorPackage.DOCUMENT_ROOT__MIXED:
getMixed().clear();
return;
case ColorPackage.DOCUMENT_ROOT__XMLNS_PREFIX_MAP:
getXMLNSPrefixMap().clear();
return;
case ColorPackage.DOCUMENT_ROOT__XSI_SCHEMA_LOCATION:
getXSISchem... |
java | public String substitute(List<String> values) throws IllegalArgumentException {
if (values == null) {
throw new IllegalArgumentException("values is null");
}
Iterator<String> iter = values.iterator();
StringBuilder sb = new StringBuilder();
for (UriChunk chunk : uriCh... |
java | public static int[] getSplit(int docId) {
if (docId <= 0) {
throw new IllegalArgumentException("docId must be positive");
}
int[] ret = new int[3];
ret[0] = docId / 1000000;
ret[1] = (docId % 1000000) / 1000;
ret[2] = docId % 1000;
return ret;
} |
python | def autonomous(self):
"""
Starts an autonomous region for downstream processing.
By default IBM Streams processing is executed in an autonomous region
where any checkpointing of operator state is autonomous (independent)
of other operators.
This method may be use... |
java | public void setMaxBoxHt(Integer newMaxBoxHt) {
Integer oldMaxBoxHt = maxBoxHt;
maxBoxHt = newMaxBoxHt;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.FNC__MAX_BOX_HT, oldMaxBoxHt, maxBoxHt));
} |
java | public Observable<StorageBundle> updateStorageAccountAsync(String vaultBaseUrl, String storageAccountName, String activeKeyName, Boolean autoRegenerateKey, String regenerationPeriod, StorageAccountAttributes storageAccountAttributes, Map<String, String> tags) {
return updateStorageAccountWithServiceResponseAsyn... |
python | def get_query_columns(query):
"""
:type query str
:rtype: list[str]
"""
columns = []
last_keyword = None
last_token = None
# print(preprocess_query(query))
# these keywords should not change the state of a parser
# and not "reset" previously found SELECT keyword
keywords_ig... |
java | @Override
public boolean fileCreated(File file) throws WatchingException {
try {
createApplicationBundle();
} catch (Exception e) {
throw new WatchingException(e.getMessage(), file, e);
}
return true;
} |
java | public int spanBack(CharSequence s, SpanCondition spanCondition) {
return spanBack(s, s.length(), spanCondition);
} |
python | def plot_poles_colorbar(map_axis, plons, plats, A95s, colorvalues, vmin, vmax,
colormap='viridis', edgecolor='k', marker='o', markersize='20',
alpha=1.0, colorbar=True, colorbar_label='pole age (Ma)'):
"""
This function plots multiple paleomagnetic pole and A95 er... |
java | final int recordExceptionalCompletion(Throwable ex) {
int s;
if ((s = status) >= 0) {
int h = System.identityHashCode(this);
final ReentrantLock lock = exceptionTableLock;
lock.lock();
try {
expungeStaleExceptions();
Excepti... |
python | def conv2d(ni:int, nf:int, ks:int=3, stride:int=1, padding:int=None, bias=False, init:LayerFunc=nn.init.kaiming_normal_) -> nn.Conv2d:
"Create and initialize `nn.Conv2d` layer. `padding` defaults to `ks//2`."
if padding is None: padding = ks//2
return init_default(nn.Conv2d(ni, nf, kernel_size=ks, stride=st... |
java | protected void incremenetMessageBatchNumber()
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "incremenetMessageBatchNumber");
checkNotBrowserSession(); // F171893
this.messageBatchNumber++;
if (TraceComponent.isAnyTra... |
python | def parse_routing_info(cls, records):
""" Parse the records returned from a getServers call and
return a new RoutingTable instance.
"""
if len(records) != 1:
raise RoutingProtocolError("Expected exactly one record")
record = records[0]
routers = []
rea... |
java | @XmlElementDecl(namespace = "http://www.w3.org/1998/Math/MathML", name = "laplacian")
public JAXBElement<LaplacianType> createLaplacian(LaplacianType value) {
return new JAXBElement<LaplacianType>(_Laplacian_QNAME, LaplacianType.class, null, value);
} |
java | public static RootContainer getRootContainer(final EntityContainer container) {
// Root must be identifable
if (!(container instanceof Identifiable)) {
return null;
}
EntityContainer parent = container instanceof Entity ? ((Entity) container).getContainer() : null;
UUID rootID = null;
// Check not root
if... |
java | public void marshall(ScalingPolicy scalingPolicy, ProtocolMarshaller protocolMarshaller) {
if (scalingPolicy == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(scalingPolicy.getPolicyName(), POLICYNAM... |
python | def append_diff_hist(diff, diff_hist=list()):
"""Given a diff as generated by record_diff, append a diff record to the
list of diff_hist records."""
diff, diff_hist = _norm_json_params(diff, diff_hist)
if not diff_hist:
diff_hist = list()
diff_hist.append({'diff': diff, 'diff_date': now_fi... |
java | public <T> ClaimValue<Optional<T>> generalClaimValueProducer(InjectionPoint ip) {
String name = getName(ip);
ClaimValueWrapper<Optional<T>> wrapper = new ClaimValueWrapper<>(name);
T value = getValue(name, false);
Optional<T> optValue = Optional.ofNullable(value);
wrapper.setValu... |
java | private Transaction getAndValidateWrappedTransaction() throws IllegalStateException {
final Transaction wrappedTransaction = getWrappedTransaction();
if (wrappedTransaction == null) {
throw new IllegalStateException();
}
else {
return wrappedTransaction;
}
} |
java | public static void setFaults(Message message, KnowledgeOperation operation, Map<String, Object> contextOverrides) {
setOutputsOrFaults(message, operation.getFaultExpressionMappings(), contextOverrides, FAULT, false);
} |
java | public int setString(long pos, String str, int offset,
int len) throws SQLException {
if (!this.createdByConnection) {
/** @todo - better error message */
throw Util.notSupported();
}
String ldata = this.data;
checkValid(ldata);
... |
python | def fcontext_policy_applied(name, recursive=False):
'''
.. versionadded:: 2017.7.0
Checks and makes sure the SELinux policies for a given filespec are
applied.
'''
ret = {'name': name, 'result': False, 'changes': {}, 'comment': ''}
changes_text = __salt__['selinux.fcontext_policy_is_applie... |
python | def _open_data_stream(self):
'''Open the data stream connection.
Coroutine.
'''
@asyncio.coroutine
def connection_factory(address: Tuple[int, int]):
self._data_connection = yield from self._acquire_connection(address[0], address[1])
return self._data_conn... |
python | def clean(ctx, state, dry_run=False, bare=False, user=False):
"""Uninstalls all packages not specified in Pipfile.lock."""
from ..core import do_clean
do_clean(ctx=ctx, three=state.three, python=state.python, dry_run=dry_run,
system=state.system) |
java | public void writeXML(OutputStream outputStream, String encoding, String indent, String lineSeparator)
throws IOException {
XMLOutputter outputter = new XMLOutputter();
Format format = Format.getPrettyFormat();
format.setEncoding(encoding);
format.setIndent(indent);
format.setLineSeparator(lineSepa... |
java | public Table concat(Table tableToConcatenate) {
Preconditions.checkArgument(tableToConcatenate.rowCount() == this.rowCount(),
"Both tables must have the same number of rows to concatenate them.");
for (Column<?> column : tableToConcatenate.columns()) {
this.addColumns(column)... |
python | def _setup_profiles(self, conversion_profiles):
'''
Add given conversion profiles checking for invalid profiles
'''
# Check for invalid profiles
for key, path in conversion_profiles.items():
if isinstance(path, str):
path = (path, )
for lef... |
python | def pruneToAtoms(self, atoms):
"""Prune the molecule to the specified atoms
bonds will be removed atomatically"""
_atoms = self.atoms[:]
for atom in _atoms:
if atom not in atoms:
self.remove_atom(atom) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.