language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def upload_files_in_folder(self, dirname, fnames):
"""Handles the iteration across files within a folder."""
if utils.match_pattern(dirname, self.ignore):
return False
good_names = (nm for nm in fnames
if not utils.match_pattern(nm, self.ignore))
for fname in ... |
java | public static void compress(String srcFilePath, String destFilePath) throws Exception {
File src = new File(srcFilePath);
if (!src.exists()) {
throw new RuntimeException(srcFilePath + "不存在");
}
File zipFile = new File(destFilePath);
ZipOutputStream zos=null;
try {
FileOutputStream fos = new Fi... |
java | public static void notNegative(Integer value) {
if(!validation) return;
Validate.notNull(value);
if(value < 0)
throw new ParameterException(ErrorCode.NEGATIVE);
} |
python | def _connect_mitogen_doas(spec):
"""
Return ContextService arguments for doas as a first class connection.
"""
return {
'method': 'doas',
'kwargs': {
'username': spec.remote_user(),
'password': spec.password(),
'python_path': spec.python_path(),
... |
python | def _enclose_readings(container, readings):
"""Enclose a reading within a container, e.g. '[]'."""
container_start, container_end = tuple(container)
enclosed_readings = '%(container_start)s%(readings)s%(container_end)s' % {
'container_start': container_start, 'container_end': container_end,
... |
java | private List<?> loadDataFromXml(String xml, Class<?> cls) {
logger.entering(new Object[] { xml, cls });
Preconditions.checkArgument(cls != null, "Please provide a valid type.");
List<?> returned;
try {
JAXBContext context = JAXBContext.newInstance(Wrapper.class, cls);
... |
java | public static Iterable<String> renderSolutionTable(final List<String> variables,
final Iterable<? extends BindingSet> solutions) {
final List<String> actualVariables;
if (variables != null) {
actualVariables = ImmutableList.copyOf(variables);
} else {
final S... |
python | def fetch(self):
"""
Fetch a FieldValueInstance
:returns: Fetched FieldValueInstance
:rtype: twilio.rest.autopilot.v1.assistant.field_type.field_value.FieldValueInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
sel... |
java | public static void resetCookieValue(HttpServletResponse response, String cookieName) {
Cookie cookie = new Cookie(cookieName, null);
cookie.setMaxAge(0);
response.addCookie(cookie);
} |
java | @Deprecated
public static AsyncSearchQueryResult fromIndexNotFound(final String indexName) {
//dummy default values
SearchStatus status = new DefaultSearchStatus(1L, 1L, 0L);
SearchMetrics metrics = new DefaultSearchMetrics(0L, 0L, 0d);
return new DefaultAsyncSearchQueryResult(
... |
java | private void updateOnlyHeaderBuildDigest(Mac digest) throws IllegalStateException, UnsupportedEncodingException {
digest.update(Validator.notNull(apiKey, "apiKey not null").getBytes(charset));
digest.update(delimiter);
digest.update(Validator.notNull(contentType, "contentType not null").getBytes... |
java | private int findIndexOfUnglobbedPart(String globExpression) {
int result = -1;
for (int i = 0; i < globExpression.length(); i++) {
switch (globExpression.charAt(i)) {
case '/':
case '\\':
result = i;
break;
... |
java | public static ArrayList<String> getSpeechRecognitionResults(int requestCode, int resultCode, Intent data) {
ArrayList<String> matches = null;
if (requestCode == 0 && resultCode == -1) {
matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
StringBuilder sb = new StringBuilder();
for ... |
java | private static void parseAEJava(String line,
IteratorWithPrevious<String> it, Pipeline pipeline)
throws ParseException {
LOG.info("+-parsing line '{}'", line);
Interpreter i = new Interpreter(); // Construct an interpreter
// Eval a statement and get the result
... |
python | def _make_suffix(cov):
"""Create a suffix for nbval data file depending on pytest-cov config."""
# Check if coverage object has data_suffix:
if cov and cov.data_suffix is not None:
# If True, the suffix will be autogenerated by coverage.py.
# The suffixed data files will be automatically com... |
python | def delete(self, uri_pattern, headers=None, parameters=None, **kwargs):
"""
Launch HTTP DELETE request to the API with given arguments
:param uri_pattern: string pattern of the full API url with keyword arguments (format string syntax)
:param headers: HTTP header (dict)
:param pa... |
python | def getDevicesById(self): # , query):
"""
rows = self.camera_collection.get(query)
devices_by_id = {}
for row in rows:
row.pop("classname")
device = DataModel.RTSPCameraDevice(**row)
devices_by_id[device._id] = device
return devices_by_id
... |
python | def get_tempdir():
""" Get the temporary directory where pyelastix stores its temporary
files. The directory is specific to the current process and the
calling thread. Generally, the user does not need this; directories
are automatically cleaned up. Though Elastix log files are also
written here.
... |
python | def read_command(self):
"""
Attempt to read the next command from the editor/server
:return: boolean. Did we actually read a command?
"""
# Do a non-blocking read here so the demo can keep running if there is no data
comm = self.reader.byte(blocking=False)
if comm... |
python | def make_log_record_output(category, level, message,
format=None, datefmt=None, **kwargs):
"""
Create the output for a log record, like performed by :mod:`logging` module.
:param category: Name of the logger (as string or None).
:param level: Log level (as number).
... |
java | @Override
public Object deserialize(Writable blob) {
HiveBitcoinBlock result = null;
if (blob instanceof BitcoinBlock) {
result = convertToHiveBitcoinBlock((BitcoinBlock) blob);
}
return result;
} |
java | public java.util.List<AccessKeyMetadata> getAccessKeyMetadata() {
if (accessKeyMetadata == null) {
accessKeyMetadata = new com.amazonaws.internal.SdkInternalList<AccessKeyMetadata>();
}
return accessKeyMetadata;
} |
java | private void writeFieldDescriptors(ObjectStreamClass classDesc, boolean externalizable) throws IOException {
Class<?> loadedClass = classDesc.forClass();
ObjectStreamField[] fields = null;
int fieldCount = 0;
// The fields of String are not needed since Strings are treated as
//... |
python | def close(self):
"""close(self)"""
if self.isClosed:
raise ValueError("operation illegal for closed doc")
if hasattr(self, '_outline') and self._outline:
self._dropOutline(self._outline)
self._outline = None
self._reset_page_refs()
self.metada... |
python | def parse(self, text, encoding='utf8', raise_exception=False):
"""Alias of helper.string.serialization.json.parse"""
return self.helper.string.serialization.json.parse(
text=text,
encoding=encoding,
raise_exception=raise_exception) |
java | public List<MapRow> readTable(Class<? extends TableReader> readerClass) throws IOException
{
TableReader reader;
try
{
reader = readerClass.getConstructor(StreamReader.class).newInstance(this);
}
catch (Exception ex)
{
throw new RuntimeException(ex);
}
... |
python | def update(self, **kwargs):
"""
Update the node on the compute server
:param kwargs: Node properties
"""
# When updating properties used only on controller we don't need to call the compute
update_compute = False
old_json = self.__json__()
compute_prop... |
java | private static UserGroupInformation createSecurityEnabledProxyUser(String userToProxy,
String fileLocation, Logger log
) throws IOException {
if (!new File(fileLocation).exists()) {
throw new RuntimeException("hadoop token file doesn't exist.");
}
log.info("Found token file. Setting " + Had... |
python | def damping(self):
"""Strain-compatible damping."""
try:
value = self._damping.value
except AttributeError:
value = self._damping
return value |
python | def compute_q(self, query_antecedent):
"""Compute query Tensor q.
Args:
query_antecedent: a Tensor with dimensions
{query_input_dim} + other_dims
Returns:
a Tensor with dimensions
query_heads_dims + {key_dim} + other_dims
"""
ret = mtf.einsum(
[query_antecedent... |
java | public void writeDefaultConstructor(String strClassName)
{
this.readThisMethod(strClassName);
Record recClassInfo = this.getMainRecord();
if ("interface".equals(recClassInfo.getField(ClassInfo.CLASS_TYPE).toString()))
return;
MethodInfo methodInfo = new MethodInfo();
... |
java | private static List<Object> mergeReferenceValues(AttributeDefinition attrDef, Object... values) {
List<Object> merged = new ArrayList<Object>();
for (Object value : values) {
if (value instanceof String) {
merged.addAll(getAsList((String) value, attrDef));
} else ... |
java | public Mailbox createMailbox(MailboxesQueue queue) {
if (mailboxCreator != null) {
return mailboxCreator.createMailbox(queue);
} else {
return new Mailbox(queue);
}
} |
python | def tween2(self, val, frm, to):
"""
linearly maps val between frm and to to a number between 0 and 1
"""
return self.tween(Mapping.linlin(val, frm, to, 0, 1)) |
java | public static <E> SortedSet<E> filter(
SortedSet<E> unfiltered, Predicate<? super E> predicate) {
return Platform.setsFilterSortedSet(unfiltered, predicate);
} |
java | public boolean waitForDialogToOpen() {
if(config.commandLogging){
Log.d(config.commandLoggingTag, "waitForDialogToOpen()");
}
return dialogUtils.waitForDialogToOpen(Timeout.getLargeTimeout(), true);
} |
java | void commitStatus(Runnable closure) {
GhprbSimpleStatusContext context = new GhprbSimpleStatusContext();
ContextExtensionPoint.executeInContext(closure, context);
extensions.add(new GhprbSimpleStatus(
context.showMatrixStatus,
context.context,
con... |
python | def _create_m2m_links_step(self, rel_model_name,
rel_key, rel_value, relation_name):
"""
Link many-to-many models together.
Syntax:
And `model` with `field` "`value`" is linked to `other model` in the
database:
Example:
.. code-block:: gherkin
... |
python | def _endStationsNode(self, name, content):
"""Process the end of a node under xtvd/stations"""
if name == 'callSign':
self._callSign = content
elif name == 'name':
self._stationName = content
elif name == 'affiliate':
self._affiliate = content
... |
java | public String[] getHardLinkedFiles(String src) throws IOException {
byte[][] components = INode.getPathComponents(src);
List<byte [][]> results = null;
readLock();
try {
INodeFile inode = getFileINode(components);
if (!exists(inode)) {
throw new IOException(src + " does not exist");
... |
java | public static PermutationChromosome<Integer>
ofInteger(final int start, final int end) {
if (end <= start) {
throw new IllegalArgumentException(format(
"end <= start: %d <= %d", end, start
));
}
return ofInteger(IntRange.of(start, end), end - start);
} |
python | def bytes_to_bits(bytes_):
"""Convert bytes to a list of bits
"""
res = []
for x in bytes_:
if not isinstance(x, int):
x = ord(x)
res += byte_to_bits(x)
return res |
python | def _subst_vars(path, local_vars):
"""In the string `path`, replace tokens like {some.thing} with the
corresponding value from the map `local_vars`.
If there is no corresponding value, leave the token unchanged.
"""
def _replacer(matchobj):
name = matchobj.group(1)
if name in local_... |
java | static void putObjectIfNotNull(
@NonNull JSONObject jsonObject,
@NonNull @Size(min = 1) String fieldName,
@Nullable JSONObject value
) {
if (value == null) {
return;
}
try {
jsonObject.put(fieldName, value);
} catch (JSONEx... |
java | private void expand(int roomNeeded)
{
// First, let's move current segment to segment list:
if (mSegments == null) {
mSegments = new ArrayList<char[]>();
}
char[] curr = mCurrentSegment;
mHasSegments = true;
mSegments.add(curr);
int oldLen = curr.l... |
python | def check(text):
"""Check the text."""
err = "misc.currency"
msg = u"Incorrect use of symbols in {}."
symbols = [
"\$[\d]* ?(?:dollars|usd|us dollars)"
]
return existence_check(text, symbols, err, msg) |
python | async def settings(dev: Device):
"""Print out all possible settings."""
settings_tree = await dev.get_settings()
for module in settings_tree:
await traverse_settings(dev, module.usage, module.settings) |
java | @Nonnull
public static <T> LToByteFunction<T> toByteFunctionFrom(Consumer<LToByteFunctionBuilder<T>> buildingFunction) {
LToByteFunctionBuilder builder = new LToByteFunctionBuilder();
buildingFunction.accept(builder);
return builder.build();
} |
java | public BoxRequestsShare.AddCollaboration getAddRequest(BoxCollaborationItem collaborationItem, BoxCollaboration.Role role, String login) {
BoxRequestsShare.AddCollaboration collab = new BoxRequestsShare.AddCollaboration(getCollaborationsUrl(),
createStubItem(collaborationItem), role, login, mSes... |
python | def main(
source,
repo_source_files,
requirements_file,
local_source_file,
work_dir):
"""
Bundle up a deployment package for AWS Lambda.
From your local filesystem:
\b
$ make-lambda-package .
...
dist/lambda-package.zip
Or from a rem... |
java | public final void acceptBoth(Consumer<? super L> left, Consumer<? super R> right, L defaultLeft, R defaultRight) {
left.accept(isLeft() ? getLeft() : defaultLeft);
right.accept(isRight() ? getRight() : defaultRight);
} |
java | public static String encodeObject(final java.io.Serializable serializableObject) {
return Base64.encodeObject(serializableObject, Base64.NO_OPTIONS);
} |
python | def get_available_storage_systems(self, start=0, count=-1, filter='', sort='', **kwargs):
"""
Retrieves the list of the storage systems and their associated volumes available to the server profile
based on the given server hardware type and enclosure group.
Args:
count:
... |
python | def read_pandas(fname, *args, **kwargs):
"""Read a file and return a pd.DataFrame"""
if not os.path.exists(fname):
raise ValueError('no data file `{}` found!'.format(fname))
if fname.endswith('csv'):
df = pd.read_csv(fname, *args, **kwargs)
else:
xl = pd.ExcelFile(fname)
... |
java | public ServiceFuture<BackupCertificateResult> backupCertificateAsync(String vaultBaseUrl, String certificateName, final ServiceCallback<BackupCertificateResult> serviceCallback) {
return ServiceFuture.fromResponse(backupCertificateWithServiceResponseAsync(vaultBaseUrl, certificateName), serviceCallback);
} |
java | public static IGeneratorSet asGeneratorSet( JsonObject json)
{
GeneratorSet generatorSet = new GeneratorSet();
// Get generator definitions
json.keySet().stream()
.forEach( function -> {
try
{
generatorSet.addGenerator( validFunction( function), asGenerator( json.getJs... |
python | def weighted_round_robin(iterable):
'''Takes an iterable of tuples of <item>, <weight> and cycles around them,
returning heavier (integer) weighted items more frequently.
'''
cyclable_list = []
assigned_weight = 0
still_to_process = [
(item, weight) for item, weight in
sorted(ite... |
java | protected ArrayList<EnvLoaderListener> getEnvironmentListeners()
{
ArrayList<EnvLoaderListener> listeners;
listeners = new ArrayList<EnvLoaderListener>();
/*
// add the descendant listeners
if (_childListeners != null) {
synchronized (_childListenerLock) {
ClassLoader loader;
... |
java | private static X509Certificate getReqSigCert(Message message) {
List<WSHandlerResult> results =
CastUtils.cast((List<?>)
message.getExchange().getInMessage().get(WSHandlerConstants.RECV_RESULTS));
if (results == null) {
return null;
}
/*
... |
python | async def on_raw_433(self, message):
""" Nickname in use. """
if not self.registered:
self._registration_attempts += 1
# Attempt to set new nickname.
if self._attempt_nicknames:
await self.set_nickname(self._attempt_nicknames.pop(0))
else:
... |
java | public static String md5(Resource res) throws NoSuchAlgorithmException, IOException {
InputStream is = res.getInputStream();
try {
return DigestUtils.md5Hex(is);
}
finally {
IOUtil.closeEL(is);
}
} |
java | public void marshall(GetStageRequest getStageRequest, ProtocolMarshaller protocolMarshaller) {
if (getStageRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getStageRequest.getApiId(), APIID_... |
java | public static List<AsyncOneResponse> scheduleRepairs(ColumnFamily resolved, String keyspaceName, DecoratedKey key, List<ColumnFamily> versions, List<InetAddress> endpoints)
{
List<AsyncOneResponse> results = new ArrayList<AsyncOneResponse>(versions.size());
for (int i = 0; i < versions.size(); i++)... |
java | public static base_responses add(nitro_service client, nsip resources[]) throws Exception {
base_responses result = null;
if (resources != null && resources.length > 0) {
nsip addresources[] = new nsip[resources.length];
for (int i=0;i<resources.length;i++){
addresources[i] = new nsip();
addresources[... |
python | def delete_website_configuration(self, headers=None):
"""
Removes all website configuration from the bucket.
"""
response = self.connection.make_request('DELETE', self.name,
query_args='website', headers=headers)
body = response.read()
boto.log.debug(body)... |
java | public String format(String key, Object ... params) {
ResourceBundle bundle = getBundle();
if (bundle.containsKey(key)) {
String msg = bundle.getString(key);
return MessageFormat.format(msg, params);
} else {
return MessageFormat.format("!!{0}!!", key); //$NON... |
python | def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
"""
When the form is posted, don't pass an instance to the form. It should
create a new one out of the posted data. We also need to nullify any
IDs posted for inline menu items, so that new instances of those are
... |
java | public C4QueryEnumerator run(C4QueryOptions options, AllocSlice parameters)
throws LiteCoreException {
if (parameters == null) { parameters = new AllocSlice(null); }
return new C4QueryEnumerator(run(handle, options.isRankFullText(), parameters.getHandle()));
} |
java | public ACE[] getSecurity(boolean resolveSids) throws IOException {
int f;
ACE[] aces;
f = open0( O_RDONLY, READ_CONTROL, 0, isDirectory() ? 1 : 0 );
/*
* NtTrans Query Security Desc Request / Response
*/
NtTransQuerySecurityDesc request = new NtTransQuerySecu... |
java | public static Trajectory getTrajectoryByID(List<? extends Trajectory> t, int id){
Trajectory track = null;
for(int i = 0; i < t.size() ; i++){
if(t.get(i).getID()==id){
track = t.get(i);
break;
}
}
return track;
} |
python | def to_dict(self):
"""
dump a representation of the nparray object to a dictionary. The
nparray object should then be able to be fully restored via
nparray.from_dict
"""
def _json_safe(v):
if isinstance(v, np.ndarray):
return v.tolist()
... |
python | def _parse_datetime_default_value(property_name, default_value_string):
"""Parse and return the default value for a datetime property."""
# OrientDB doesn't use ISO-8601 datetime format, so we have to parse it manually
# and then turn it into a python datetime object. strptime() will raise an exception
... |
java | public static void closeSession(String wrapper) {
Session session = map.get(wrapper);
if (session != null) {
Method method;
try {
method = session.getClass().getDeclaredMethod("protectedClose");
method.setAccessible(true);
method.invoke(session);
} catch (InvocationTargetException e) {
thro... |
python | def move_files_to_folders(directory):
"""
Loops through a parent directory and nests files within folders that already exists and have matching prefixs
:param directory: Starting directory
"""
# Generate lists of files and folders in root directory
files, folders, files_to_move = [], [], []
... |
python | def calculate_Y(sub_network,skip_pre=False):
"""Calculate bus admittance matrices for AC sub-networks."""
if not skip_pre:
calculate_dependent_values(sub_network.network)
if sub_network.network.sub_networks.at[sub_network.name,"carrier"] != "AC":
logger.warning("Non-AC networks not support... |
python | def _calc_entropy(data, size=None):
"""
Calculate the entropy of a piece of data
:param data: The target data to calculate entropy on
:param size: Size of the data, Optional.
:return: A float
"""
if not data:
return 0
entropy = 0
if s... |
java | public final void loadPublic(Properties ps)
{
//表示如果Field是static的,则obj即便给它传值,JVM也会忽略的。还说明了,此入参在这种情况下可以为null
for(Field f:getClass().getFields())
{
try {
setFiled(f,ps.getProperty(f.getName()));
} catch (Exception e) {
log.error(e.getMessage(),e);
}
}
} |
java | protected void defineManagedResource()
{
super.defineManagedResource();
defineAttribute("configuration");
defineAttribute("rootWebApp");
defineAttribute("webApplicationConfigurationClassNames");
defineOperation("addWebApplication",
new String[... |
python | def click_visible_elements(self, selector, by=By.CSS_SELECTOR, limit=0):
""" Finds all matching page elements and clicks visible ones in order.
If a click reloads or opens a new page, the clicking will stop.
Works best for actions such as clicking all checkboxes on a page.
Ex... |
java | public static <T> void registerBlockData(String identifier, Function<ByteBuf, T> fromBytes, Function<T, ByteBuf> toBytes)
{
instance.handlerInfos.put(identifier, new HandlerInfo<>(identifier, fromBytes, toBytes));
} |
python | def getmacbyip(ip, chainCC=0):
"""Return MAC address corresponding to a given IP address"""
if isinstance(ip, Net):
ip = next(iter(ip))
ip = inet_ntoa(inet_aton(ip or "0.0.0.0"))
tmp = [orb(e) for e in inet_aton(ip)]
if (tmp[0] & 0xf0) == 0xe0: # mcast @
return "01:00:5e:%.2x:%.2x:%... |
java | public void destroy() {
try {
ctx.close();
}
catch (javax.naming.NamingException e) {
LOG.warn("Error when closing", e);
}
} |
python | def set_heat_pump_feature(self, device_label, feature):
""" Set heatpump mode
Args:
feature: 'QUIET', 'ECONAVI', or 'POWERFUL'
"""
response = None
try:
response = requests.put(
urls.set_heatpump_feature(self._giid, device_label, feature),
... |
java | public Log getInstance(Class c) throws LogConfigurationException
{
if (c!=null)
return getInstance(c.getName());
return getInstance((String)null);
} |
java | private static int findStraddle(final double[] xArr, final double x) {
assert ((xArr.length >= 2) && (x >= xArr[0]) && (x <= xArr[xArr.length - 1]));
return (recursiveFindStraddle(xArr, 0, xArr.length - 1, x));
} |
python | def add_current_text(self):
"""
Add current text to combo box history (convenient method).
If path ends in os separator ("\" windows, "/" unix) remove it.
"""
text = self.currentText()
if osp.isdir(text) and text:
if text[-1] == os.sep:
... |
python | def do_pdb(self, line):
"""
'pdb' command:
switches back to debugging with (almost) standard pdb.Pdb
except for added 'vim' command.
"""
self.from_vim.closeSocket()
self.pdb = get_hooked_pdb()
self.pdb.set_trace_without_step(self.botframe)
if self.... |
java | protected EventBuilder createEventBuilder(LogRecord record) {
EventBuilder eventBuilder = new EventBuilder()
.withSdkIntegration("java.util.logging")
.withLevel(getLevel(record.getLevel()))
.withTimestamp(new Date(record.getMillis()))
.withLogger(record.getLoggerN... |
java | private static void injectMeAttribute(final DOMAccess me, final Object target, final Class<?> projectionInterface) {
//final Class<?> projectionInterface = me.getProjectionInterface();
for (Field field : target.getClass().getDeclaredFields()) {
if (!isValidMeField(field, projectionInterface)... |
python | def pybel_to_json(molecule, name=None):
"""Converts a pybel molecule to json.
Args:
molecule: An instance of `pybel.Molecule`
name: (Optional) If specified, will save a "name" property
Returns:
A Python dictionary containing atom and bond data
"""
# Save atom element type and... |
python | def get_shipping_label(jobIds=None, name=None, company=None, phoneNumber=None, country=None, stateOrProvince=None, city=None, postalCode=None, street1=None, street2=None, street3=None, APIVersion=None):
"""
This operation generates a pre-paid UPS shipping label that you will use to ship your device to AWS for p... |
python | def get_opt(self, opt):
"""Get value of option from configuration file
Parameters
-----------
opt : string
Name of option (e.g. output-file-format)
Returns
--------
value : string
The value for the option. Returns None if option not prese... |
python | def Martin_Sims(m, x, D, rhol, rhog, hl):
r'''Calculates the two-phase non-boiling heat transfer coefficient of a
liquid and gas flowing inside a tube of any inclination, as in [1]_ and
reviewed in [2]_.
.. math::
\frac{h_{TP}}{h_l} = 1 + 0.64\sqrt{\frac{V_{gs}}{V_{ls}}}
Para... |
python | def _constraint_names(self, model, column_names=None, unique=None,
primary_key=None, index=None, foreign_key=None,
check=None):
"""
Returns all constraint names matching the columns and conditions
"""
column_names = list(column_names) i... |
python | def rename_scored_calls(self,change):
"""
Change the names of scored call names, input dictionary change with {<current name>:<new name>} format, new name must not already exist
Args:
change (dict): a dictionary of current name keys and new name values
Returns:
... |
python | def has_scope(self, scope):
"""Return True if OAuth2 authorized for the passed in scope(s)."""
if not self.is_oauth_session():
return False
if '*' in self._authentication:
return True
if isinstance(scope, six.string_types):
scope = [scope]
retu... |
java | public static <E> void serialize(List<E> list, OutputStream os, Class<E> jsonObjectClass) throws IOException {
mapperFor(jsonObjectClass).serialize(list, os);
} |
java | private <T> T sendPostRequest(Object request, String urlStr, Class<T> clazz) throws IOException, URISyntaxException {
ObjectWriter writer = mapper.writer().without(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
boolean notPlainText = false;
if (request instanceof DocumentRequest) {
Object... |
java | @SuppressWarnings("unchecked")
public Map<String, BEValue> getMap() throws InvalidBEncodingException {
if (this.value instanceof HashMap) {
return (Map<String, BEValue>) this.value;
} else {
throw new InvalidBEncodingException("Expected Map<String, BEValue> !");
}
} |
java | public Termination withCidrAllowedList(String... cidrAllowedList) {
if (this.cidrAllowedList == null) {
setCidrAllowedList(new java.util.ArrayList<String>(cidrAllowedList.length));
}
for (String ele : cidrAllowedList) {
this.cidrAllowedList.add(ele);
}
ret... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.