language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def save(self, parent=None):
"""
Either creates a resource or updates it (if it already has an id).
This will trigger an api POST or PATCH request.
:returns: the resource itself
"""
if self.id:
return self.update(parent=parent)
else:
return... |
java | private static Configuration injectTransactionManager(TransactionManagerLookupDelegator transactionManagerLookupDelegator, Configuration configuration) {
if ( configuration.transaction().transactionMode() == TransactionMode.TRANSACTIONAL ) {
ConfigurationBuilder builder = new ConfigurationBuilder().read( configura... |
python | def fastqmover(self):
"""Links .fastq files created above to :sequencepath"""
# Create the sequence path if necessary
make_path(self.sequencepath)
# Iterate through all the sample names
for sample in self.metadata.samples:
# Make directory variables
output... |
java | List<Endpoint> endpoints() {
try {
String urlString = String.format("%s/api/v1/namespaces/%s/pods", kubernetesMaster, namespace);
return enrichWithPublicAddresses(parsePodsList(callGet(urlString)));
} catch (RestClientException e) {
return handleKnownException(e);
... |
java | @SuppressWarnings("deprecation")
public <T> ResourceLeakDetector<T> newResourceLeakDetector(Class<T> resource, int samplingInterval) {
return newResourceLeakDetector(resource, ResourceLeakDetector.SAMPLING_INTERVAL, Long.MAX_VALUE);
} |
python | def _batchify(self, data_source):
"""Load data from underlying arrays, internal use only."""
assert self.cursor < self.num_data, 'DataIter needs reset.'
# first batch of next epoch with 'roll_over'
if self.last_batch_handle == 'roll_over' and \
-self.batch_size < self.cursor ... |
python | def get(self, key, *, default=None, cast_func=None, case_sensitive=None, raise_exception=None, warn_missing=None, use_cache=True, additional_sources=[]):
"""
Gets the setting specified by ``key``. For efficiency, we cache the retrieval of settings to avoid multiple searches through the sources list.
... |
python | def _snake_case(cls, text):
"""
Transform text to snake cale (Based on SCREAMING_SNAKE_CASE)
:param text:
:return:
"""
if text.islower():
return text
return cls._screaming_snake_case(text).lower() |
java | public MapWithProtoValuesFluentAssertion<M> withPartialScopeForValues(FieldScope fieldScope) {
return usingConfig(config.withPartialScope(checkNotNull(fieldScope, "fieldScope")));
} |
java | public void addClassesSummary(ClassDoc[] classes, String label,
String tableSummary, String[] tableHeader, Content packageSummaryContentTree) {
addClassesSummary(classes, label, tableSummary, tableHeader,
packageSummaryContentTree, profile.value);
} |
java | public static String format(final String code, final Properties options, final LineEnding lineEnding) {
Check.notEmpty(code, "code");
Check.notEmpty(options, "options");
Check.notNull(lineEnding, "lineEnding");
final CodeFormatter formatter = ToolFactory.createCodeFormatter(options);
final String lineSeparat... |
java | @SuppressWarnings("unchecked")
public <KP extends Object> KP getKeyPart(final Class<KP> keyPartClass) {
return (KP) getListKeyPart().stream()
.filter(kp -> kp != null && keyPartClass.isAssignableFrom(kp.getClass()))
.findFirst()
... |
java | public static int mulAndCheck (int x, int y) throws ArithmeticException {
long m = ((long)x) * ((long)y);
if (m < Integer.MIN_VALUE || m > Integer.MAX_VALUE) {
throw new ArithmeticException();
}
return (int)m;
} |
python | def get_lrc(self):
"""
返回当前播放歌曲歌词
"""
if self._playingsong != self._pre_playingsong:
self._lrc = douban.get_lrc(self._playingsong)
self._pre_playingsong = self._playingsong
return self._lrc |
java | @Override
public Iterator findMembers(IEntityGroup eg) throws GroupsException {
Collection members = new ArrayList(10);
Iterator it = null;
for (it = findMemberGroups(eg); it.hasNext(); ) {
members.add(it.next());
}
for (it = findMemberEntities(eg); it.hasNext();... |
python | def encode_payload(cls, payload):
'''Encode a Python object as JSON and convert it to bytes.'''
try:
return json.dumps(payload).encode()
except TypeError:
msg = f'JSON payload encoding error: {payload}'
raise ProtocolError(cls.INTERNAL_ERROR, msg) from None |
python | def get_mx(self, tree: Union[ast.Symbol, ast.ComponentRef, ast.Expression]) -> ca.MX:
"""
We pull components and symbols from the AST on demand.
This is to ensure that parametrized vector dimensions can be resolved. Vector
dimensions need to be known at CasADi MX creation time.
... |
python | def handle_template(bot_or_project, name, target=None, **options):
"""
Copy either a bot layout template or a Trading-Bots project
layout template into the specified directory.
:param bot_or_project: The string 'bot' or 'project'.
:param name: The name of the bot or project.
:param target: The d... |
java | public static base_responses add(nitro_service client, cachepolicylabel resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
cachepolicylabel addresources[] = new cachepolicylabel[resources.length];
for (int i=0;i<resources.length;i++){
addresource... |
java | protected void release(ByteArray byteArray) {
if (byteArray instanceof PooledByteArray) {
PooledByteArray pooledArray = (PooledByteArray) byteArray;
if (pooledArray.release()) {
this.byteArrayPool.release(byteArray.getBytes());
}
}
} |
java | public static int Maximum(ImageSource fastBitmap, int startX, int startY, int width, int height) {
int max = 0;
if (fastBitmap.isGrayscale()) {
for (int i = startX; i < height; i++) {
for (int j = startY; j < width; j++) {
int gray = fastBitmap.getR... |
python | def replace_uid(old_uwnetid, new_uwnetid, no_custom_fields=True):
"""
Return a list of BridgeUser objects without custom fields
"""
url = author_uid_url(old_uwnetid)
if not no_custom_fields:
url += ("?%s" % CUSTOM_FIELD)
resp = patch_resource(url, '{"user":{"uid":"%s@uw.edu"}}' % new_uwn... |
java | public ListShardsResult withShards(Shard... shards) {
if (this.shards == null) {
setShards(new com.amazonaws.internal.SdkInternalList<Shard>(shards.length));
}
for (Shard ele : shards) {
this.shards.add(ele);
}
return this;
} |
java | public static List<File> changeAllFilenameSuffix(final File file, final String oldSuffix,
final String newSuffix, final boolean delete)
throws IOException, FileDoesNotExistException, FileIsADirectoryException
{
boolean success;
List<File> notDeletedFiles = null;
final String filePath = file.getAbsolutePath()... |
python | def replace_payment_transaction_by_id(cls, payment_transaction_id, payment_transaction, **kwargs):
"""Replace PaymentTransaction
Replace all attributes of PaymentTransaction
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=... |
python | def iterRun(self, sqlTail = '', raw = False) :
"""Compile filters and run the query and returns an iterator. This much more efficient for large data sets but
you get the results one element at a time. One thing to keep in mind is that this function keeps the cursor open, that means that the sqlite databae is locked... |
java | private static Matrix readMatlabSparse(
File matrixFile,
Type matrixType,
boolean transposeOnRead) throws IOException {
Matrix matrix = new GrowingSparseMatrix();
BufferedReader br = new BufferedReader(new FileReader(matrixFile));
for (String line = nul... |
python | def compile_cxxfile(module_name, cxxfile, output_binary=None, **kwargs):
'''c++ file -> native module
Return the filename of the produced shared library
Raises CompileError on failure
'''
builddir = mkdtemp()
buildtmp = mkdtemp()
extension_args = make_extension(python=True, **kwargs)
... |
java | public ErrorPage getErrorPageTraverseRootCause(Throwable th) {
while (th != null && th instanceof ServletException) { // defect 155880
// - Check
// rootcause !=
// null
Throwable rootCause = ((ServletException) th).getRootCause();
if (rootCause == nul... |
python | def isRef(self, doc, attr):
"""Determine whether an attribute is of type Ref. In case we
have DTD(s) then this is simple, otherwise we use an
heuristic: name Ref (upper or lowercase). """
if doc is None: doc__o = None
else: doc__o = doc._o
if attr is None: attr__o = ... |
java | public void registerProvider(Object provider) {
if (provider != null) {
Collection<Object> providerList = new ArrayList<>(1);
providerList.add(provider);
registerProviders(providerList);
}
} |
java | public void setCalendar(Calendar calendar) {
if (calendar == null) {
dateEditor.setDate(null);
} else {
dateEditor.setDate(calendar.getTime());
}
} |
python | def _getVirtualScreenBitmap(self):
""" Returns a PIL bitmap (BGR channel order) of all monitors
Arranged like the Virtual Screen
"""
# Collect information about the virtual screen & monitors
min_x, min_y, screen_width, screen_height = self._getVirtualScreenRect()
monito... |
java | @SuppressWarnings("rawtypes")
public MonetaryAmountFactory getMonetaryAmountFactory() {
MonetaryAmountFactory factory = get(MonetaryAmountFactory.class);
if (factory == null) {
return Monetary.getDefaultAmountFactory();
}
return factory;
} |
java | public void setGatewayGroups(java.util.Collection<GatewayGroupSummary> gatewayGroups) {
if (gatewayGroups == null) {
this.gatewayGroups = null;
return;
}
this.gatewayGroups = new java.util.ArrayList<GatewayGroupSummary>(gatewayGroups);
} |
python | def flatten_unique(l: Iterable) -> List:
""" Return a list of UNIQUE non-list items in l """
rval = OrderedDict()
for e in l:
if not isinstance(e, str) and isinstance(e, Iterable):
for ev in flatten_unique(e):
rval[ev] = None
else:
rval[e] = None
r... |
python | def connection_made(self, transport):
"""Do the websocket handshake.
According to https://tools.ietf.org/html/rfc6455
"""
randomness = os.urandom(16)
key = base64encode(randomness).decode('utf-8').strip()
self.transport = transport
message = "GET / HTTP/1.1\r\n"
... |
python | def _get_magnitude_scaling(self, C, mag):
"""
Implements the magnitude scaling function F(M) presented in equation 4
"""
if mag < self.CONSTANTS["mh"]:
return C["e1"] + C["b1"] * (mag - self.CONSTANTS["mref"]) +\
C["b2"] * ((mag - self.CONSTANTS["mref"]) ** 2.... |
python | def get(self, uri, params={}):
'''A generic method to make GET requests'''
logging.debug("Requesting URL: "+str(urlparse.urljoin(self.BASE_URL, uri)))
return requests.get(urlparse.urljoin(self.BASE_URL, uri),
params=params, verify=False,
auth=self.auth) |
python | def _format_obj(self, item=None):
""" Determines the type of the object and maps it to the correct
formatter
"""
# Order here matters, odd behavior with tuples
if item is None:
return getattr(self, 'number')(item)
elif isinstance(item, self.str_):
... |
python | def setStr(self, name, n, value):
"""
setStr(CHeaderMap self, std::string name, limix::muint_t n, std::string value)
Parameters
----------
name: std::string
n: limix::muint_t
value: std::string
"""
return _core.CHeaderMap_setStr(self, name, n, va... |
python | def _call_method(self, method_name, *args, **kwargs):
"""Call the corresponding method using RIBCL, RIS or REDFISH
Make the decision to invoke the corresponding method using RIBCL,
RIS or REDFISH way. In case of none, throw out ``NotImplementedError``
"""
if self.use_redfish_onl... |
java | public MapWritable getValueMapWritable(String label) {
HadoopObject o = getHadoopObject(VALUE, label, ObjectUtil.MAP, "Map");
if (o == null) {
return null;
}
return (MapWritable) o.getObject();
} |
python | def dump_bulk(cls, parent=None, keep_ids=True):
"""Dumps a tree branch to a python data structure."""
serializable_cls = cls._get_serializable_model()
if (
parent and serializable_cls != cls and
parent.__class__ != serializable_cls
):
parent =... |
python | def _show_final_overflow_message(self, row_overflow, col_overflow):
"""Displays overflow message after import in statusbar"""
if row_overflow and col_overflow:
overflow_cause = _("rows and columns")
elif row_overflow:
overflow_cause = _("rows")
elif col_overflow:... |
java | @Override
public Long zremrangeByRank(final byte[] key, final long start, final long stop) {
checkIsInMultiOrPipeline();
client.zremrangeByRank(key, start, stop);
return client.getIntegerReply();
} |
java | public static String getSystemProperty(final String string) throws PrivilegedActionException {
return AccessController.doPrivileged(new PrivilegedAction<String>() {
@Override
public String run() {
return System.getProperty(string);
}
});
} |
python | def close(self):
"""
Closes all the iterators.
This is particularly important if the iterators are files.
"""
if hasattr(self, 'iterators'):
for it in self.iterators:
if hasattr(it, 'close'):
it.close() |
python | def compute_correction_factors(data, true_conductivity, elem_file, elec_file):
"""Compute correction factors for 2D rhizotron geometries, following
Weigand and Kemna, 2017, Biogeosciences
https://doi.org/10.5194/bg-14-921-2017
Parameters
----------
data : :py:class:`pandas.DataFrame`
m... |
java | private static String asString(ArrayList<RePairSymbolRecord> symbolizedString) {
StringBuffer res = new StringBuffer();
RePairSymbolRecord s = symbolizedString.get(0); // since digrams are starting from left symbol,
// the symbol 0 is never NULL
do {
... |
java | public List<CeQueueDto> selectByMainComponentUuid(DbSession session, String projectUuid) {
return mapper(session).selectByMainComponentUuid(projectUuid);
} |
python | def create_repo(self,
name,
description='',
homepage='',
private=False,
has_issues=True,
has_wiki=True,
has_downloads=True,
team_id=0,
auto_... |
python | def line_iterator(readable_file, size=None):
# type: (IO[bytes], Optional[int]) -> Iterator[bytes]
"""Iterate over the lines of a file.
Implementation reads each char individually, which is not very
efficient.
Yields:
str: a single line in the file.
"""
read = readable_file.read
... |
java | private int ratioRemove(int[] h) {
computeRatio();
int minIndex = Integer.MAX_VALUE;
double minValue = Double.MAX_VALUE;
for (int i = 0; i < nbHash; i++) {
if (ratio[h[i]] < minValue) {
minValue = ratio[h[i]];
minIndex = h[i];
}
}
return minIndex;
} |
python | def hicup_alignment_chart (self):
""" Generate the HiCUP Aligned reads plot """
# Specify the order of the different possible categories
keys = OrderedDict()
keys['Unique_Alignments_Read'] = { 'color': '#2f7ed8', 'name': 'Unique Alignments' }
keys['Multiple_Alignments_Read'] =... |
python | def is_valid_requeue_limit(requeue_limit):
"""Checks if the given requeue limit is valid.
A valid requeue limit is always greater than
or equal to -1.
"""
if not isinstance(requeue_limit, (int, long)):
return False
if requeue_limit <= -2:
return False
return True |
java | protected Boolean parseInstanceStatus(InstanceStatus status) {
if (status == null) {
return null;
}
return status == InstanceStatus.UP;
} |
java | public Observable<Page<NetworkSecurityGroupInner>> listAsync() {
return listWithServiceResponseAsync()
.map(new Func1<ServiceResponse<Page<NetworkSecurityGroupInner>>, Page<NetworkSecurityGroupInner>>() {
@Override
public Page<NetworkSecurityGroupInner> call(ServiceRe... |
java | public NotificationSettings getProjectNotificationSettings(int projectId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", projectId, "notification_settings");
return (response.readEntity(NotificationSettings.class));
} |
python | def get_pay_giftcard(self, rule_id):
"""
查询支付后投放卡券的规则
详情请参见
https://mp.weixin.qq.com/wiki?id=mp1466494654_K9rNz
:param rule_id: 支付即会员的规则 ID
:return: 支付后投放卡券的规则
:rtype: dict
"""
return self._post(
'card/paygiftcard/getbyid',
... |
java | @Override
public View generateView(Context ctx) {
VH viewHolder = getViewHolder(createView(ctx, null));
//as we already know the type of our ViewHolder cast it to our type
bindView(viewHolder, Collections.EMPTY_LIST);
//return the bound view
return viewHolder.itemView;
... |
python | def image(self, height=1, module_width=1, add_quiet_zone=True):
"""Get the barcode as PIL.Image.
By default the image is one pixel high and the number of modules pixels wide, with 10 empty modules added to
each side to act as the quiet zone. The size can be modified by setting height and module... |
python | def get_var(self, name):
"""Return an nd array from model library"""
# How many dimensions.
rank = self.get_var_rank(name)
# The shape array is fixed size
shape = np.empty((MAXDIMS, ), dtype='int32', order='F')
shape = self.get_var_shape(name)
# there should be no... |
java | @Override
public final PArray optArray(final String key, final PArray defaultValue) {
PArray result = optArray(key);
return result == null ? defaultValue : result;
} |
java | protected void NCName()
{
m_ops.setOp(m_ops.getOp(OpMap.MAPINDEX_LENGTH), m_queueMark - 1);
m_ops.setOp(OpMap.MAPINDEX_LENGTH, m_ops.getOp(OpMap.MAPINDEX_LENGTH) + 1);
nextToken();
} |
java | @Override
public Map<String, FieldTypes> get(final Collection<String> fieldNames, Collection<String> indexNames) {
// Shortcut - if we don't select any fields we don't have to do any database query
if (fieldNames.isEmpty()) {
return Collections.emptyMap();
}
// We have t... |
java | public static byte toByte(TypeOfAddress toa) {
byte b = 0;
if (toa.getTon() != null) {
b |= ( toa.getTon().toInt() << 0 );
}
if (toa.getNpi() != null) {
b |= ( toa.getNpi().toInt() << 4 );
}
b |= ( 1 << 7 );
return b;
} |
java | public static <T> T queryBean(String sql, Class<T> beanType, Object[] params)
throws YankSQLException {
return queryBean(YankPoolManager.DEFAULT_POOL_NAME, sql, beanType, params);
} |
python | def _clone_post_init(self, obj=None, **kwargs):
"""
obj must be another Plottable instance. obj is used by Clone to properly
transfer all attributes onto this object.
"""
# Initialize the extra attributes
if obj is None or obj is self:
# We must be asrootpy-in... |
python | def send_array(
socket, A=None, metadata=None, flags=0,
copy=False, track=False, compress=None,
chunksize=50 * 1000 * 1000
):
"""send a numpy array with metadata over zmq
message is mostly multipart:
metadata | array part 1 | array part 2, etc
only metadata:
metadata
t... |
java | public static void registerMbean(MBeanServer server, ModelMBean mbean, ObjectName name) {
try {
synchronized(LOCK) {
if(server.isRegistered(name))
JmxUtils.unregisterMbean(server, name);
server.registerMBean(mbean, name);
}
} ca... |
python | def find_bled112_devices(cls):
"""Look for BLED112 dongles on this computer and start an instance on each one"""
found_devs = []
ports = serial.tools.list_ports.comports()
for port in ports:
if not hasattr(port, 'pid') or not hasattr(port, 'vid'):
continue
... |
python | def dados_qrcode(cfe):
"""Compila os dados que compõem o QRCode do CF-e-SAT, conforme a
documentação técnica oficial **Guia para Geração do QRCode pelo Aplicativo
Comercial**, a partir de uma instância de ``ElementTree`` que represente a
árvore do XML do CF-e-SAT.
:param cfe: Instância de :py:mod:`... |
python | def bfs(self, graph, start):
"""
Performs BFS operation for eliminating useless loop transitions
Args:
graph (PDA): the PDA object
start (PDA state): The PDA initial state
Returns:
list: A cleaned, smaller list of DFA states
"""
newstat... |
python | def getRanking(self, profile, sampleFileName = None):
"""
Returns a list of lists that orders all candidates in tiers from best to worst when we use
MCMC approximation to compute Bayesian utilities for an election profile.
:ivar Profile profile: A Profile object that represents an elec... |
python | def connect_put_namespaced_pod_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_put_namespaced_pod_proxy # noqa: E501
connect PUT requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please... |
java | static synchronized String getTimeZoneDisplay(TimeZone tz, boolean daylight, int style, Locale locale) {
Object key = new TimeZoneDisplayKey(tz, daylight, style, locale);
String value = (String) cTimeZoneDisplayCache.get(key);
if (value == null) {
// This is a very slow call, so ... |
python | def hexdump(buf, num_bytes, offset=0, width=32):
"""Perform a hexudmp of the buffer.
Returns the hexdump as a canonically-formatted string.
"""
ind = offset
end = offset + num_bytes
lines = []
while ind < end:
chunk = buf[ind:ind + width]
actual_width = len(chunk)
he... |
java | public void setFloat(String key, float value)
{
checkKeyIsUniform(key);
checkFloatNotNaNOrInfinity("value", value);
NativeShaderData.setFloat(getNative(), key, value);
} |
java | public Future<PutItemResult> putItemAsync(final PutItemRequest putItemRequest)
throws AmazonServiceException, AmazonClientException {
return executorService.submit(new Callable<PutItemResult>() {
public PutItemResult call() throws Exception {
return putItem(putItemReques... |
python | def _contiguous_offsets(self, offsets):
"""
Sorts the input list of integer offsets,
ensures that values are contiguous.
"""
offsets.sort()
for i in range(len(offsets) - 1):
assert offsets[i] + 1 == offsets[i + 1], \
"Offsets not contiguous: %s... |
java | public void destroy(boolean removeFromQueue) {
if (mState == State.IDLE) {
return;
}
if (removeFromQueue) {
mThreadPoolExecutor.remove(this);
}
if (mState == State.DECODED) {
mMemoryCache.put(getCacheKey(), mBitmap);
}
mBitmap = null;
mDrawingOptions.inBitmap = null;
... |
java | @Override
public void setup(AbstractInvokable parent) {
@SuppressWarnings("unchecked")
final FlatMapFunction<IT, OT> mapper =
BatchTask.instantiateUserCode(this.config, userCodeClassLoader, FlatMapFunction.class);
this.mapper = mapper;
FunctionUtils.setFunctionRuntimeContext(mapper, getUdfRuntimeContext());... |
python | async def bluetooth(dev: Device, target, value):
"""Get or set bluetooth settings."""
if target and value:
await dev.set_bluetooth_settings(target, value)
print_settings(await dev.get_bluetooth_settings()) |
python | def _phi2deriv(self,R,z,phi=0.,t=0.):
"""
NAME:
_phi2deriv
PURPOSE:
evaluate the second azimuthal derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
... |
java | public static Lock toLock(Entity entity) {
return new Lock(entity.getKey().getName(),
(String) entity.getProperty(TRANSACTION_PROPERTY),
(Date) entity.getProperty(TIMESTAMP_PROPERTY));
} |
java | private List<SimulatorEvent> processTaskAttemptCompletionEvent(
TaskAttemptCompletionEvent event) {
if (LOG.isDebugEnabled()) {
LOG.debug("Processing task attempt completion event" + event);
}
long now = event.getTimeStamp();
TaskStatus finalStatus = event.getStatus();
TaskAttempt... |
java | protected void addProperties(Element element, BeanDefinitionBuilder builder) {
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Node node = attributes.item(i);
String attrName = getNodeName(node);
attrName ... |
python | def delFromTimeVary(self,*params):
'''
Removes any number of parameters from time_vary for this instance.
Parameters
----------
params : string
Any number of strings naming attributes to be removed from time_vary
Returns
-------
None
... |
java | @Override
public StateConnection onCloseRead()
{
ConnectionProtocol request = request();
if (request != null) {
request.onCloseRead();
}
_sequenceClose.set(_sequenceRead.get());
if (_sequenceFlush.get() < _sequenceClose.get()) {
_isClosePending.set(true);
... |
java | @Deprecated
public static FileSystem getProxiedFileSystem(@NonNull final String userNameToProxyAs, Properties properties,
URI fsURI) throws IOException {
return getProxiedFileSystem(userNameToProxyAs, properties, fsURI, new Configuration());
} |
java | public V retrieveOrCreate(K key, Factory<V> factory) {
// Clean up stale entries on every put.
// This should avoid a slow memory leak of reference objects.
this.cleanUpStaleEntries();
return retrieveOrCreate(key, factory, new FutureRef<V>());
} |
java | private void emitWindowResult(W window) throws Exception {
BaseRow aggResult = windowFunction.getWindowAggregationResult(window);
if (sendRetraction) {
previousState.setCurrentNamespace(window);
BaseRow previousAggResult = previousState.value();
// has emitted result for the window
if (previousAggResul... |
java | public boolean hasValue(String property, String value) {
boolean hasValue = false;
if (has()) {
Map<String, Object> fieldValues = buildFieldValues(property, value);
TResult result = getDao().queryForFieldValues(fieldValues);
try {
hasValue = result.getCount() > 0;
} finally {
result.close();
... |
java | public static String readable( Visitable visitable,
ExecutionContext context ) {
// return visit(visitable, new ReadableVisitor()).getString();
return visit(visitable, new JcrSql2Writer(context)).getString();
} |
python | def credit(self, amount, debit_account, description, debit_memo="", credit_memo="", datetime=None):
""" Post a credit of 'amount' and a debit of -amount against this account and credit_account respectively.
note amount must be non-negative.
"""
assert amount >= 0
return self.pos... |
python | def optimize(self, loss, num_async_replicas=1, use_tpu=False):
"""Return a training op minimizing loss."""
lr = learning_rate.learning_rate_schedule(self.hparams)
if num_async_replicas > 1:
log_info("Dividing learning rate by num_async_replicas: %d",
num_async_replicas)
lr /= math.s... |
java | public Map<String, String> getUriVariablesForQueryWithPost(BullhornEntityInfo entityInfo, Set<String> fieldSet, QueryParams params) {
Map<String, String> uriVariables = params.getParameterMap();
this.addCommonUriVariables(fieldSet, entityInfo, uriVariables);
return uriVariables;
} |
python | def spin(self, use_thread=False):
'''call callback for all data forever (until \C-c)
:param use_thread: use thread for spin (do not block)
'''
if use_thread:
if self._thread is not None:
raise 'spin called twice'
self._thread = threading.Thread(ta... |
java | public void readEofPacket() throws SQLException, IOException {
Buffer buffer = reader.getPacket(true);
switch (buffer.getByteAt(0)) {
case EOF:
buffer.skipByte();
this.hasWarnings = buffer.readShort() > 0;
this.serverStatus = buffer.readShort();
break;
case ERROR:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.