language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
java | public boolean feed_publishTemplatizedAction(CharSequence titleTemplate,
Map<String, CharSequence> titleData,
CharSequence bodyTemplate,
Map<String, CharSequence> bodyData,
... |
java | public void doProcess(InputStream in, PrintWriter out, Map<String, Object> properties)
throws RemoteException
{
String strCommand = this.getProperty(REMOTE_COMMAND, properties);
try {
if (OPEN.equals(strCommand))
{
String strKeyArea = this.getNextStrin... |
java | public void setUtc(String utc) {
if (utc == null) {
this.utc = null;
} else {
if (utc.length() != 20) {
throw new IllegalArgumentException("Must be of the form YYYYMMDDTHHMMSS.sssZ");
}
}
} |
python | def single_line_stdout(cmd, expected_errors=(), shell=True, sudo=False, quiet=False):
"""
Runs a command and returns the first line of the result, that would be written to `stdout`, as a string.
The output itself can be suppressed.
:param cmd: Command to run.
:type cmd: unicode
:param expected_... |
python | def make_pipeline(context):
"""
Create our pipeline.
"""
# Filter for primary share equities. IsPrimaryShare is a built-in filter.
primary_share = IsPrimaryShare()
# Not when-issued equities.
not_wi = ~IEXCompany.symbol.latest.endswith('.WI')
# Equities without LP in their name, .matc... |
java | public int fetchEntries(int tableIndex, int size, List<Map.Entry<K, V>> entries) {
final long now = Clock.currentTimeMillis();
final Segment<K, V> segment = segments[0];
final HashEntry<K, V>[] currentTable = segment.table;
int nextTableIndex;
if (tableIndex >= 0 && tableIndex < ... |
java | private ImmutableMap<Predicate,ImmutableList<TermType>> extractCastTypeMap(
Multimap<Predicate, CQIE> ruleIndex, List<Predicate> predicatesInBottomUp,
ImmutableMap<CQIE, ImmutableList<Optional<TermType>>> termTypeMap, DBMetadata metadata) {
// Append-only
Map<Predicate,Immutable... |
python | def needs_invalidation(self, requirement, cache_file):
"""
Check whether a cached binary distribution needs to be invalidated.
:param requirement: A :class:`.Requirement` object.
:param cache_file: The pathname of a cached binary distribution (a string).
:returns: :data:`True` i... |
python | def request_frame(self):
"""Construct initiating frame."""
self.session_id = get_new_session_id()
return FrameCommandSendRequest(node_ids=[self.node_id], parameter=self.parameter, session_id=self.session_id) |
java | private void _createZeroArgsMethodExpression(MethodExpression methodExpression)
{
ExpressionFactory expressionFactory = getFacesContext().getApplication().getExpressionFactory();
this.methodExpressionZeroArg = expressionFactory.createMethodExpression(getElContext(),
methodExpress... |
python | async def scp_to(self, source, destination, user='ubuntu', proxy=False,
scp_opts=''):
"""Transfer files to this machine.
:param str source: Local path of file(s) to transfer
:param str destination: Remote destination of transferred files
:param str user: Remote user... |
java | public void poppush( int n, Frame ary, String key) {
addRef(ary);
for( int i=0; i<n; i++ ) {
assert _sp > 0;
_sp--;
_fcn[_sp] = subRef(_fcn[_sp]);
_ary[_sp] = subRef(_ary[_sp], _key[_sp]);
}
push(1); _ary[_sp-1] = ary; _key[_sp-1] = key;
assert check_all_refcnts();
} |
python | def make_module_to_builder_dict(datasets=None):
"""Get all builders organized by module in nested dicts."""
# pylint: disable=g-long-lambda
# dict to hold tfds->image->mnist->[builders]
module_to_builder = collections.defaultdict(
lambda: collections.defaultdict(
lambda: collections.defaultdict(... |
python | def pad_matrix(self, matrix, pad_value=0):
"""
Pad a possibly non-square matrix to make it square.
:Parameters:
matrix : list of lists
matrix to pad
pad_value : int
value to use to pad the matrix
:rtype: list of lists
:re... |
java | public BinaryDecoder createBinaryDecoder(final Encoding encoding)
throws UnsupportedEncodingException {
if (Encoding.QUOTED_PRINTABLE.equals(encoding)) {
return new QuotedPrintableCodec();
}
else if (Encoding.BASE64.equals(encoding)) {
return new Base64();
... |
python | def from_clause(cls, clause):
""" Factory method """
(field, operator, val) = clause
return cls(field, operator, field_or_value(val)) |
java | @BetaApi
public final ListDisksPagedResponse listDisks(ProjectZoneName zone) {
ListDisksHttpRequest request =
ListDisksHttpRequest.newBuilder().setZone(zone == null ? null : zone.toString()).build();
return listDisks(request);
} |
java | public DrawerProfile setRoundedAvatar(Context context, Bitmap image) {
return setAvatar(new RoundedAvatarDrawable(new BitmapDrawable(context.getResources(), image).getBitmap()));
} |
python | def read(self):
"""Return a single byte from the output buffer
"""
if self._output_buffer:
b, self._output_buffer = (self._output_buffer[0:1],
self._output_buffer[1:])
return b
return b'' |
java | SearchResult search(@NonNull ByteArraySegment key, int startPos) {
// Positions here are not indices into "source", rather they are entry positions, which is why we always need
// to adjust by using entryLength.
int endPos = getCount();
Preconditions.checkArgument(startPos <= endPos, "st... |
java | public org.osmdroid.views.overlay.Polygon toCurvePolygon(CurvePolygon curvePolygon) {
org.osmdroid.views.overlay.Polygon polygonOptions = new org.osmdroid.views.overlay.Polygon();
List<GeoPoint> pts = new ArrayList<>();
List<Curve> rings = curvePolygon.getRings();
List<List<GeoPoint>> ... |
java | static void makeTypeInfoBits(ErrorCorrectionLevel ecLevel, int maskPattern, BitArray bits)
throws WriterException {
if (!QRCode.isValidMaskPattern(maskPattern)) {
throw new WriterException("Invalid mask pattern");
}
int typeInfo = (ecLevel.getBits() << 3) | maskPattern;
bits.appendBits(typeI... |
java | static Object coerceTypeImpl(Class<?> type, Object value)
{
if (value != null && value.getClass() == type) {
return value;
}
switch (getJSTypeCode(value)) {
case JSTYPE_NULL:
// raise error if type.isPrimitive()
if (type.isPrimitive()) {
... |
java | public static String printToUnicodeString(final UnknownFieldSet fields) {
try {
final StringBuilder text = new StringBuilder();
UNICODE_PRINTER.printUnknownFields(fields, new TextGenerator(text));
return text.toString();
} catch (IOException e) {
throw new IllegalStateException(e);
}... |
python | def add_mpl_colorscale(fig, heatmap_gs, ax_map, params, title=None):
"""Add colour scale to heatmap."""
# Set tick intervals
cbticks = [params.vmin + e * params.vdiff for e in (0, 0.25, 0.5, 0.75, 1)]
if params.vmax > 10:
exponent = int(floor(log10(params.vmax))) - 1
cbticks = [int(round... |
java | private void extractIndirectionTables(DescriptorRepository model, Database schema)
{
HashMap indirectionTables = new HashMap();
// first we gather all participants for each m:n relationship
for (Iterator classDescIt = model.getDescriptorTable().values().iterator(); classDescIt.hasNext(... |
python | def ellipse(self, x,y,w,h,style=''):
"Draw a ellipse"
if(style=='F'):
op='f'
elif(style=='FD' or style=='DF'):
op='B'
else:
op='S'
cx = x + w/2.0
cy = y + h/2.0
rx = w/2.0
ry = h/2.0
lx = 4.0/3.0*(math.sqrt(2)-... |
java | protected void reportFailure (Throwable caught)
{
java.util.logging.Logger.getLogger("PagedWidget").warning("Failure to page: " + caught);
} |
java | public void write(Model project, Document document, String encoding, OutputStreamWriter writer)
throws java.io.IOException
{
Format format = Format.getRawFormat().setEncoding(encoding).setLineSeparator(LS);
write(project, document, writer, format);
} |
java | private String getInternalName(Klass k) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
klass.printValueOn(new PrintStream(bos));
// '*' is used to denote VM internal klasses.
return "* " + bos.toString();
} |
java | public Photos getPhotos(String galleryId, EnumSet<JinxConstants.PhotoExtras> extras) throws JinxException {
JinxUtils.validateParams(galleryId);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.galleries.getPhotos");
params.put("gallery_id", galleryId);
if (!JinxUtils.isNul... |
python | def convert_logistic_regression_output(node, **kwargs):
"""Map MXNet's SoftmaxOutput operator attributes to onnx's Softmax operator
and return the created node.
"""
name = node["name"]
input1_idx = kwargs["index_lookup"][node["inputs"][0][0]]
input1 = kwargs["proc_nodes"][input1_idx]
sigmoid... |
java | private void put(PrintStream p, String s, int column, int colSpan, BandElement bandElement) {
if (s == null) {
// nl();
put(p, "", column, colSpan, bandElement);
return;
}
int size = 0;
if (colSpan > 1) {
for (int i=column; i<c... |
python | def view_task_info(token, dstore):
"""
Display statistical information about the tasks performance.
It is possible to get full information about a specific task
with a command like this one, for a classical calculation::
$ oq show task_info:classical
"""
args = token.split(':')[1:] # cal... |
java | @Override
public void doSessionCreated(ManagementContext managementContext,
ServiceManagementBean serviceBean,
IoSessionEx session,
ManagementSessionType managementSessionType) throws Exception {
SessionManage... |
java | private void unlockInherited(final String absoluteResourcename) throws CmsException {
CmsObject cms = getCms();
CmsLock parentLock = getParentLock(absoluteResourcename);
if (!parentLock.isNullLock()) {
if (parentLock.isInherited()) {
unlockInherited(parentLock.getRes... |
python | def uid(self):
"""Return the user id that the process will run as
:rtype: int
"""
if not self._uid:
if self.config.daemon.user:
self._uid = pwd.getpwnam(self.config.daemon.user).pw_uid
else:
self._uid = os.getuid()
return ... |
java | public ServiceFuture<List<BlobContainerInner>> listStorageContainersAsync(final String resourceGroupName, final String accountName, final String storageAccountName, final ListOperationCallback<BlobContainerInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listStorageContainersSin... |
python | def quartus_prop(self, buff: List[str], intfName: str, name: str, value,
escapeStr=True):
"""
Set property on interface in Quartus TCL
:param buff: line buffer for output
:param intfName: name of interface to set property on
:param name: property name
... |
python | def create_domain(self, domain, ipaddr, params=None):
''' /v1/dns/create_domain
POST - account
Create a domain name in DNS
Link: https://www.vultr.com/api/#dns_create_domain
'''
params = update_params(params, {
'domain': domain,
'ip': ipaddr
... |
java | public QueryBuilder populateFilterBuilder(Expression condtionalExp, EntityMetadata m)
{
log.info("Populating filter for expression: " + condtionalExp);
QueryBuilder filter = null;
if (condtionalExp instanceof SubExpression)
{
filter = populateFilterBuilder(((SubExpressio... |
python | def linspace_pix(self, start=None, stop=None, pixel_step=1, y_vs_x=None):
"""Return x,y values evaluated with a given pixel step.
The returned values are computed within the corresponding
bounding box of the line.
Parameters
----------
start : float
Minimum ... |
java | @Indexable(type = IndexableType.REINDEX)
@Override
public CommerceNotificationTemplateUserSegmentRel updateCommerceNotificationTemplateUserSegmentRel(
CommerceNotificationTemplateUserSegmentRel commerceNotificationTemplateUserSegmentRel) {
return commerceNotificationTemplateUserSegmentRelPersistence.update(commer... |
java | protected AqlQueryOptions mergeQueryOptions(final AqlQueryOptions oldStatic, final AqlQueryOptions newDynamic) {
if (oldStatic == null) {
return newDynamic;
}
if (newDynamic == null) {
return oldStatic;
}
final Integer batchSize = newDynamic.getBatchSize();
if (batchSize != null) {
oldStatic.batchS... |
python | def CreateSms(self, MessageType, *TargetNumbers):
"""Creates an SMS message.
:Parameters:
MessageType : `enums`.smsMessageType*
Message type.
TargetNumbers : str
One or more target SMS numbers.
:return: An sms message object.
:rtype: `SmsMess... |
python | def replace(self, seq):
'''
Performs search and replace on the given input string `seq` using
the values stored in this trie. This method uses a O(n**2)
chart-parsing algorithm to find the optimal way of replacing
matches in the input.
Arguments:
- `seq`:
... |
java | public static void resetBean(MethodSpec.Builder methodBuilder, TypeName beanClass, String beanName,
ModelProperty property, String cursorName, String indexName) {
SQLTransform transform = lookup(property.getElement().asType());
if (transform == null) {
throw new IllegalArgumentException("Transform of " + pro... |
java | protected <T extends CSSProperty> boolean genericProperty(Class<T> type,
TermIdent term, boolean avoidInherit,
Map<String, CSSProperty> properties, String propertyName) {
T property = genericPropertyRaw(type, null, term);
if (property == null || (avoidInherit && property.equalsInherit()))
return false;
... |
java | private String getContentFromPath(String sourcePath,
HostsSourceType sourceType) throws IOException {
String res = "";
if (sourceType == HostsSourceType.LOCAL_FILE) {
res = PcFileNetworkIoUtils.readFileContentToString(sourcePath);
} else if (sourceType == HostsSourceTyp... |
python | def p_constant_def(t):
"""constant_def : CONST ID EQUALS constant SEMI"""
global name_dict
id = t[2]
value = t[4]
lineno = t.lineno(1)
if id_unique(id, 'constant', lineno):
name_dict[id] = const_info(id, value, lineno) |
java | public void validateNonce(ConsumerDetails consumerDetails, long timestamp, String nonce) throws AuthenticationException {
long nowSeconds = (System.currentTimeMillis() / 1000);
if ((nowSeconds - timestamp) > getValidityWindowSeconds()) {
throw new CredentialsExpiredException("Expired timestamp.");
}
... |
java | public QueryBuilder parentIds(final Set<Integer> ids) {
parentIds = new HashSet<Integer>();
if (ids != null) {
parentIds.addAll(ids);
}
return this;
} |
java | @Override
public CProduct findByUuid_Last(String uuid,
OrderByComparator<CProduct> orderByComparator)
throws NoSuchCProductException {
CProduct cProduct = fetchByUuid_Last(uuid, orderByComparator);
if (cProduct != null) {
return cProduct;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_S... |
java | public static String getSettingForApp(App app, String key, String defaultValue) {
if (app != null) {
Map<String, Object> settings = app.getSettings();
if (settings.containsKey(key)) {
return String.valueOf(settings.getOrDefault(key, defaultValue));
} else if (app.isRootApp()) {
return Config.getConfi... |
python | def handle_aliases_in_init_files(name, import_alias_mapping):
"""Returns either None or the handled alias.
Used in add_module.
"""
for key, val in import_alias_mapping.items():
# e.g. Foo == Foo
# e.g. Foo.Bar startswith Foo.
if name == val or \
name.startswith(va... |
java | public void setReplicationTasks(java.util.Collection<ReplicationTask> replicationTasks) {
if (replicationTasks == null) {
this.replicationTasks = null;
return;
}
this.replicationTasks = new java.util.ArrayList<ReplicationTask>(replicationTasks);
} |
python | def register(self, resource=None, **kwargs):
""" Register resource for currnet API.
:param resource: Resource to be registered
:type resource: jsonapi.resource.Resource or None
:return: resource
:rtype: jsonapi.resource.Resource
.. versionadded:: 0.4.1
:param kw... |
python | def doesnt_have(self, relation, boolean='and', extra=None):
"""
Add a relationship count to the query.
:param relation: The relation to count
:type relation: str
:param boolean: The boolean value
:type boolean: str
:param extra: The extra query
:type ex... |
python | def _graph_connected_component(graph, node_id):
"""
Find the largest graph connected components the contains one
given node
Parameters
----------
graph : array-like, shape: (n_samples, n_samples)
adjacency matrix of the graph, non-zero weight means an edge
between the nodes
... |
java | public Observable<PolicyDefinitionInner> getAsync(String policyDefinitionName) {
return getWithServiceResponseAsync(policyDefinitionName).map(new Func1<ServiceResponse<PolicyDefinitionInner>, PolicyDefinitionInner>() {
@Override
public PolicyDefinitionInner call(ServiceResponse<PolicyDef... |
python | def get_declared_items(self):
""" Get the members that were set in the enamldef block for this
Declaration. Layout keys are grouped together until the end so as
to avoid triggering multiple updates.
Returns
-------
result: List of (k,v) pairs that were defined fo... |
java | private void handleUndeliverableMessage(
DestinationHandler destinationHandler,
LinkHandler linkHandler,
SIMPMessage msg,
int exceptionReason,
... |
python | def list(self, host_rec=None, service_rec=None, hostfilter=None):
"""
Returns a list of vulnerabilities based on t_hosts.id or t_services.id.
If neither are set then statistical results are added
:param host_rec: db.t_hosts.id
:param service_rec: db.t_services.id
:param ... |
python | def _partialParseDateStr(self, s, sourceTime):
"""
test if giving C{s} matched CRE_DATE3, used by L{parse()}
@type s: string
@param s: date/time text to evaluate
@type sourceTime: struct_time
@param sourceTime: C{struct_time} value to use as the base
... |
java | public void addFilterAt(IRuleFilter filter, Class<? extends IRuleFilter> atFilter) {
int index = getIndexOfClass(filters, atFilter);
if (index == -1) {
throw new FilterAddException("filter " + atFilter.getSimpleName() + " has not been added");
}
filters.remove(index);
... |
java | public static Object[] extract(String xmltext) throws AesException {
Object[] result = new Object[3];
try {
DocumentBuilder db = Wxs.xmls();
StringReader sr = new StringReader(xmltext);
InputSource is = new InputSource(sr);
Document document = db.parse(is);
Element root = document.getDocumentEle... |
java | public void writeUnmodifiedUTF (String str)
throws IOException
{
// byte[] bytes = str.getBytes(Charsets.UTF_8); // TODO Java 6 (Charsets is from guava)
byte[] bytes = str.getBytes("UTF-8");
writeShort(bytes.length);
write(bytes);
} |
java | private static int[] filter(int[] org, int skip1, int skip2) {
int n = 0;
int[] dest = new int[org.length - 2];
for (int w : org) {
if (w != skip1 && w != skip2) dest[n++] = w;
}
return dest;
} |
java | public static Img createRemoteImg(BufferedImage bimg){
int type = bimg.getRaster().getDataBuffer().getDataType();
if(type != DataBuffer.TYPE_INT){
throw new IllegalArgumentException(
String.format("cannot create Img as remote of provided BufferedImage!%n"
+ "Need BufferedImage with DataBuffer of type... |
java | public void releaseLock(Object key) {
ReentrantReadWriteLock lock = getLock(key);
if (lock.isWriteLockedByCurrentThread()) {
lock.writeLock().unlock();
if (trace) log.tracef("WL released for '%s'", key);
} else {
lock.readLock().unlock();
if (trace) log.tracef("RL r... |
python | def is_handler(cls, name, value):
"""Detect an handler and return its wanted signal name."""
signal_name = False
config = None
if callable(value) and hasattr(value, SPEC_CONTAINER_MEMBER_NAME):
spec = getattr(value, SPEC_CONTAINER_MEMBER_NAME)
if spec['kin... |
java | public Response bind(String name, Object model) {
getLocals().put(name, model);
return this;
} |
java | private MessageML parseMessageML(String messageML, String version) throws InvalidInputException, ProcessingException {
validateMessageText(messageML);
org.w3c.dom.Element docElement = parseDocument(messageML);
validateEntities(docElement, entityJson);
switch (docElement.getTagName()) {
case Mes... |
python | def append_position(path, position, separator=''):
"""
Concatenate a path and a position,
between the filename and the extension.
"""
filename, extension = os.path.splitext(path)
return ''.join([filename, separator, str(position), extension]) |
python | def memory(self):
"""Memory information in bytes
Example:
>>> print(ctx.device(0).memory())
{'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L}
Returns:
total/used/free memory in bytes
"""
class GpuMemoryInfo(Structure):
... |
python | def set_total_deposit(
self,
given_block_identifier: BlockSpecification,
channel_identifier: ChannelID,
total_deposit: TokenAmount,
partner: Address,
):
""" Set channel's total deposit.
`total_deposit` has to be monotonically increasing, t... |
python | def get_user(self, username="", ext_collections=False, ext_galleries=False):
"""Get user profile information
:param username: username to lookup profile of
:param ext_collections: Include collection folder info
:param ext_galleries: Include gallery folder info
"""
if n... |
java | JmsConnectionImpl instantiateConnection(JmsJcaConnection jcaConnection, Map<String, String> _passThruProps) throws JMSException {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(this, tc, "instantiateConnection", jcaConnection);
JmsConnectionImpl jmsConnection = ... |
python | def _GetFileMappingsByPath(self, key_path_upper):
"""Retrieves the Windows Registry file mappings for a specific path.
Args:
key_path_upper (str): Windows Registry key path, in upper case with
a resolved root key alias.
Yields:
WinRegistryFileMapping: Windows Registry file mapping.
... |
java | public synchronized CuratorFramework getLocalConnection() throws IOException
{
if ( localConnection == null )
{
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
.connectString("localhost:" + configManager.getConfig().getInt(IntConfigs.CLIENT_POR... |
python | def delete_firewall_rule(self, server_uuid, firewall_rule_position):
"""
Delete a firewall rule based on a server uuid and rule position.
"""
url = '/server/{0}/firewall_rule/{1}'.format(server_uuid, firewall_rule_position)
return self.request('DELETE', url) |
python | def bbox(self):
"""BBox"""
return self.left, self.top, self.right, self.bottom |
java | public Member register(RegistrationRequest registrationRequest) throws RegistrationException {
Member member = getMember(registrationRequest.getEnrollmentID());
member.register(registrationRequest);
return member;
} |
java | @Transactional
public <T> List<T> findProperty(Class<T> propertyType, E entity, SearchParameters sp, List<Attribute<?, ?>> attributes) {
if (sp.hasNamedQuery()) {
return byNamedQueryUtil.findByNamedQuery(sp);
}
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
... |
python | def _ingest_string(self, input_string, path_to_root):
'''
a helper method for ingesting a string
:return: valid_string
'''
valid_string = ''
try:
valid_string = self._validate_string(input_string, path_to_root)
except:
rules_path_to... |
python | def connection_cache(func: callable):
"""Connection cache for SSH sessions. This is to prevent opening a
new, expensive connection on every command run."""
cache = dict()
lock = RLock()
@wraps(func)
def func_wrapper(host: str, username: str, *args, **kwargs):
key = "{h}-{u}".format(h=h... |
java | public void store(Object key, Object value) {
getJdbcTemplate().update(getMergeSql(),
new BeanPropertySqlParameterSource(value));
} |
java | public void end() {
ProfilingTimerNode currentNode = current.get();
if (currentNode != null) {
currentNode.stop();
current.set(currentNode.parent);
}
} |
python | def get_sections(self, s, base,
sections=['Parameters', 'Other Parameters']):
"""
Method that extracts the specified sections out of the given string if
(and only if) the docstring follows the numpy documentation guidelines
[1]_. Note that the section either must app... |
java | public RunList<R> node(final Node node) {
return filter(new Predicate<R>() {
public boolean apply(R r) {
return (r instanceof AbstractBuild) && ((AbstractBuild)r).getBuiltOn()==node;
}
});
} |
python | def info(name):
'''Show the information of the given virtual folder.
NAME: Name of a virtual folder.
'''
with Session() as session:
try:
result = session.VFolder(name).info()
print('Virtual folder "{0}" (ID: {1})'
.format(result['name'], result['id']))
... |
java | @edu.umd.cs.findbugs.annotations.SuppressWarnings(
value="NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE",
justification="Checked in precondition")
static Path pathForDataset(Path root, @Nullable String namespace, @Nullable String name) {
Preconditions.checkNotNull(namespace, "Namespace cannot be... |
java | public NamespaceContext buildContext(Message receivedMessage, Map<String, String> namespaces) {
SimpleNamespaceContext simpleNamespaceContext = new SimpleNamespaceContext();
//first add default namespace definitions
if (namespaceMappings.size() > 0) {
simpleNamespaceContext.... |
java | public void setDefault() {
try {
TelephonyManager telephonyManager = (TelephonyManager) getContext().getSystemService(Context.TELEPHONY_SERVICE);
String phone = telephonyManager.getLine1Number();
if (phone != null && !phone.isEmpty()) {
this.setNumber(phone);
... |
python | def get_minimum_needs(self):
"""Get the minimum needed information about the minimum needs.
That is the resource and the amount.
:returns: minimum needs
:rtype: OrderedDict
"""
minimum_needs = OrderedDict()
for resource in self.minimum_needs['resources']:
... |
python | def to_array(self):
"""
Serializes this InputMediaAnimation to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(InputMediaAnimation, self).to_array()
# 'type' given by superclass
# 'media' given by superclass... |
python | def p_rule(self, rule):
'''rule : GUIDELINE
| REGULATION'''
if len(rule[1]) == 4:
# This is a guideline
rule[0] = Guideline(rule[1][1], rule[1][2], rule[1][3])
else:
# This is a regulation
indentsize = rule[1][0]
number ... |
python | def offset_to_line(self, offset):
"""
Converts 0-based character offset to pair (line, col) of 1-based line and 0-based column
numbers.
"""
offset = max(0, min(self._text_len, offset))
line_index = bisect.bisect_right(self._line_offsets, offset) - 1
return (line_index + 1, offset - self._lin... |
python | def heartbeat(self):
"""Heartbeat request to keep session alive.
"""
unique_id = self.new_unique_id()
message = {
'op': 'heartbeat',
'id': unique_id,
}
self._send(message)
return unique_id |
java | @JsonIgnore
public void setUnknownFields(final Map<String,Object> unknownFields) {
this.unknownFields.clear();
this.unknownFields.putAll(unknownFields);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.