language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | private static Type[] getImplicitBounds(final TypeVariable<?> typeVariable) {
Assert.requireNonNull(typeVariable, "typeVariable");
final Type[] bounds = typeVariable.getBounds();
return bounds.length == 0 ? new Type[]{Object.class} : normalizeUpperBounds(bounds);
} |
java | public static JsonValue parse(Reader reader) throws IOException {
if (reader == null) {
throw new NullPointerException(READER_IS_NULL);
}
DefaultHandler handler = new DefaultHandler();
new JsonParser(handler).parse(reader);
return handler.getValue();
} |
python | def get_kinto_records(kinto_client, bucket, collection, permissions,
config=None):
"""Return all the kinto records for this bucket/collection."""
# Create bucket if needed
try:
kinto_client.create_bucket(id=bucket, if_not_exists=True)
except KintoException as e:
if ... |
java | @Override
public void registerStatsStorageListener(StatsStorageListener listener) {
if (!this.listeners.contains(listener)) {
this.listeners.add(listener);
}
} |
java | @NotNull public static <T> Observable<Response<T>> from(@NotNull final ApolloCall<T> call) {
checkNotNull(call, "call == null");
return Observable.create(new ObservableOnSubscribe<Response<T>>() {
@Override public void subscribe(final ObservableEmitter<Response<T>> emitter) throws Exception {
can... |
python | def get(self):
"""Get options."""
opts = current_app.config['RECORDS_REST_SORT_OPTIONS'].get(
self.search_index)
sort_fields = []
if opts:
for key, item in sorted(opts.items(), key=lambda x: x[1]['order']):
sort_fields.append(
... |
java | public boolean exitsMongoDbDataBase(String dataBaseName) {
List<String> dataBaseList = mongoClient.getDatabaseNames();
return dataBaseList.contains(dataBaseName);
} |
python | def decrement(self, key, value=1):
"""
Decrement the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The decrement value
:type value: int
:rtype: int or bool
"""
return self._memcache.decr(self._prefix + key... |
java | private void provideDefaultReturnType() {
if (contents.getSourceNode() != null && contents.getSourceNode().isAsyncGeneratorFunction()) {
// Set the return type of a generator function to:
// @return {!AsyncGenerator<?>}
ObjectType generatorType = typeRegistry.getNativeObjectType(ASYNC_GENERATOR_... |
java | public IndexBrowser browse(Query params) throws AlgoliaException {
return new IndexBrowser(client, encodedIndexName, params, null, RequestOptions.empty);
} |
java | @Override
public Request<CreateTransitGatewayVpcAttachmentRequest> getDryRunRequest() {
Request<CreateTransitGatewayVpcAttachmentRequest> request = new CreateTransitGatewayVpcAttachmentRequestMarshaller().marshall(this);
request.addParameter("DryRun", Boolean.toString(true));
return request;... |
java | public static systemcore[] get(nitro_service service, systemcore_args args) throws Exception{
systemcore obj = new systemcore();
options option = new options();
option.set_args(nitro_util.object_to_string_withoutquotes(args));
systemcore[] response = (systemcore[])obj.get_resources(service, option);
return re... |
python | def serialize_smarttag(ctx, document, el, root):
"Serializes smarttag."
if ctx.options['smarttag_span']:
_span = etree.SubElement(root, 'span', {'class': 'smarttag', 'data-smarttag-element': el.element})
else:
_span = root
for elem in el.elements:
_ser = ctx.get_serializer(elem... |
python | def uuid(self):
'''Universally unique identifier for an instance of a :class:`Model`.
'''
pk = self.pkvalue()
if not pk:
raise self.DoesNotExist(
'Object not saved. Cannot obtain universally unique id')
return self.get_uuid(pk) |
java | private void handleServerTextChannel(JsonNode jsonChannel) {
long channelId = jsonChannel.get("id").asLong();
api.getTextChannelById(channelId).map(c -> ((ServerTextChannelImpl) c)).ifPresent(channel -> {
String oldTopic = channel.getTopic();
String newTopic = jsonChannel.has("to... |
java | private void cacheFormatCodes()
{
CTNumFmts numFmts = stylesheet.getNumFmts();
if(numFmts != null)
{
List list = numFmts.getNumFmt();
for(int i = 0; i < list.size(); i++)
addFormatCode((CTNumFmt)list.get(i));
}
}
/**
* Creates a n... |
java | public Future<ChangeMessageVisibilityResult> changeMessageVisibility(ChangeMessageVisibilityRequest request,
AsyncHandler<ChangeMessageVisibilityRequest, ChangeMessageVisibilityResult> handler) {
QueueBufferCallback<ChangeMessageVisibilityRequest, ChangeMessageVis... |
python | def metadata(self, delete=False):
"""
Gets the metadata.
"""
if delete:
return self._session.delete(self.__v1() + "/metadata").json()
else:
return self._session.get(self.__v1() + "/metadata").json() |
python | def parse_verbosity(self, args):
'''parse_verbosity will take an argument object, and return the args
passed (from a dictionary) to a list
Parameters
==========
args: the argparse argument objects
'''
flags = []
if args.silent is True:
flags.append('--silent')
... |
java | @SuppressWarnings("unchecked")
D minusYears(long yearsToSubtract) {
return (yearsToSubtract == Long.MIN_VALUE ? ((ChronoLocalDateImpl<D>)plusYears(Long.MAX_VALUE)).plusYears(1) : plusYears(-yearsToSubtract));
} |
java | private FileStatus createFileStatus(StoredObject tmp, Container cObj,
String hostName, Path path) throws IllegalArgumentException, IOException {
String newMergedPath = getMergedPath(hostName, path, tmp.getName());
return new FileStatus(tmp.getContentLength(), false, 1, blockSize,
Utils.lastModifie... |
java | public void marshall(Diagnostics diagnostics, ProtocolMarshaller protocolMarshaller) {
if (diagnostics == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(diagnostics.getErrorCode(), ERRORCODE_BINDING)... |
python | def move_to(self, position):
"""Set the Coordinator to a specific endpoint or time, or load state from a token.
:param position: "trim_horizon", "latest", :class:`~datetime.datetime`, or a
:attr:`Coordinator.token <bloop.stream.coordinator.Coordinator.token>`
"""
if isinstan... |
java | public Iterator<Runnable> buildIterator() {
return new Iterator<Runnable>() {
@Override
public boolean hasNext() {
return false;
}
@Override
public Runnable next() {
return null;
}
@Override
public void remove() {
}
};
} |
python | def is_running(self):
"""Check if ZAP is running."""
try:
result = requests.get(self.proxy_url)
except RequestException:
return False
if 'ZAP-Header' in result.headers.get('Access-Control-Allow-Headers', []):
return True
raise ZAPError('Anoth... |
java | public static Document parseEscapedXmlString(String input) throws UnmarshalException {
String deEscapedXml = deEscapeXml(input);
return parseXmlString(deEscapedXml);
} |
python | def payload(self):
"""
Picks out the payload from the different parts of the signed/encrypted
JSON Web Token. If the content type is said to be 'jwt' deserialize the
payload into a Python object otherwise return as-is.
:return: The payload
"""
_msg = as_unicode(s... |
python | def get_result(self):
"""
Returns an http response object.
"""
timeout = 60
if self.method == "GET":
timeout = 360
headers = {
"Authorization": "Bearer " + self.key,
"content-type": "application/json"
}
response = None... |
python | def make_template_paths(template_file, paths=None):
"""
Make up a list of template search paths from given 'template_file'
(absolute or relative path to the template file) and/or 'paths' (a list of
template search paths given by user).
NOTE: User-given 'paths' will take higher priority over a dir o... |
java | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public void setCompoundDrawablesRelative (Drawable start, Drawable top, Drawable end, Drawable bottom){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
mInputView.setCompoundDrawablesRelative(start, top, end, bottom);
else
mInputView.setCompoundD... |
java | public static Hours from(TemporalAmount amount) {
if (amount instanceof Hours) {
return (Hours) amount;
}
Objects.requireNonNull(amount, "amount");
int hours = 0;
for (TemporalUnit unit : amount.getUnits()) {
long value = amount.get(unit);
if (... |
python | def combinatorics(self):
"""
Returns mutually exclusive/inclusive mappings
Returns
-------
(dict,dict)
A tuple of 2 dictionaries.
For each mapping key, the first dict has as value the set of mutually exclusive mappings while
the second dict ha... |
python | def _close_writable(self):
"""
Close the object in write mode.
"""
# Wait parts upload completion
for part in self._write_futures:
part['ETag'] = part.pop('response').result()['ETag']
# Complete multipart upload
with _handle_client_error():
... |
java | public java.util.List<InstanceCapacity> getAvailableInstanceCapacity() {
if (availableInstanceCapacity == null) {
availableInstanceCapacity = new com.amazonaws.internal.SdkInternalList<InstanceCapacity>();
}
return availableInstanceCapacity;
} |
java | public static Interval[][] calculateTemporalDistance( Interval[][] constraintMatrix ) {
Interval[][] result = new Interval[constraintMatrix.length][];
for( int i = 0; i < result.length; i++ ) {
result[i] = new Interval[constraintMatrix[i].length];
for( int j = 0; j < result[i].le... |
python | def GetEntries(self, parser_mediator, top_level=None, **unused_kwargs):
"""Simple method to exact date values from a Plist.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
top_level (dict[str, object]): plist t... |
python | def prune_empty_node(node, seen):
"""
Recursively remove empty branches and return whether this makes the node
itself empty.
The ``seen`` parameter is used to avoid infinite recursion due to cycles
(you never know).
"""
if node.methods:
return False
if id(node) in seen:
... |
java | protected void addItemView(View itemView, int childIndex) {
final ViewGroup currentParent = (ViewGroup) itemView.getParent();
if (currentParent != null) {
currentParent.removeView(itemView);
}
((ViewGroup) mMenuView).addView(itemView, childIndex);
} |
python | def freq_filt(bma):
"""
This is a framework for 2D FFT filtering. It has not be tested or finished - might be a dead end
See separate utility freq_analysis.py
"""
"""
Want to fit linear function to artifact line in freq space,
Then mask everything near that line at distances of ~5-200 pixel... |
python | def _pad_block(self, handle):
'''Pad the file with 0s to the end of the next block boundary.'''
extra = handle.tell() % 512
if extra:
handle.write(b'\x00' * (512 - extra)) |
java | public static long parseJsonValueToLong(JsonValue value) {
try {
return value.asLong();
} catch (UnsupportedOperationException e) {
String s = value.asString().replace("\"", "");
return Long.parseLong(s);
}
} |
python | def normalize_fieldsets(fieldsets):
"""
Make sure the keys in fieldset dictionaries are strings. Returns the
normalized data.
"""
result = []
for name, options in fieldsets:
result.append((name, normalize_dictionary(options)))
return result |
python | def update_service_definitions(self, service_definitions):
"""UpdateServiceDefinitions.
[Preview API]
:param :class:`<VssJsonCollectionWrapper> <azure.devops.v5_0.location.models.VssJsonCollectionWrapper>` service_definitions:
"""
content = self._serialize.body(service_definition... |
python | def rr_absent(name, HostedZoneId=None, DomainName=None, PrivateZone=False,
Name=None, Type=None, SetIdentifier=None,
region=None, key=None, keyid=None, profile=None):
'''
Ensure the Route53 record is deleted.
name
The name of the state definition. This will be used for ... |
java | @Override
public final T process(final Map<String, Object> pReqVars,
final T pEntity, final IRequestData pRequestData) throws Exception {
SeSeller ses = findSeSeller.find(pReqVars, pRequestData.getUserName());
pEntity.setSeller(ses);
if (pEntity.getIsNew()) {
this.srvOrm.insertEntity(pReqVars, p... |
python | def _generate_struct_class_properties(self, ns, data_type):
"""
Each field of the struct has a corresponding setter and getter.
The setter validates the value being set.
"""
for field in data_type.fields:
field_name = fmt_func(field.name)
field_name_reserv... |
python | def potcar_spec( filename ):
"""
Returns a dictionary specifying the pseudopotentials contained in a POTCAR file.
Args:
filename (Str): The name of the POTCAR file to process.
Returns:
(Dict): A dictionary of pseudopotential filename: dataset pairs, e.g.
{ 'Fe_pv': 'PBE... |
python | def get_registered_layer(name):
"""
Args:
name (str): the name of the layer, e.g. 'Conv2D'
Returns:
the wrapped layer function, or None if not registered.
"""
ret = _LAYER_REGISTRY.get(name, None)
if ret == _NameConflict:
raise KeyError("Layer named '{}' is registered wit... |
java | public JNDIContentRepositoryBuilder withContextProperty(final String name, final Object value) {
contextProperties.put(name, value);
return this;
} |
java | public static List<RoboconfCompletionProposal> buildProposalsFromMap( Map<String,String> candidates, String prefix ) {
List<RoboconfCompletionProposal> result = new ArrayList<> ();
for( Map.Entry<String,String> entry : candidates.entrySet()) {
// Matching candidate?
String candidate = entry.getKey();
if(... |
python | def findHomography(self, img, drawMatches=False):
'''
Find homography of the image through pattern
comparison with the base image
'''
print("\t Finding points...")
# Find points in the next frame
img = self._prepareImage(img)
features, descs = self... |
java | void processAckExpected(
long ackExpStamp,
int priority,
Reliability reliability,
SIBUuid12 stream)
throws SIResourceException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "processAckExpected", new Long(ackExpStamp));
_internalOutputStreamManager... |
python | def load_result_json(result_path, json_file_name):
"""load_result_json."""
json_path = os.path.join(result_path, json_file_name)
_list = []
if os.path.isfile(json_path):
with open(json_path) as json_data:
try:
_list = json.load(json_data)
except ValueErro... |
python | def transformer_ada_lmpackedbase_dialog():
"""Set of hyperparameters."""
hparams = transformer_base_vq_ada_32ex_packed()
hparams.max_length = 1024
hparams.ffn_layer = "dense_relu_dense"
hparams.batch_size = 4096
return hparams |
python | def selectis(table, field, value, complement=False):
"""Select rows where the given field `is` the given value."""
return selectop(table, field, value, operator.is_, complement=complement) |
python | def initialize_CART_rot(self, s):
"""
Sets current specimen to s and calculates the data necessary to plot
the specimen plots (zijderveld, specimen eqarea, M/M0)
Parameters
----------
s: specimen to set as the GUI's current specimen
"""
self.s = s # only... |
python | def guess_formatter(values, precision=1, commas=True, parens=True, nan='nan', prefix=None, pcts=0,
trunc_dot_zeros=0):
"""Based on the values, return the most suitable formatter
Parameters
----------
values : Series, DataFrame, scalar, list, tuple, or ndarray
Values used... |
java | public static Collection<Class<?>> getInterfaces(Class<?> object, Class<?> base)
{
Check.notNull(object);
Check.notNull(base);
final Collection<Class<?>> interfaces = new ArrayList<>();
Class<?> current = object;
while (current != null)
{
final D... |
python | def center(self) -> Location:
"""
:return: a Point corresponding to the absolute position of the center
of the well relative to the deck (with the front-left corner of slot 1
as (0,0,0))
"""
top = self.top()
center_z = top.point.z - (self._depth / 2.0)
ret... |
java | protected void fireSourceUpdated(S e) {
for (int i = 0, n = this.listenerList.size(); i < n; i++) {
this.listenerList.get(i).sourceUpdated(e);
}
} |
java | public DescribeConfigurationRecordersResult withConfigurationRecorders(ConfigurationRecorder... configurationRecorders) {
if (this.configurationRecorders == null) {
setConfigurationRecorders(new com.amazonaws.internal.SdkInternalList<ConfigurationRecorder>(configurationRecorders.length));
}
... |
java | public static String put(String url, Map<String, String> body) {
return put(url, JSONObject.toJSONString(body));
} |
python | def bus_line_names(self):
"""Append bus injection and line flow names to `varname`"""
if self.system.tds.config.compute_flows:
self.system.Bus._varname_inj()
self.system.Line._varname_flow()
self.system.Area._varname_inter() |
python | def swipe_bottom(self, steps=10, *args, **selectors):
"""
Swipe the UI object with *selectors* from center to bottom
See `Swipe Left` for more details.
"""
self.device(**selectors).swipe.down(steps=steps) |
python | def _set_support(self, v, load=False):
"""
Setter method for support, mapped from YANG variable /support (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_support is considered as a private
method. Backends looking to populate this variable should
do so... |
java | public boolean anyMatch(@NotNull IntPredicate predicate) {
while(iterator.hasNext()) {
if(predicate.test(iterator.nextInt()))
return true;
}
return false;
} |
java | @Override
public String getSignature(String baseString, String apiSecret, String tokenSecret) {
try {
Preconditions.checkEmptyString(apiSecret, "Api secret cant be null or empty string");
return OAuthEncoder.encode(apiSecret) + '&' + OAuthEncoder.encode(tokenSecret);
} catch ... |
java | private static void writeZonePropsByDOW_LEQ_DOM(Writer writer, boolean isDst, String tzname, int fromOffset, int toOffset,
int month, int dayOfMonth, int dayOfWeek, long startTime, long untilTime) throws IOException {
// Check if this rule can be converted to DOW rule
if (dayOfMonth%7 == 0) ... |
java | public void setAnimationType(Type type){
if(type == null)
options.clearProperty(ANIMATION_EASING);
else
options.setProperty(ANIMATION_EASING, type.getValue());
} |
python | def load(self, image=None):
'''load an image, either an actual path on the filesystem or a uri.
Parameters
==========
image: the image path or uri to load (e.g., docker://ubuntu
'''
from spython.image import Image
from spython.instance import Instance
self.simage = Image(ima... |
java | @Override
public String query(String contig, int start, int end) throws Exception {
Region region = new Region(contig, start, end);
QueryResult<GenomeSequenceFeature> queryResult
= genomeDBAdaptor.getSequence(region, QueryOptions.empty());
// This behaviour mimics the behav... |
java | private String readLine() throws IOException {
StringBuffer sbuf = new StringBuffer();
int result;
String line;
do {
result = in.readLine(buf, 0, buf.length); // does +=
if (result != -1) {
sbuf.append(new String(buf, 0, result, encoding));
}
} while (result == buf.length... |
java | public void readLed(Callback<LedColor> callback) {
addCallback(BeanMessageID.CC_LED_READ_ALL, callback);
sendMessageWithoutPayload(BeanMessageID.CC_LED_READ_ALL);
} |
python | def execd_submodule_paths(command, execd_dir=None):
"""Generate a list of full paths to the specified command within exec_dir.
"""
for module_path in execd_module_paths(execd_dir):
path = os.path.join(module_path, command)
if os.access(path, os.X_OK) and os.path.isfile(path):
yie... |
python | def get_local_current_sample(ip):
"""Gets current sample from *local* Neurio device IP address.
This is a static method. It doesn't require a token to authenticate.
Note, call get_user_information to determine local Neurio IP addresses.
Args:
ip (string): address of local Neurio device
Ret... |
java | public boolean isWhitelistedAndNotBlacklisted(final WhiteBlackListLeafname jarWhiteBlackList) {
return jarWhiteBlackList.isWhitelistedAndNotBlacklisted(pathWithinParentZipFileSlice) //
&& (parentZipFileSlice == null
|| parentZipFileSlice.isWhitelistedAndNotBlacklisted(jar... |
python | def connection(self):
""" Provide the connection parameters for kombu's ConsumerMixin.
The `Connection` object is a declaration of connection parameters
that is lazily evaluated. It doesn't represent an established
connection to the broker at this point.
"""
heartbeat = ... |
python | def createKMZ(self, kmz_as_json):
"""
Creates a KMZ file from json.
See http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Create_Kmz/02r3000001tm000000/
for more information.
"""
kmlURL = self._url + "/createKmz"
params = {
"f" :... |
java | public static SecurityMetadata getSecurityMetadata() {
SecurityMetadata secMetadata = null;
ModuleMetaData mmd = ComponentMetaDataAccessorImpl.getComponentMetaDataAccessor().getComponentMetaData().getModuleMetaData();
if (mmd instanceof WebModuleMetaData) {
secMetadata = (SecurityMet... |
python | def length(self):
"""Gets the length of the Vector"""
return math.sqrt((self.x * self.x) + (self.y * self.y) + (self.z * self.z) + (self.w * self.w)) |
java | public void updateMainComponent(Component comp) {
comp.setSizeFull();
m_rootLayout.setMainContent(comp);
Map<String, Object> attributes = getAttributesForComponent(comp);
updateAppAttributes(attributes);
} |
java | private void openProxy(CompletableFuture<SessionClient> future) {
log.debug("Opening proxy session");
proxyFactory.get().thenCompose(proxy -> proxy.connect()).whenComplete((proxy, error) -> {
if (error == null) {
synchronized (this) {
this.log = ContextualLoggerFactory.getLogger(getClass... |
python | def set_xticks_for_all(self, row_column_list=None, ticks=None):
"""Manually specify the x-axis tick values.
:param row_column_list: a list containing (row, column) tuples to
specify the subplots, or None to indicate *all* subplots.
:type row_column_list: list or None
:param ... |
python | def set_sampling_strategies(self, filter, strategy_and_parms):
"""Set a strategy for all sensors matching the filter, including unseen sensors
The strategy should persist across sensor disconnect/reconnect.
filter : str
Filter for sensor names
strategy_and_params : seq of st... |
java | public void registerTypeWithKryoSerializer(Class<?> type, Class<? extends Serializer<?>> serializerClass) {
config.registerTypeWithKryoSerializer(type, serializerClass);
} |
java | private void attemptSocketBind(InetSocketAddress address, boolean reuseflag) throws IOException {
this.serverSocket.setReuseAddress(reuseflag);
this.serverSocket.bind(address, this.tcpChannel.getConfig().getListenBacklog());
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
... |
java | @edu.umd.cs.findbugs.annotations.SuppressWarnings({"DM_DEFAULT_ENCODING", "OS_OPEN_STREAM"})
private static void getUlimit(PrintWriter writer) throws IOException {
// TODO should first check whether /bin/bash even exists
InputStream is = new ProcessBuilder("bash", "-c", "ulimit -a").start().getInput... |
python | def inverse(self, encoded, duration=None):
'''Inverse transformation'''
ann = jams.Annotation(namespace=self.namespace, duration=duration)
for start, end, value in self.decode_intervals(encoded,
duration=duration,
... |
java | public TypedQuery<ENTITY> withRowAsyncListener(Function<Row, Row> rowAsyncListener) {
this.options.setRowAsyncListeners(Optional.of(asList(rowAsyncListener)));
return this;
} |
java | public static String cleanParam(String[] strParams, boolean bSetDefault, String strDefault)
{
if ((strParams == null) || (strParams.length == 0))
strParams = new String[1];
if (strParams[0] == null) if (bSetDefault)
strParams[0] = strDefault;
if (strParams[0] == null)... |
python | def download_permanent_media(self, media_id):
"""
获取永久素材。
:param media_id: 媒体文件 ID
:return: requests 的 Response 实例
"""
return requests.post(
url="https://api.weixin.qq.com/cgi-bin/material/get_material",
params={"access_token": self.token},
... |
python | def search(self, jobs: List[Dict[str, str]]) -> None:
"""Perform searches based on job orders."""
if not isinstance(jobs, list):
raise Exception("Jobs must be of type list.")
self._log.info("Project: %s" % self.project)
self._log.info("Processing jobs: %d", len(jobs))
... |
java | public static void copyURLToFile(final URL source, final File destination) throws UncheckedIOException {
InputStream is = null;
try {
is = source.openStream();
write(destination, is);
} catch (IOException e) {
throw new UncheckedIOException(e);
... |
python | def load_weapons(self):
"""|coro|
Load the players weapon stats
Returns
-------
list[:class:`Weapon`]
list of all the weapon objects found"""
data = yield from self.auth.get("https://public-ubiservices.ubi.com/v1/spaces/%s/sandboxes/%s/playerstats2/statistic... |
java | public static void writeObject(CodedOutputStream out, int order, FieldType type, Object o, boolean list,
boolean withTag) throws IOException {
if (o == null) {
return;
}
if (type == FieldType.OBJECT) {
Class cls = o.getClass();
Codec tar... |
java | static <K, V> Map<V, K> invert(Map<K, V> map)
{
Map<V, K> result = new LinkedHashMap<V, K>();
for (Entry<K, V> entry : map.entrySet())
{
result.put(entry.getValue(), entry.getKey());
}
return result;
} |
python | def _find_already_built_wheel(metadata_directory):
"""Check for a wheel already built during the get_wheel_metadata hook.
"""
if not metadata_directory:
return None
metadata_parent = os.path.dirname(metadata_directory)
if not os.path.isfile(pjoin(metadata_parent, WHEEL_BUILT_MARKER)):
... |
python | def execute_notebook(nb_path, pkg_dir, dataframes, write_notebook=False, env=None):
"""
Execute a notebook after adding the prolog and epilog. Can also add %mt_materialize magics to
write dataframes to files
:param nb_path: path to a notebook.
:param pkg_dir: Directory to which dataframes are mater... |
python | def _taskdict(task):
'''
Note: No locking is provided. Under normal circumstances, like the other task is not running (e.g. this is running
from the same event loop as the task) or task is the current task, this is fine.
'''
if task is None:
task = asyncio.current_task()
assert task
... |
java | @Override
public BatchStopJobRunResult batchStopJobRun(BatchStopJobRunRequest request) {
request = beforeClientExecution(request);
return executeBatchStopJobRun(request);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.