language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public IoBuffer decodeFully(IoBuffer in) {
int contentLength = ctx.getContentLength();
IoBuffer decodedBuffer = ctx.getDecodedBuffer();
int oldLimit = in.limit();
// Retrieve fixed length content
if (contentLength > -1) {
if (decodedBuffer == null) {
... |
python | def patch_webbrowser():
"""
Some custom patches on top of the python webbrowser module to fix
user reported bugs and limitations of the module.
"""
# https://bugs.python.org/issue31014
# https://github.com/michael-lazar/rtv/issues/588
def register_patch(name, klass, instance=None, update_tr... |
python | def safe_makedirs(path):
"""A safe function for creating a directory tree."""
try:
os.makedirs(path)
except OSError as err:
if err.errno == errno.EEXIST:
if not os.path.isdir(path):
raise
else:
raise |
java | public void acceptAlert() {
String action = "Clicking 'OK' on an alert";
String expected = "Alert is present to be clicked";
// wait for element to be present
if (!is.alertPresent()) {
waitFor.alertPresent();
}
if (!is.alertPresent()) {
reporter.fa... |
java | @Override
public Pair<Integer, Integer> pPredecessor(int partition, int token) {
Integer partForToken = m_tokensMap.get().get(token);
if (partForToken != null && partForToken == partition) {
Map.Entry<Integer, Integer> predecessor = m_tokensMap.get().headMap(token).lastEntry();
... |
python | def sitemap_index(request):
"""Return a sitemap index xml file for search engines."""
sitemaps = []
with db_connect() as db_connection:
with db_connection.cursor() as cursor:
cursor.execute("""\
SELECT authors[1], max(revised)
FROM latest_modules
... |
java | public static boolean valueMatchesWildcardExpression(String val, String exp) {
//replace [\^$.|?*+() to make regexp do wildcard match
String expCopy = StringSupport.replaceAll(
exp,
new String[]{"[", "\\", "^", "$", ".", "?", "*", "+", "(", ")"},
new String[]{"\\[", "\\\\", "\\^", "\\$", "\\.",".?", ... |
java | @SuppressWarnings("unchecked")
public boolean getBooleanValue() {
String stringValue = getStringValue();
checkState(
stringValue.equalsIgnoreCase("true") || stringValue.equalsIgnoreCase("false"),
"Field value is not of boolean type");
return Boolean.parseBoolean(stringValue);
} |
java | private TimeSeriesValue interpolateTSV(GroupName name) {
final Map.Entry<DateTime, TimeSeriesValue> backTSV = findName(backward, name),
forwTSV = findName(forward, name);
final long backMillis = max(new Duration(backTSV.getKey(), getTimestamp()).getMillis(), 0),
forwMill... |
python | def get_recipe_intent_handler(request):
"""
You can insert arbitrary business logic code here
"""
# Get variables like userId, slots, intent name etc from the 'Request' object
ingredient = request.slots["Ingredient"] # Gets an Ingredient Slot from the Request object.
if ingredient == ... |
java | private Bindings createBindings(Entity entity, int depth) {
Bindings bindings = new SimpleBindings();
JSObject global = (JSObject) magmaBindings.get("nashorn.global");
JSObject magmaScript = (JSObject) global.getMember(KEY_MAGMA_SCRIPT);
JSObject dollarFunction = (JSObject) magmaScript.getMember(KEY_DOL... |
java | public static String unicode2String(String unicode) {
StringBuffer string = new StringBuffer();
String[] hex = unicode.split("\\\\u");
for (int i = 1; i < hex.length; i++) {
int data = Integer.parseInt(hex[i], 16);
string.append((char) data);
}
return string.toString();... |
python | def url(self, schemes=None):
"""
:param schemes: a list of strings to use as schemes, one will chosen randomly.
If None, it will generate http and https urls.
Passing an empty list will result in schemeless url generation like "://domain.com".
:returns: a random url string.
... |
python | def eval(self, id1, id2, inst1):
"""
Computes the result of the kernel function for two instances. If id1 == -1, eval use inst1 instead of an
instance in the dataset.
:param id1: the index of the first instance in the dataset
:type id1: int
:param id2: the index of the s... |
java | public static <T extends View> T mount(T v, Renderable r) {
Mount m = new Mount(v, r);
mounts.put(v, m);
render(v);
return v;
} |
python | def native(self, value, context=None):
"""Convert a foreign value to a native boolean."""
value = super().native(value, context)
if self.none and (value is None):
return None
try:
value = value.lower()
except AttributeError:
return bool(value)
if value in self.truthy:
return True
... |
java | private static String getProperty(String driverId, String propertyName) {
String propertyValue = PROPERTIES.getProperty(DEFAULT_PREFIX + "." + driverId + "." + propertyName);
if (propertyValue != null) {
propertyValue = propertyValue.trim();
if (propertyValue.isEmpty()) {
propertyValue = null;
}
}
... |
java | protected void addVisit(CmsDbContext dbc, String poolName, CmsVisitEntry visit) throws CmsDbSqlException {
Connection conn = null;
PreparedStatement stmt = null;
try {
if (CmsStringUtil.isNotEmpty(poolName)) {
conn = m_sqlManager.getConnection(poolName);
... |
python | def symlink(parser, cmd, args):
"""
Set up symlinks for (a subset of) the pwny apps.
"""
parser.add_argument(
'apps',
nargs=argparse.REMAINDER,
help='Which apps to create symlinks for.'
)
args = parser.parse_args(args)
base_dir, pwny_main = os.path.split(sys.argv[0]... |
java | public static ProducerTemplate generateTemplete(String contextUri) throws Exception
{
String initKey = contextUri.intern();
synchronized (initKey)
{
ProducerTemplate template = templates.get(initKey);
// 初期化済みの場合は、初期化済みのProducerTemplateを返す。
if (te... |
java | private ImmutableSubstitution<ImmutableTerm> computeLiftableSubstitution(
ImmutableSubstitution<? extends ImmutableTerm> selectedSubstitution,
Optional<Variable> rightProvenanceVariable, ImmutableSet<Variable> leftVariables) {
ImmutableMap<Variable, ImmutableTerm> newMap;
if (ri... |
python | def validate(reference_labels, estimated_labels):
"""Checks that the input annotations to a comparison function look like
valid chord labels.
Parameters
----------
reference_labels : list, len=n
Reference chord labels to score against.
estimated_labels : list, len=n
Estimated ch... |
java | private void setSwatchDescription(int rowNumber, int index, int rowElements, boolean selected,
View swatch) {
int accessibilityIndex;
if (rowNumber % 2 == 0) {
// We're in a regular-ordered row
accessibilityIndex = index;
} else {
// We're in a bac... |
java | public void addRecord(String key,
boolean b)
throws TarMalformatException, IOException {
addRecord(key, Boolean.toString(b));
} |
java | public void setupKeys()
{
KeyAreaInfo keyArea = null;
keyArea = new KeyAreaInfo(this, Constants.UNIQUE, ID_KEY);
keyArea.addKeyField(ID, Constants.ASCENDING);
keyArea = new KeyAreaInfo(this, Constants.NOT_UNIQUE, CLASS_INFO_ID_KEY);
keyArea.addKeyField(CLASS_INFO_ID, Constant... |
python | def get_zone():
"""make http response to AcraServer api to generate new zone and return tuple
of zone id and public key
"""
response = urlopen('{}/getNewZone'.format(ACRA_CONNECTOR_API_ADDRESS))
json_data = response.read().decode('utf-8')
zone_data = json.loads(json_data)
return zone_data['i... |
python | def cmd_startstop(options):
"""Start or Stop the specified instance.
Finds instances that match args and instance-state expected by the
command. Then, the target instance is determined, the action is
performed on the instance, and the eturn information is displayed.
Args:
options (object)... |
java | @Override
public boolean contains(IAtom atom) {
for (int i = 0; i < getAtomCount(); i++) {
if (atoms[i].equals(atom)) return true;
}
return false;
} |
java | public void marshall(CreateDataSourceFromRDSRequest createDataSourceFromRDSRequest, ProtocolMarshaller protocolMarshaller) {
if (createDataSourceFromRDSRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshalle... |
java | private void addNode(final TrieNode<V> node, final CharSequence key,
final int beginIndex, final TrieNode<V> newNode) {
final int lastKeyIndex = key.length() - 1;
TrieNode<V> currentNode = node;
int i = beginIndex;
for (; i < lastKeyIndex; i++) {
fin... |
java | public void setBaselineCost(int baselineNumber, Number value)
{
set(selectField(AssignmentFieldLists.BASELINE_COSTS, baselineNumber), value);
} |
python | def _resp_exception(self, resp):
"""If we encounter an exception in our upload.
we will look at how we can attempt to resolve the exception.
:param resp:
"""
message = [
'Url: [ %s ] Reason: [ %s ] Request: [ %s ] Status Code: [ %s ]. ',
resp.url,
... |
python | def needs_update(self, cache_key):
"""Check if the given cached item is invalid.
:param cache_key: A CacheKey object (as returned by CacheKeyGenerator.key_for().
:returns: True if the cached version of the item is out of date.
"""
if not self.cacheable(cache_key):
# An uncacheable CacheKey is... |
python | def make_optimize_tensor(self, model, session=None, var_list=None, **kwargs):
"""
Make SciPy optimization tensor.
The `make_optimize_tensor` method builds optimization tensor and initializes
all necessary variables created by optimizer.
:param model: GPflow model.
... |
python | def soap_action(self, service, action, payloadbody):
"""Do a soap request """
payload = self.soapenvelope.format(body=payloadbody).encode('utf-8')
headers = ['SOAPAction: ' + action,
'Content-Type: application/soap+xml; charset=UTF-8',
'Content-Length: ' + s... |
java | @Pure
protected AStarNode<ST, PT> translateCandidate(PT endPoint, AStarNode<ST, PT> node) {
if (endPoint.equals(node.getGraphPoint())) {
return null;
}
return node;
} |
java | public boolean containsMapping(Object key, Object value) {
Set<V> s = map.get(key);
return s != null && s.contains(value);
} |
python | def _check_device(self, requested_device, map_device):
"""Compare the requested device with the map device and
return the map device if it differs from the requested device
along with a warning.
"""
type_1 = torch.device(requested_device)
type_2 = torch.device(map_device)... |
python | def is_file_url(url):
"""Returns true if the given url is a file url"""
from .misc import to_text
if not url:
return False
if not isinstance(url, six.string_types):
try:
url = getattr(url, "url")
except AttributeError:
raise ValueError("Cannot parse url f... |
java | public CacheKeyTO getCacheKey(Object target, String methodName, Object[] arguments, String keyExpression,
String hfieldExpression, Object result, boolean hasRetVal) {
String key = null;
String hfield = null;
if (null != keyExpression && keyExpression.trim().leng... |
java | private String readString(byte stringTag, String stringName,
String enc) throws IOException {
if (buffer.read() != stringTag)
throw new IOException("DER input not a " +
stringName + " string");
int length = getLength(buffer);
... |
java | public static <T extends Tree> Matcher<T> isArrayType() {
return new Matcher<T>() {
@Override
public boolean matches(Tree t, VisitorState state) {
Type type = getType(t);
return type != null && state.getTypes().isArray(type);
}
};
} |
java | public StreamingJobInner beginCreateOrReplace(String resourceGroupName, String jobName, StreamingJobInner streamingJob) {
return beginCreateOrReplaceWithServiceResponseAsync(resourceGroupName, jobName, streamingJob).toBlocking().single().body();
} |
java | private void merge(NodeTask target, NodeTask source) {
List<StageType> stages = target.getStage();
List<TaskEvent> events = target.getEvent();
List<StageType> mergeStates = new ArrayList<StageType>();
List<TaskEvent> mergeEvents = new ArrayList<TaskEvent>();
// 合并两者的交集的数据
... |
java | @Action(name = "Create Volume",
outputs = {
@Output(Outputs.RETURN_CODE),
@Output(Outputs.RETURN_RESULT),
@Output(Outputs.EXCEPTION)
},
responses = {
@Response(text = Outputs.SUCCESS, field = Outputs.RETU... |
java | public void updateComment(int commentId, CommentUpdate comment) {
getResourceFactory().getApiResource("/comment/" + commentId)
.entity(comment, MediaType.APPLICATION_JSON_TYPE).put();
} |
python | def reconstruct_headers(self, response):
"""
Purpose of this method is to reconstruct the headers dictionary that
is normally passed in with a "response" object from scrapy.
Args:
response: A scrapy response object
Returns: A dictionary that mirrors the "response.he... |
python | def send(self, request, **kwargs):
# type: (ClientRequest, Any) -> ClientResponse
"""Send request object according to configuration.
Allowed kwargs are:
- session : will override the driver session and use yours. Should NOT be done unless really required.
- anything else is sent... |
python | def df(self):
"""
Makes a pandas DataFrame containing Curve data for all the wells
in the Project. The DataFrame has a dual index of well UWI and
curve Depths. Requires `pandas`.
Args:
No arguments.
Returns:
`pandas.DataFrame`.
"""
... |
python | def multiline_regex_suggestor(regex, substitution=None, ignore_case=False):
"""
Return a suggestor function which, given a list of lines, generates patches
to substitute matches of the given regex with (if provided) the given
substitution.
@param regex Either a regex object or a string desc... |
python | def get_version(dunder_file):
"""Returns a version string for the current package, derived
either from git or from a .version file.
This function is expected to run in two contexts. In a development
context, where .git/ exists, the version is pulled from git tags.
Using the BuildPyCommand and SDist... |
python | def concat(self, *dss, **kwargs):
"""
Concatenate dataswim instances from and
set it to the main dataframe
:param dss: dataswim instances to concatenate
:type dss: Ds
:param kwargs: keyword arguments for ``pd.concat``
"""
try:
df = p... |
java | @Override
public synchronized ChainGroupData removeChainGroup(String groupName) throws ChainGroupException {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Removing chain group, " + groupName);
}
if (null == groupName) {
throw new Cha... |
python | def _cp_embeds_into(cp1, cp2):
"""Check that any state in ComplexPattern2 is matched in ComplexPattern1.
"""
# Check that any state in cp2 is matched in cp1
# If the thing we're matching to is just a monomer pattern, that makes
# things easier--we just need to find the corresponding monomer pattern
... |
python | def encode(self, x):
"""
Given an input array `x` it returns its associated encoding `y(x)`, that is,
a stable configuration (local energy minimum) of the hidden units
while the visible units are clampled to `x`.
Note that NO learning takes place.
"""
E... |
java | public ICalendar first() throws IOException {
StreamReader reader = constructReader();
if (index != null) {
reader.setScribeIndex(index);
}
try {
ICalendar ical = reader.readNext();
if (warnings != null) {
warnings.add(reader.getWarnings());
}
return ical;
} finally {
if (closeWhenDone(... |
python | def configure_job():
"""Construct jobSpec for ML Engine job."""
# See documentation:
# https://cloud.google.com/ml-engine/reference/rest/v1/projects.jobs#traininginput
training_input = {
"pythonModule": "tensor2tensor.bin.t2t_trainer",
"args": flags_as_args(),
"region": text_encoder.native_to_... |
java | public int last() {
assertNonEmpty();
short lastKey = keys[size - 1];
Container container = values[size - 1];
return lastKey << 16 | container.last();
} |
java | public Observable<DatabaseVulnerabilityAssessmentInner> getAsync(String resourceGroupName, String serverName, String databaseName) {
return getWithServiceResponseAsync(resourceGroupName, serverName, databaseName).map(new Func1<ServiceResponse<DatabaseVulnerabilityAssessmentInner>, DatabaseVulnerabilityAssessmen... |
python | def select_date(self, rows: List[Row], column: DateColumn) -> Date:
"""
Select function takes a row as a list and a column name and returns the date in that column.
"""
dates: List[Date] = []
for row in rows:
cell_value = row.values[column.name]
if isinsta... |
python | def is_subsumed_by(x, y):
"""
Returns true if y subsumes x (for example P(x) subsumes P(A) as it is more
abstract)
"""
varsX = __split_expression(x)[1]
theta = unify(x, y)
if theta is problem.FAILURE:
return False
return all(__is_variable(theta[var]) for var in theta.keys()
... |
java | protected <R> R getWithTransaction(TransactionalFunction<R> function) {
Instant start = Instant.now();
LazyToString callingMethod = getCallingMethod();
logger.trace("{} : starting transaction", callingMethod);
try(Connection tx = dataSource.getConnection()) {
boolean previou... |
python | def _set_request_referer_metric(self, request):
"""
Add metric 'request_referer' for http referer.
"""
if 'HTTP_REFERER' in request.META and request.META['HTTP_REFERER']:
monitoring.set_custom_metric('request_referer', request.META['HTTP_REFERER']) |
java | public String max(List<String> s) {
String max = "";
for (String p : s) {
if (p.length() > max.length()) {
max = p;
}
}
return max;
} |
java | @SuppressWarnings({"AssignmentToMethodParameter"})
@NotNull
StoreImpl openStoreImpl(@NotNull final String name,
@NotNull StoreConfig config,
@NotNull final TransactionBase txn,
@Nullable TreeMetaInfo metaInfo) {
checkIfT... |
java | protected void dispatch(Throwable object, boolean child) {
if (object instanceof CompilationFailedException) {
report((CompilationFailedException) object, child);
} else if (object instanceof GroovyExceptionInterface) {
report((GroovyExceptionInterface) object, child);
} ... |
python | def NamedTemporaryFile(
mode="w+b",
buffering=-1,
encoding=None,
newline=None,
suffix=None,
prefix=None,
dir=None,
delete=True,
wrapper_class_override=None,
):
"""Create and return a temporary file.
Arguments:
'prefix', 'suffix', 'dir' -- as for mkstemp.
'mode' -- the... |
java | public IotHubDescriptionInner createOrUpdate(String resourceGroupName, String resourceName, IotHubDescriptionInner iotHubDescription, String ifMatch) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, resourceName, iotHubDescription, ifMatch).toBlocking().last().body();
} |
python | def exec_command(
client, container, command, interactive=True, stdout=None, stderr=None, stdin=None):
"""
Run provided command via exec API in provided container.
This is just a wrapper for PseudoTerminal(client, container).exec_command()
"""
exec_id = exec_create(client, container, comman... |
python | def measure_time(func_to_measure):
"""
This decorator allows to measure the execution time
of a function and prints it to the console.
:param func_to_measure: function to be decorated
"""
def wrap(*args, **kwargs):
start_time = time()
return_value = func_to_measure(*args, **kwarg... |
java | public static PageFlowController getCurrentPageFlow( HttpServletRequest request, ServletContext servletContext )
{
ActionResolver cur = getCurrentActionResolver( request, servletContext );
if (cur != null && cur.isPageFlow()) {
PageFlowController pfc = (PageFlowController) cur;
... |
python | def cmd_rot(self, deg=None, ch=None):
"""rot deg=num_deg ch=chname
Rotate the image for the given viewer/channel by the given
number of degrees.
If no value is given, reports the current rotation.
"""
viewer = self.get_viewer(ch)
if viewer is None:
se... |
python | def _call_vecfield_p(self, vf, out):
"""Implement ``self(vf, out)`` for exponent 1 < p < ``inf``."""
# Optimization for 1 component - just absolute value (maybe weighted)
if len(self.domain) == 1:
vf[0].ufuncs.absolute(out=out)
if self.is_weighted:
out *= ... |
java | public Observable<P2SVpnServerConfigurationInner> beginCreateOrUpdateAsync(String resourceGroupName, String virtualWanName, String p2SVpnServerConfigurationName, P2SVpnServerConfigurationInner p2SVpnServerConfigurationParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, virtualWan... |
java | public void removeElementsWithNoRelationships() {
Set<RelationshipView> relationships = getRelationships();
Set<String> elementIds = new HashSet<>();
relationships.forEach(rv -> elementIds.add(rv.getRelationship().getSourceId()));
relationships.forEach(rv -> elementIds.add(rv.getRelatio... |
java | private int getIntForType(JSType type) {
// Templatized types don't exist at runtime, so collapse to raw type
if (type != null && type.isGenericObjectType()) {
type = type.toMaybeObjectType().getRawType();
}
if (intForType.containsKey(type)) {
return intForType.get(type).intValue();
}
... |
java | public List<ConnectionParams> resolveAll(String correlationId, String key) {
List<ConnectionParams> connections = new ArrayList<ConnectionParams>();
synchronized (_lock) {
for (DiscoveryItem item : _items) {
if (item.key == key && item.connection != null)
connections.add(item.connection);
}
}
r... |
python | def grade(adjective, suffix=COMPARATIVE):
""" Returns the comparative or superlative form of the given (inflected) adjective.
"""
b = predicative(adjective)
# groß => großt, schön => schönst
if suffix == SUPERLATIVE and b.endswith(("s", u"ß")):
suffix = suffix[1:]
# große => großere, sch... |
java | public long installBundle( final String bundleUrl )
throws BundleException
{
LOG.info( "Install bundle from URL [" + bundleUrl + "]" );
return m_bundleContext.installBundle( bundleUrl ).getBundleId();
} |
java | @Override
public void serialize(final DataOutput pOutput) throws TTIOException {
try {
pOutput.writeInt(IConstants.ROOT);
mDel.serialize(pOutput);
mStrucDel.serialize(pOutput);
} catch (final IOException exc) {
throw new TTIOException(exc);
}
... |
java | public static Failure parse(String failure) {
Failure result = new Failure();
int dash = failure.indexOf('-');
int leftBracet = failure.indexOf('(');
int rightBracet = failure.indexOf(')');
result.title = failure.substring(0, leftBracet).trim();
result.code = failure.subs... |
java | protected void refreshItem(CacheItem item, Cache cache) throws Exception {
CacheLoader loader = item.getLoader();
Object[] loaderParams = item.getLoaderParams();
if (loader == null) {
throw new InternalCacheEngineException("No cache loader for " + getScopeAndKeyString(item));
... |
java | public List<NamedStoredProcedureQuery<OrmDescriptor>> getAllNamedStoredProcedureQuery()
{
List<NamedStoredProcedureQuery<OrmDescriptor>> list = new ArrayList<NamedStoredProcedureQuery<OrmDescriptor>>();
List<Node> nodeList = model.get("named-stored-procedure-query");
for(Node node: nodeList)
... |
python | def _validate_date_like_dtype(dtype):
"""
Check whether the dtype is a date-like dtype. Raises an error if invalid.
Parameters
----------
dtype : dtype, type
The dtype to check.
Raises
------
TypeError : The dtype could not be casted to a date-like dtype.
ValueError : The d... |
java | private static void assertAllLoopablePasses(List<PassFactory> passes) {
for (PassFactory pass : passes) {
checkState(!pass.isOneTimePass());
}
} |
java | public void setBundleStartLevel( long bundleId, int startLevel )
throws RemoteException, BundleException
{
try
{
final StartLevel startLevelService = getService( StartLevel.class, 0 );
startLevelService.setBundleStartLevel( m_bundleContext.getBundle( bundleId ), start... |
python | def setErrorHandler(self, errorhandler):
"""
Sets a new error handler.
Args:
errorhandler: The object handling AMPL errors and warnings.
"""
class ErrorHandlerWrapper(ErrorHandler):
def __init__(self, errorhandler):
self.errorhandler = err... |
python | def meta_description(request):
"""
{% meta_description request %}
"""
try:
fragments = request._feincms_fragments
except:
fragments = {}
if '_meta_description' in fragments and fragments.get("_meta_description"):
return fragments.get("_meta_description")
else:
... |
python | def get_method(self, name, descriptor):
"""
Get the method by name and descriptor,
or create a new one if the requested method does not exists.
:param name: method name
:param descriptor: method descriptor, for example `'(I)V'`
:return: :class:`ExternalMethod`
""... |
java | public static authenticationradiuspolicy_vpnvserver_binding[] get(nitro_service service, String name) throws Exception{
authenticationradiuspolicy_vpnvserver_binding obj = new authenticationradiuspolicy_vpnvserver_binding();
obj.set_name(name);
authenticationradiuspolicy_vpnvserver_binding response[] = (authentic... |
java | public <S, T> FromUnmarshaller<S, T> findUnmarshaller(ConverterKey<S,T> key) {
Converter<T,S> converter = findConverter(key.invert());
if (converter == null) {
return null;
}
if (FromUnmarshallerConverter.class.isAssignableFrom(converter.getClass())) {
return ((FromUnmarshallerConverter<S,... |
java | public void convertToConstants(List<SDVariable> variables){
if(variables.size() == 0)
return;
boolean allConst = true;
for(SDVariable variable : variables) {
if (variable.getVariableType() != VariableType.CONSTANT) {
allConst = false;
Preco... |
python | def symmetric_difference(self, other):
"""
Return a tree with elements only in self or other but not
both.
"""
if not isinstance(other, set): other = set(other)
me = set(self)
ivs = me.difference(other).union(other.difference(me))
return IntervalTree(ivs) |
java | public void writeExternal(PofWriter writer)
throws IOException {
super.writeExternal(writer);
writer.writeBinary(10, toBinary(value));
writer.writeBoolean(11, fAllowInsert);
writer.writeBoolean(12, fReturn);
} |
java | public Map<ModelField,Set<Command>> process(ModelFactory modelFactory, Erector erector, Object model) throws PolicyException {
Map<ModelField,Set<Command>> modelFieldCommands = new HashMap<ModelField,Set<Command>>();
for ( ModelField modelField : erector.getModelFields() ) {
logger.debug( " {} {}", get... |
python | def process_read_batch(self, batch):
"""Process a single, partitioned read.
:type batch: mapping
:param batch:
one of the mappings returned from an earlier call to
:meth:`generate_read_batches`.
:rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet... |
java | private static String getResourceSuffix(Locale locale)
{
String suffix = "_" + locale.getLanguage();
String country = locale.getCountry();
if (country.equals("TW"))
suffix += "_" + country;
return suffix;
} |
python | def get_rich_menu(self, rich_menu_id, timeout=None):
"""Call get rich menu API.
https://developers.line.me/en/docs/messaging-api/reference/#get-rich-menu
:param str rich_menu_id: ID of the rich menu
:param timeout: (optional) How long to wait for the server
to send data bef... |
java | public static <T extends Object> T[] splice (T[] values, int offset)
{
int length = (values == null) ? 0 : values.length - offset;
return splice(values, offset, length);
} |
java | public static Vec compose(TransfVec origVec, int[][] transfMap, String[] domain, boolean keepOrig) {
// Do a mapping from INT -> ENUM -> this vector ENUM
int[][] domMap = Utils.compose(new int[][] {origVec._values, origVec._indexes }, transfMap);
Vec result = origVec.masterVec().makeTransf(domMap[0], domMap... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.