language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def dump(self, o_name=None, details=False, raw=False):
"""Dump an host (all hosts) from the arbiter.
The arbiter will get the host (all hosts) information from all its schedulers.
This gets the main host information from the scheduler. If details is set, then some
more information are ... |
java | private void addInfoFromESS(EntitySrcSyn ess, int eId, EntityInfo c) {
c.setOrganismCommon(ess.getOrganism_common_name());
c.setOrganismScientific(ess.getOrganism_scientific());
c.setOrganismTaxId(ess.getNcbi_taxonomy_id());
} |
java | public EventFilter withEntityArns(String... entityArns) {
if (this.entityArns == null) {
setEntityArns(new java.util.ArrayList<String>(entityArns.length));
}
for (String ele : entityArns) {
this.entityArns.add(ele);
}
return this;
} |
python | def handle(self, key, value):
'''
Processes a vaild action info request
@param key: The key that matched the request
@param value: The value associated with the key
'''
# the master dict to return
master = {}
master['uuid'] = value
master['total_p... |
java | public JacksonDBCollection<T, K> enable(Feature feature) {
features.put(feature, true);
return this;
} |
java | public void setFNNRGLen(Integer newFNNRGLen) {
Integer oldFNNRGLen = fnnrgLen;
fnnrgLen = newFNNRGLen;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.FNC__FNNRG_LEN, oldFNNRGLen, fnnrgLen));
} |
python | def check_lazy_load_wegsegment(f):
'''
Decorator function to lazy load a :class:`Wegsegment`.
'''
def wrapper(*args):
wegsegment = args[0]
if (
wegsegment._methode_id is None or
wegsegment._geometrie is None or
wegsegment._metadata is None
):
... |
python | def get_event(self,
request,
tag='',
matcher=prefix_matcher.__func__,
callback=None,
timeout=None
):
'''
Get an event (asynchronous of course) return a future that will get it later
'''
... |
java | public boolean getBoolean(int index, boolean def) {
Object tmp = mArray.get(index);
return tmp != null && tmp instanceof Boolean ? ((Boolean) tmp)
.booleanValue() : def;
} |
python | def feedback_summaries(self):
"""
Access the feedback_summaries
:returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList
:rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList
"""
if self._feedback_summaries is None:
... |
java | protected void aggregateEntry(Entry other, long currentTime,
double negLambda) {
this.data.aggregate(other.data, currentTime - this.timestamp,
negLambda);
this.timestamp = currentTime;
} |
java | public void setElementView(String elementView) {
m_elementView = elementView;
if (LOG.isDebugEnabled()) {
LOG.debug("Setting element view to " + elementView);
}
} |
java | public StringWriter append(CharSequence csq, int start, int end) {
CharSequence cs = (csq == null ? "null" : csq);
write(cs.subSequence(start, end).toString());
return this;
} |
java | @Override
public ElementOperator<PlainTime> newValue(V value) {
return new TimeOperator(this, ElementOperator.OP_NEW_VALUE, value);
} |
java | public Observable<Page<JobInner>> listByAgentNextAsync(final String nextPageLink) {
return listByAgentNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<JobInner>>, Page<JobInner>>() {
@Override
public Page<JobInner> call(ServiceResponse<Pa... |
java | public void marshall(CoreDefinitionVersion coreDefinitionVersion, ProtocolMarshaller protocolMarshaller) {
if (coreDefinitionVersion == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(coreDefinitionVe... |
java | private Description checkAnnotations(
Tree tree,
int treePos,
List<? extends AnnotationTree> annotations,
Comment danglingJavadoc,
int firstModifierPos,
int lastModifierPos,
VisitorState state) {
SuggestedFix.Builder builder = SuggestedFix.builder();
List<AnnotationTree... |
python | def update_cached_response(self, request, response):
"""On a 304 we will get a new set of headers that we want to
update our cached value with, assuming we have one.
This should only ever be called when we've sent an ETag and
gotten a 304 as the response.
"""
cache_url =... |
java | public void deattach(JainMgcpListener listener) {
int identifier = -1;
//search identifier of the specified listener
Set<Integer> IDs = txListeners.keySet();
for (Integer id : IDs) {
if (txListeners.get(id) == listener) {
identifier = id;
... |
python | def get_dependencies(self):
"""
Retrieve the set of all dependencies for a given configuration.
Returns:
utils.utils.OrderedSet: The set of all dependencies for the
tracked configuration.
"""
all_deps = OrderedSet()
for key, _ in list(self.__c... |
java | public static SSLContext acceptingSslContext() {
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, TRUST_MANAGERS, new SecureRandom());
return sslContext;
} catch (NoSuchAlgorithmException | KeyManagementException ex) {
th... |
java | public boolean mapLocalToTarget()
{
GVRSkeleton srcskel = mSourceSkeleton;
GVRSkeleton dstskel = mDestSkeleton;
Vector3f v = new Vector3f();
if ((dstskel == null) || (srcskel == null))
{
return false;
}
if (mBoneMap == null)
{
... |
java | @Override
public boolean isReadonly() {
if (isIdProperty() || isVersionProperty()) {
return false;
}
Indexed indexedAnnotation = getIndexAnnotation();
if (indexedAnnotation != null && indexedAnnotation.readonly()) {
return true;
}
if (indexedAnnotation == null && getFieldAnnotation() == null) {
... |
python | def _windcalc(self, first, totalmass, nsteps, niso, ypssurf, ypsinit, \
X_i, E_i, cycles):
"""
This function calculates the windyields and ejected masses as called from
windyields(). It uses a summation version of the formulae used in Hirschi
et al. 2005, "Yields of rotating stars a... |
java | protected final UtlInvLine<RS, PurchaseInvoice, PurchaseInvoiceLine,
PurchaseInvoiceTaxLine, PurchaseInvoiceGoodsTaxLine> lazyGetUtlPurGdLn(
final Map<String, Object> pAddParam) throws Exception {
UtlInvLine<RS, PurchaseInvoice, PurchaseInvoiceLine,
PurchaseInvoiceTaxLine, PurchaseInvoiceGoodsTaxLin... |
java | public boolean parse(String criteria, Map<String, ? extends Object> attributes) throws CriteriaParseException {
if (criteria == null) {
return true;
} else {
try {
return Boolean.parseBoolean(FREEMARKER_BUILTINS.eval(criteria, attributes));
} catch (Te... |
java | public static String getRelPath(String siblings, String resourceId)
{
String relResourceId = null;
if (resourceId != null && resourceId.length() != 0)
{
char cs = resourceId.charAt(0);
if (!(cs == '\\' || cs == '/'))
{
//相对路径
int i = siblings.length() - 1;
boolean find = false;
... |
java | public GlobalizationPreferences setCollator(Collator collator) {
if (isFrozen()) {
throw new UnsupportedOperationException("Attempt to modify immutable object");
}
try {
this.collator = (Collator) collator.clone(); // clone for safety
} catch (CloneNotSupportedExc... |
java | @CanIgnoreReturnValue
@GwtIncompatible // TODO
public static <V> V getUninterruptibly(Future<V> future, long timeout, TimeUnit unit)
throws ExecutionException, TimeoutException {
boolean interrupted = false;
try {
long remainingNanos = unit.toNanos(timeout);
long end = System.nanoTime() + ... |
java | @Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case SimpleAntlrPackage.AND_EXPRESSION__LEFT:
return basicSetLeft(null, msgs);
case SimpleAntlrPackage.AND_EXPRESSION__RIGHT:
return basicSetR... |
java | public static Field[] getFieldArrayIncludeSupClassExcludeUID(Class<?> clazz) {
Field[] currField = clazz.getDeclaredFields();
clazz = clazz.getSuperclass();
Field[] supField = clazz.getDeclaredFields();
Field[] temp = new Field[currField.length + supField.length];
int length = 0;... |
java | public static Predicate<RequestHandler> withMethodAnnotation(final Class<? extends Annotation> annotation) {
return input -> input.isAnnotatedWith(annotation);
} |
java | static Stream<Attribute> getTableAttributes(EntityType entityType) {
return getPersistedAttributes(entityType).filter(PostgreSqlQueryUtils::isTableAttribute);
} |
java | public static boolean startsWithAny(String string, String[] searchStrings) {
if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {
return false;
}
for (int i = 0; i < searchStrings.length; i++) {
String searchString = searchStrings[i];
if (StringUtils.st... |
python | def replace_by_etree(self, root_el, el_idx=0):
"""Replace element.
Select element that has the same name as ``root_el``, then replace the selected
element with ``root_el``
``root_el`` can be a single element or the root of an element tree.
Args:
root_el : element
... |
java | public Observable<ServiceResponse<RegistryPoliciesInner>> beginUpdatePoliciesWithServiceResponseAsync(String resourceGroupName, String registryName, RegistryPoliciesInner registryPoliciesUpdateParameters) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter thi... |
python | def logs(channel):
"Where can one find the logs?"
default_url = 'http://' + socket.getfqdn()
base = pmxbot.config.get('logs URL', default_url)
logged_channel = channel in pmxbot.config.log_channels
path = '/channel/' + channel.lstrip('#') if logged_channel else '/'
return urllib.parse.urljoin(base, path) |
python | def flexifunction_directory_ack_encode(self, target_system, target_component, directory_type, start_index, count, result):
'''
Acknowldge sucess or failure of a flexifunction command
target_system : System ID (uint8_t)
target_component ... |
java | @Override
public void setClassProperties(final String name, final Map<String, String[]> properties) throws DevFailed {
cache.setClassProperties(name, properties);
} |
java | public synchronized VNFPackageAgent getVNFPackageAgent() {
if (this.vnfPackageAgent == null) {
if (isService) {
this.vnfPackageAgent =
new VNFPackageAgent(
this.serviceName,
this.projectId,
this.sslEnabled,
this.nfvoIp,
... |
python | def init_queue():
"""Initialize indexing queue."""
def action(queue):
queue.declare()
click.secho('Indexing queue has been initialized.', fg='green')
return queue
return action |
java | public com.google.api.ads.adwords.axis.v201809.cm.DateRange getDateRange() {
return dateRange;
} |
java | private Object getDestination(Object value,
Class<?> type,
String destinationType,
AtomicServiceReference<AdminObjectService> destinationRef,
@Sensitive Map<String, Object> activationP... |
java | @Override
public synchronized void run() {
try {
long start = System.nanoTime();
createRequiredCollaborators();
if (reg == null) {
BundleContext context = config.getBundleContext();
if (context != null) {
reg = context.... |
python | def _BuildEventData(self, record):
"""Builds an FseventsdData object from a parsed structure.
Args:
record (dls_record_v1|dls_record_v2): parsed record structure.
Returns:
FseventsdEventData: event data attribute container.
"""
event_data = FseventsdEventData()
event_data.path = re... |
python | def lookup_blob(hash_value):
"""
Combines all given arguments to create clean title-tags values.
All arguments are divided by a " " seperator and HTML tags
are to be removed.
"""
try:
blob = BlobStorage.objects.get(sha256=hash_value)
except:
return "Blob not found"
return... |
python | def _pad_bytes(request_bytes):
"""
:type request_bytes: bytes
:rtype: bytes
"""
padding_length = (_BLOCK_SIZE - len(request_bytes) % _BLOCK_SIZE)
padding_character = bytes(bytearray([padding_length]))
return request_bytes + padding_character * padding_length |
python | def get_namespaced_custom_object(self, group, version, namespace, plural, name, **kwargs):
"""
Returns a namespace scoped custom object
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_n... |
java | @Override
public Result authenticate(HttpExchange httpExchange) {
Result result = null;
for (Authenticator a : authenticators) {
result = a.authenticate(httpExchange);
if ((result instanceof Success && mode == Mode.ANY) ||
(!(result instanceof Success) && mode... |
java | public void identity_group_group_PUT(String group, String description, OvhRoleEnum role) throws IOException {
String qPath = "/me/identity/group/{group}";
StringBuilder sb = path(qPath, group);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "description", description);
addBody(o, "role",... |
python | def _index_to_row_col(lines, index):
r"""
>>> lines = ['hello\n', 'world\n']
>>> _index_to_row_col(lines, 0)
(0, 0)
>>> _index_to_row_col(lines, 7)
(1, 1)
"""
if index < 0:
raise IndexError('negative index')
current_index = 0
for line_number, line in enumerate(lines):
... |
java | @Override
protected TermsByQueryResponse newResponse(TermsByQueryRequest request, AtomicReferenceArray shardsResponses, ClusterState clusterState) {
int successfulShards = 0;
int failedShards = 0;
int numTerms = 0;
TermsSet[] termsSets = new TermsSet[shardsResponses.length()];
List<ShardOperationF... |
python | def resource_op_defaults_to(name, op_default, value, extra_args=None, cibname=None):
'''
Ensure a resource operation default in the cluster is set to a given value
Should be run on one cluster node only
(there may be races)
Can only be run on a node with a functional pacemaker/corosync
name
... |
python | def _find_install_targets(name=None,
version=None,
pkgs=None,
sources=None,
skip_suggestions=False,
pkg_verify=False,
normalize=True,
igno... |
python | def eventloop(cls, custom_actions=[]):
"""
For use outside of iteration wrapping. Makes an interactive event loop
custom_actions should be specified in format
[dispname, keys, desc, func]
"""
iiter = cls([None], custom_actions=custom_actions, verbose=False)
print(... |
python | def email(self, comment, content_object, request):
"""
Overwritten for a better email notification.
"""
if not self.email_notification:
return
send_comment_posted(comment, request) |
java | protected void updateApiVersion(KubernetesResourceList list) {
String version = getApiVersion();
if (list != null && version != null && version.length() > 0) {
List items = list.getItems();
if (items != null) {
for (Object item : items) {
if (item instanceof HasMetadata) {
... |
python | def get_config_h_filename():
"""Return the path of pyconfig.h."""
if _PYTHON_BUILD:
if os.name == "nt":
inc_dir = os.path.join(_PROJECT_BASE, "PC")
else:
inc_dir = _PROJECT_BASE
else:
inc_dir = get_path('platinclude')
return os.path.join(inc_dir, 'pyconfig... |
java | void createImpl() throws SocketException {
if (impl == null)
setImpl();
try {
impl.create(true);
created = true;
} catch (IOException e) {
throw new SocketException(e.getMessage());
}
} |
java | protected SITransaction getTransaction() throws ResourceException
{
final String methodName = "getTransaction";
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled())
{
SibTr.entry(this, TRACE, methodName);
}
final SITransaction transaction = getXaRe... |
python | def _read_routes_c_v1():
"""Retrieve Windows routes through a GetIpForwardTable call.
This is compatible with XP but won't get IPv6 routes."""
def _extract_ip(obj):
return inet_ntop(socket.AF_INET, struct.pack("<I", obj))
routes = []
for route in GetIpForwardTable():
ifIndex = route... |
python | def flags(self, index):
""" Returns the item flags for the given index.
"""
if not index.isValid():
return QtCore.Qt.NoItemFlags
item = index.internalPointer()
# return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable |
# QtCore.Qt.ItemIsDragEnabled
... |
python | def merge_configs(to_be_merged, default):
"""Merges two configuration dictionaries by overwriting values with
same keys, with the priority on values given on the 'left' side, so
the to_be_merged dict.
Notice that with lists in the configuration, it skips from the default
(right side) the tuples in t... |
python | def _safe_processing(nsafefn, source, _globals=None, _locals=None):
"""Do a safe processing of input fn in using SAFE_BUILTINS.
:param fn: function to call with input parameters.
:param source: source object to process with fn.
:param dict _globals: global objects by name.
:param dict _locals: loca... |
java | private static BannerUpdate parseNextBannerUpdate(Element element) {
BannerUpdate bannerUpdate = new BannerUpdate();
bannerUpdate.setSeasonNum(DOMHelper.getValueFromElement(element, "SeasonNum"));
bannerUpdate.setSeriesId(DOMHelper.getValueFromElement(element, SERIES));
bannerUpdate.set... |
python | def ctox(arguments, toxinidir):
"""Sets up conda environments, and sets up and runs each environment based
on the project's tox.ini configuration file.
Returns 1 if either the build or running the commands failed or 0 if
all commmands ran successfully.
"""
if arguments is None:
argumen... |
python | def create_fork(self, organization=None):
"""Create a fork of this repository.
:param str organization: (required), login for organization to create
the fork under
:returns: :class:`Repository <Repository>` if successful, else None
"""
url = self._build_url('forks', ... |
java | public int getFeaturePosition(AbstractFeature feature) {
AbstractFeature result = feature;
if (!featurePositions.containsKey(feature)) {
if (feature instanceof FeatureGroup) {
FeatureGroup featureGroup = (FeatureGroup) feature;
List<Feature> features = feature... |
python | def config_options(self):
"""
Generate a Trailets Config instance for shell widgets using our
config system
This lets us create each widget with its own config
"""
# ---- Jupyter config ----
try:
full_cfg = load_pyconfig_files(['jupyter_qtcon... |
java | private static PersistenceUnitMetadata parsePersistenceUnit(final URL url, final String[] persistenceUnits,
Element top, final String versionName)
{
PersistenceUnitMetadata metadata = new PersistenceUnitMetadata(versionName, getPersistenceRootUrl(url), url);
String puName = top.get... |
python | def create_default_layout(app, message='',
lexer=None, is_password=False,
reserve_space_for_menu=False,
get_prompt_tokens=None,
get_bottom_toolbar_tokens=None,
display_completions_in_columns... |
python | def tokenize(text):
"""
Yield tokens.
Args:
text (str): The original text.
Yields:
dict: The next token.
"""
stem = PorterStemmer().stem
tokens = re.finditer('[a-z]+', text.lower())
for offset, match in enumerate(tokens):
# Get the raw token.
unstemm... |
java | @Override
protected SoyValue visitFunctionNode(FunctionNode node) {
Object soyFunction = node.getSoyFunction();
// Handle nonplugin functions.
if (soyFunction instanceof BuiltinFunction) {
BuiltinFunction nonpluginFn = (BuiltinFunction) soyFunction;
switch (nonpluginFn) {
case IS_FIRST... |
java | public ResultList<Collection> searchCollection(String query, Integer page, String language) throws MovieDbException {
return tmdbSearch.searchCollection(query, page, language);
} |
python | def com_google_fonts_check_name_subfamilyname(ttFont,
style_with_spaces,
familyname_with_spaces):
""" Check name table: FONT_SUBFAMILY_NAME entries. """
from fontbakery.utils import name_entry_id
failed = False
for name... |
python | def handle_packet(self, packet):
"""Process incoming packet dict and optionally call callback."""
if self.packet_callback:
# forward to callback
self.packet_callback(packet)
else:
print('packet', packet) |
java | public String convertLineDataObjectPositionMigrationTempOrientToString(EDataType eDataType, Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
} |
java | private void installModules(final Node node, final NetworkContext context, final Handler<AsyncResult<Void>> doneHandler) {
List<ModuleContext> modules = new ArrayList<>();
for (ComponentContext<?> component : context.components()) {
if (component.isModule()) {
modules.add(component.asModule());
... |
python | def get_height(self, points, edge=True, attach=False, extra_height=0):
"""
Launch ``pyny.Place.get_height(points)`` recursively for all
the ``pyny.Place``.
The points outside the object will have a NaN value in the
z column. These point will not be stored but it w... |
java | public Response uncheckout(Session session, String path)
{
try
{
Node node = session.getRootNode().getNode(TextUtil.relativizePath(path));
Version restoreVersion = node.getBaseVersion();
node.restore(restoreVersion, true);
return Response.ok().header(HttpH... |
java | @Override
protected void paintComponent(Graphics g) {
if (!isInitialized()) {
return;
}
super.paintComponent(g);
final Graphics2D G2 = (Graphics2D) g.create();
G2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
G2.se... |
java | void writeEntryId(Object entity) throws XMLStreamException, ODataEdmException {
xmlWriter.writeStartElement(ATOM_ID);
xmlWriter.writeCharacters(getEntryIdString(entity));
xmlWriter.writeEndElement();
} |
java | public Double hincrByFloat(Object key, Object field, double value) {
Jedis jedis = getJedis();
try {
return jedis.hincrByFloat(keyToBytes(key), fieldToBytes(field), value);
}
finally {close(jedis);}
} |
java | @SuppressWarnings("unchecked")
public T createView(final Connection _con,
final String _view)
throws SQLException
{
final Statement stmt = _con.createStatement();
try {
stmt.executeUpdate(new StringBuilder().append("create view ").append(_view)
... |
python | def get_datanode_fp_meta(fp):
"""Processes a datanode style file path.
Section 3.2 of the `Data Reference Syntax`_ details:
It is recommended that ESGF data nodes should layout datasets
on disk mapping DRS components to directories as:
<activity>/<product>/<institute>/<model>/<exp... |
java | public static MonomerStore getMonomerStore(Element rootElement)
throws MonomerException, IOException {
MonomerStore monomerStore = new MonomerStore();
Element monomerListElement = rootElement.getChild("Monomers");
if (monomerListElement != null) {
@SuppressWarnings("unchecked")
List<... |
python | def generate_salt_cmd(target, module, args=None, kwargs=None):
"""
Generates a command (the arguments) for the `salt` or `salt-ssh` CLI
"""
args = args or []
kwargs = kwargs or {}
target = target or '*'
target = '"%s"' % target
cmd = [target, module]
for arg in args:
cmd.appe... |
java | private void writeUnixCleanup(File file, BufferedWriter bw) throws IOException {
bw.write("echo begin delete" + "\n");
bw.write("n=0" + "\n");
bw.write("while [ $n -ne 1 ]; do" + "\n");
bw.write(" sleep 3" + "\n");
bw.write(" if [ -e " + dir.replace('\\', '/') + " ]; then" + "\... |
java | @Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case AfplibPackage.OBJECT_CONTAINER_PRESENTATION_SPACE_SIZE__PDF_SIZE:
return getPDFSize();
}
return super.eGet(featureID, resolve, coreType);
} |
java | protected boolean activityAlreadyContainsJobDeclarationEventType(List<EventSubscriptionJobDeclaration> jobDeclarationsForActivity,
EventSubscriptionJobDeclaration jobDeclaration){
for(EventSubscriptionJobDeclaration declaration: jobDeclarationsForAc... |
java | @NonNull
public TransitionSet setOrdering(int ordering) {
switch (ordering) {
case ORDERING_SEQUENTIAL:
mPlayTogether = false;
break;
case ORDERING_TOGETHER:
mPlayTogether = true;
break;
default:
... |
java | public String getProxyRemoteAddr(String realIpHeader) {
String ip = null;
if (realIpHeader != null && realIpHeader.length() != 0) {
ip = getHeaderString(realIpHeader);
}
if (StringUtils.isBlank(ip)) {
ip = getHeaderString("X-Real-IP");
if (StringUtils.... |
java | public TeeOutputStream with(OutputStream stream, boolean autoclose) {
if(stream != null) {
this.streams.put(stream, autoclose);
}
return this;
} |
python | def axes_grid(n, sharex=False, sharey=False, subplot_kw=None, **fig_kw):
'''Finds a reasonable arrangement of n axes. Returns (fig, axes) tuple.
For keyword arguments descriptions, see matplotlib.pyplot.subplots'''
r = np.floor(np.sqrt(n))
r, c = int(r), int(np.ceil(n / r))
fig, axes = plt.subplots(nrows=r, n... |
python | def subtract_imagenet_mean_preprocess_batch(batch):
"""Subtract ImageNet mean pixel-wise from a BGR image."""
batch = F.swapaxes(batch,0, 1)
(r, g, b) = F.split(batch, num_outputs=3, axis=0)
r = r - 123.680
g = g - 116.779
b = b - 103.939
batch = F.concat(b, g, r, dim=0)
batch = F.swapax... |
java | public PagedList<CloudTask> list(final String jobId) {
ServiceResponseWithHeaders<Page<CloudTask>, TaskListHeaders> response = listSinglePageAsync(jobId).toBlocking().single();
return new PagedList<CloudTask>(response.body()) {
@Override
public Page<CloudTask> nextPage(String nex... |
java | JCExpression retype(JCExpression tree, Type erasedType, Type target) {
// System.err.println("retype " + tree + " to " + erasedType);//DEBUG
if (!erasedType.isPrimitive()) {
if (target != null && target.isPrimitive()) {
target = erasure(tree.type);
}
tree... |
python | def reset_awards(**kwargs):
"""
Resets badges stats.
"""
filter_badges = kwargs.get('badges', None)
exclude_badges = kwargs.get('exclude_badges', None)
for option in [filter_badges, exclude_badges]:
if option:
if not isinstance(option, (list, tuple)):
option ... |
java | public synchronized List<KafkaDependencyInstanceContext> getDepsByTopicAndEvent(final String topic,
final String regex) {
final Map<String, List<KafkaDependencyInstanceContext>> regexMap = this.topicEventMap.get(topic);
if (regexMap != null) {
return regexMap.get(regex);
}
return Collections... |
java | @Nullable
public static ExpressionTree getArgument(AnnotationTree annotationTree, String name) {
for (ExpressionTree argumentTree : annotationTree.getArguments()) {
if (argumentTree.getKind() != Tree.Kind.ASSIGNMENT) {
continue;
}
AssignmentTree assignmentTree = (AssignmentTree) argument... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.