language stringclasses 2
values | func_code_string stringlengths 63 466k |
|---|---|
python | def prepare_buckets(self):
"""
loads buckets to bucket cache.
"""
for mdl in self.registry.get_base_models():
bucket = mdl(super_context).objects.adapter.bucket
self.buckets[bucket.name] = bucket |
python | def get_id2gos(self, **kws):
"""Return associations as a dict: id2gos"""
return self._get_id2gos(self.associations, **kws) if kws else self.id2gos |
python | def run(self):
"""Run command."""
files = self.__zipped_files_data
hashes = {}
icons = {}
# Read icons.json (from the webfont zip download)
data = json.loads(files['icons.json'])
# Group icons by style, since not all icons exist for all styles:
for icon,... |
python | def _subscribe_helper(self, msg):
# TODO: error log? sometimes it's just a subscription notice
if len(msg) == 1:
debug = ' Len message == 1: %s'
self._messaging_logger.subscribe.debug(debug, msg)
return
msg = _decode_vex_msg(msg)
"""
self._mes... |
java | private void handleAllRoots() {
int totalFound = 0;
double r = 1;
int iter = 0;
// increase the search region centered around 0 until at least one root has been found
while( iter++ < maxBoundIterations && (totalFound=sturm.countRealRoots(-r,r)) <= 0 ) {
r = 2*r*r;
}
if( Double.isInfinite(r) )
throw... |
python | def set_tlsio(self, hostname, port, http_proxy):
"""Setup the default underlying TLS IO layer. On Windows this is
Schannel, on Linux and MacOS this is OpenSSL.
:param hostname: The endpoint hostname.
:type hostname: bytes
:param port: The TLS port.
:type port: int
... |
python | async def _get_login_page(self):
"""Go to the login page."""
try:
async with async_timeout.timeout(10):
raw_res = await self._session.get(HOME_URL,
allow_redirects=False,
timeo... |
python | def _kernel_versions_redhat():
'''
Name of the last installed kernel, for Red Hat based systems.
Returns:
List with name of last installed kernel as it is interpreted in output of `uname -a` command.
'''
kernel_get_last = __salt__['cmd.run']('rpm -q --last kernel')
kernels = []
... |
java | public org.valkyriercp.binding.validation.ValidationResults validate(Object object) {
return validate(object, null);
} |
java | public static void sendExceptionToClient(Throwable throwable, String probeId,
Conversation conversation, int requestNumber) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(tc, "sendExceptionToClient",
... |
python | def export_html(self, pathname):
"""
Export notebook to .html file
:param pathname: output filename
:return:
"""
html_exporter = HTMLExporter()
(body, resources) = html_exporter.from_notebook_node(self.nb)
if pathname == '-':
sys.__stdout__.... |
python | def get_setup(cls):
"""Get package setup."""
try:
with open("setup.py") as f:
return SetupVisitor(ast.parse(f.read()))
except IOError as e:
LOG.warning("Couldn't open setup file: %s", e)
return SetupVisitor(ast.parse("")) |
python | def take_samples(self, sample_hz, sample_num, sample_offset=0, live=False):
"""Take samples of the current value supplied by monsoon.
This is the actual measurement for power consumption. This function
blocks until the number of samples requested has been fulfilled.
Args:
h... |
python | def create_yarn_application_diagnostics_bundle(self, application_ids, ticket_number=None, comments=None):
"""
Collects the Diagnostics data for Yarn applications.
@param application_ids: An array of strings containing the ids of the
yarn applications.
@param ticket_number: I... |
python | def tmpl_ifdef(self, field, trueval=u'', falseval=u''):
"""If field exists return trueval or the field (default) otherwise,
emit return falseval (if provided).
* synopsis: ``%ifdef{field}``, ``%ifdef{field,text}`` or \
``%ifdef{field,text,falsetext}``
* description: If field... |
java | public long getCreationTime() {
if (!_iSess.isValid())
throw new IllegalStateException();
long value = 0;
if (_iSess != null) {
value = _iSess.getCreationTime();
}
return value;
} |
java | @Override
public EEnum getIfcProjectOrderTypeEnum() {
if (ifcProjectOrderTypeEnumEEnum == null) {
ifcProjectOrderTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(1038);
}
return ifcProjectOrderTypeEnumEEnum;
} |
java | public boolean hasValue(String fieldName) {
return resultMap.containsKey(fieldName) && resultMap.get(fieldName) != null;
} |
python | def md5(text):
"""Returns the md5 hash of a string."""
h = hashlib.md5()
h.update(_unicode(text).encode("utf-8"))
return h.hexdigest() |
python | def get_views(self, app_id, include_standard_views=False):
"""
Get all of the views for the specified app
:param app_id: the app containing the views
:param include_standard_views: defaults to false. Set to true if you wish to include standard views.
"""
include_standard... |
python | def dfs_preorder(self, reverse=False):
"""Generator that returns each element of the tree in Preorder order.
Keyword arguments:
reverse -- if true, the search is done from right to left."""
stack = deque()
stack.append(self)
while stack:
node = stack.pop()
... |
java | public void marshall(GetVoiceChannelRequest getVoiceChannelRequest, ProtocolMarshaller protocolMarshaller) {
if (getVoiceChannelRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getVoiceChann... |
python | def to_protobuf(self) -> SaveStateProto:
"""
Create protobuf item.
:return: protobuf structure
:rtype: ~unidown.plugin.protobuf.save_state_pb2.SaveStateProto
"""
result = SaveStateProto()
result.version = str(self.version)
result.last_update.CopyFrom(date... |
java | private void auditPublicSequence(final long nextPublicSequnceNumber) {
if(publicSequence == -1) {
publicSequence = nextPublicSequnceNumber;
return;
}
if(publicSequence + 1 != nextPublicSequnceNumber) {
final String errorMessage = String.format(
"Got %d as next public sequence number, expected %d"... |
python | def get_values(self, field_name: str) -> List[object]:
"""
Get a list of all the values of a field.
Args:
field_name:
Returns: the list of values (not the keys)
"""
result = list()
if self.validate_field(field_name):
for value_key in sel... |
python | def write_dag(self, out=sys.stdout):
"""Write info for all GO Terms in obo file, sorted numerically."""
for rec in sorted(self.values()):
print(rec, file=out) |
java | public static Logger getLog(Class<?> clazz)
{
synchronized (LOGS)
{
if (SLF4J_ENABLED)
return LoggerFactory.getLogger(clazz);
return LOGS.computeIfAbsent(clazz.getName(), (n) -> new SimpleLogger(clazz.getSimpleName()));
}
} |
python | def check_weather(self):
'''
Query the configured/queried station and return the weather data
'''
if self.station_id is None:
# Failed to get the nearest station ID when first launched, so
# retry it.
self.get_station_id()
self.data['update_er... |
python | def get_aggs(self):
"""
Compute the values for single valued aggregations
:returns: the single aggregation value
"""
res = self.fetch_aggregation_results()
if 'aggregations' in res and 'values' in res['aggregations'][str(self.parent_agg_counter - 1)]:
try:
... |
python | def _CompileTemplate(
template_str, builder, meta='{}', format_char='|', default_formatter='str',
whitespace='smart'):
"""Compile the template string, calling methods on the 'program builder'.
Args:
template_str: The template string. It should not have any compilation
options in the ... |
java | public static void verifyValueBounds(DateTimeFieldType fieldType,
int value, int lowerBound, int upperBound) {
if ((value < lowerBound) || (value > upperBound)) {
throw new IllegalFieldValueException
(fieldType, Integer.valueOf(value),
... |
python | def set(self, uuid, content, encoding="utf-8"):
# type: (UUID, Any, Optional[Text]) -> None
"""Store binary content with uuid as key.
:param:uuid: :class:`UUID` instance
:param:content: string, bytes, or any object with a `read()` method
:param:encoding: encoding to use when con... |
python | def install():
"""Basic Ceph client installation."""
ceph_dir = "/etc/ceph"
if not os.path.exists(ceph_dir):
os.mkdir(ceph_dir)
apt_install('ceph-common', fatal=True) |
java | public static <K, V> LinkedOptionalMap<K, V> optionalMapOf(Map<K, V> sourceMap, Function<K, String> keyNameGetter) {
LinkedHashMap<String, KeyValue<K, V>> underlyingMap = new LinkedHashMap<>(sourceMap.size());
sourceMap.forEach((k, v) -> {
String keyName = keyNameGetter.apply(k);
underlyingMap.put(keyName, ... |
python | def set_widgets(self):
"""Set widgets on the Source tab."""
# Just set values based on existing keywords
source = self.parent.get_existing_keyword('source')
if source or source == 0:
self.leSource.setText(source)
else:
self.leSource.clear()
source... |
java | public void marshall(TrafficRoute trafficRoute, ProtocolMarshaller protocolMarshaller) {
if (trafficRoute == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(trafficRoute.getListenerArns(), LISTENERARN... |
java | @Restricted(DoNotUse.class)
public AutoCompletionCandidates doAutoCompleteCopyNewItemFrom(@QueryParameter final String value, @AncestorInPath ItemGroup<?> container) {
AutoCompletionCandidates candidates = AutoCompletionCandidates.ofJobNames(TopLevelItem.class, value, container);
if (container insta... |
java | protected void close() throws IOException {
synchronized(fdLock) {
if (fd != null && fd.valid()) {
if (!stream) {
ResourceManager.afterUdpClose();
}
if (closePending) {
return;
}
clo... |
java | public SendRequest getSendRequest() {
Transaction tx = new Transaction(params);
for (Protos.Output output : paymentDetails.getOutputsList())
tx.addOutput(new TransactionOutput(params, tx, Coin.valueOf(output.getAmount()), output.getScript().toByteArray()));
return SendRequest.forTx(t... |
java | private void translatePreconditionMacros(WyilFile.Decl.FunctionOrMethod declaration) {
Tuple<WyilFile.Expr> invariants = declaration.getRequires();
//
for (int i = 0; i != invariants.size(); ++i) {
// Construct fresh environment for this macro. This is necessary to
// avoid name clashes with subsequent macr... |
java | public static byte updateBlock(byte[] data, int len, byte crc) {
for (int i = 0; i < len; i++)
crc = CRC8_TABLE[crc ^ data[i]];
return crc;
} |
java | @Override
public void cacheResult(List<CPOption> cpOptions) {
for (CPOption cpOption : cpOptions) {
if (entityCache.getResult(CPOptionModelImpl.ENTITY_CACHE_ENABLED,
CPOptionImpl.class, cpOption.getPrimaryKey()) == null) {
cacheResult(cpOption);
}
else {
cpOption.resetOriginalValues();
}
... |
java | public final StringSubject hasMessageThat() {
StandardSubjectBuilder check = check("getMessage()");
if (actual() instanceof ErrorWithFacts && ((ErrorWithFacts) actual()).facts().size() > 1) {
check =
check.withMessage(
"(Note from Truth: When possible, instead of asserting on the f... |
java | public void checkMessages(XMLFile messagesDoc) throws DocumentException {
// Detector elements must all have a class attribute
// and details child element.
for (Iterator<Node> i = messagesDoc.xpathIterator("/MessageCollection/Detector"); i.hasNext();) {
Node node = i.next();
... |
java | public static EncodingUtil getInstance() {
if (instance == null) {
synchronized (EncodingUtilImpl.class) {
if (instance == null) {
EncodingUtilImpl util = new EncodingUtilImpl();
util.initialize();
instance = util;
}
}
}
return instance;
} |
python | def inner(self):
"""
:returns: the underlying Docker model object
"""
if not self.created:
raise RuntimeError(
'{} not created yet.'.format(self.__model_type__.__name__))
return self._inner |
python | def _policy_psets(policy_instances):
"""Find all permission sets making use of all of a list of policy_instances.
The input is an array of policy instances.
"""
if len(policy_instances) == 0:
# Special case: find any permission sets that don't have
# associated policy instances.
... |
java | public XSDocument addList(String itemTypeNS, String itemTypeLocalpart) throws SAXException{
xml.startElement(URI_XSD, "list");
xml.addAttribute("itemType", xml.toQName(itemTypeNS, itemTypeLocalpart));
xml.endElement();
return this;
} |
java | @Given("^I( do not)? set sso token using host '(.+?)' with user '(.+?)' and password '(.+?)'( and tenant '(.+?)')?$")
public void setGoSecSSOCookie(String set, String ssoHost, String userName, String passWord, String foo, String tenant) throws Exception {
if (set == null) {
HashMap<String, Strin... |
java | protected void sendMessage(byte[] msg) throws SshException {
try {
Packet pkt = createPacket();
pkt.write(msg);
sendMessage(pkt);
} catch (IOException ex) {
throw new SshException(SshException.UNEXPECTED_TERMINATION, ex);
}
} |
java | public java.util.List<String> getPublicIps() {
if (publicIps == null) {
publicIps = new com.amazonaws.internal.SdkInternalList<String>();
}
return publicIps;
} |
java | public void alias( double value , String name ) {
if( isReserved(name))
throw new RuntimeException("Reserved word or contains a reserved character. '"+name+"'");
VariableDouble old = (VariableDouble)variables.get(name);
if( old == null ) {
variables.put(name, new Variabl... |
java | private Collection<String> createEnabledByQuery() {
Collection<String> query = new ArrayList<String>();
String temp = "";
//generate queries
temp = "wlpInformation.requireFeature=";
temp += getProvideFeature();
String version = findVersion();
if (version != null)... |
python | def get_configuration(self):
"""Returns a mapping of UID -> configuration
"""
mapping = {}
settings = self.get_settings()
for record in self.context.getAnalyses():
uid = record.get("service_uid")
setting = settings.get(uid, {})
config = {
... |
python | def aux_dict(self):
"""Get dictionary representation of auxiliary states arrays.
Returns
-------
aux_dict : dict of str to NDArray
The dictionary that maps name of auxiliary states to NDArrays.
Raises
------
ValueError : if there are duplicated names... |
java | @Override
public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws IOException {
String action;
if ((action = req.getParams().get(PARAM_ACTION)) != null) {
// generate list of files
if (action.equals(ACTION_CONFIG_FILES)) {
String configDir = req.getCore().getResou... |
python | def visit(spht, node):
"""Append opening tags to document body list.
:param sphinx.writers.html.SmartyPantsHTMLTranslator spht: Object to modify.
:param sphinxcontrib.imgur.nodes.ImgurJavaScriptNode node: This class' instance.
"""
html_attrs_bq = {'async': '', 'src': '//s.imgur.... |
python | def get_repo_config(self, repo='default'):
"""Retrieve configuration for a given repository.
Args:
repo (str): a repository "realm" (alias) or its URL
Returns:
RepositoryConfig: if there is configuration for that repository
None: otherwise
"""
... |
python | def simple_predictive_probability(self, M_c, X_L, X_D, Y, Q):
"""Calculate probability of a cell taking a value given a latent state.
:param Y: A list of constraints to apply when querying. Each constraint
is a triplet of (r, d, v): r is the row index, d is the column
index and... |
java | protected final Token consumeToken(Symbol expected) throws ScanException, ParseException {
if (token.getSymbol() != expected) {
fail(expected);
}
return consumeToken();
} |
python | def random_state(qubits: Union[int, Qubits]) -> State:
"""Return a random state from the space of N qubits"""
N, qubits = qubits_count_tuple(qubits)
ket = np.random.normal(size=([2] * N)) \
+ 1j * np.random.normal(size=([2] * N))
return State(ket, qubits).normalize() |
python | def add_candidate_peer_endpoints(self, peer_endpoints):
"""Adds candidate endpoints to the list of endpoints to
attempt to peer with.
Args:
peer_endpoints ([str]): A list of public uri's which the
validator can attempt to peer with.
"""
if self._topol... |
python | def mea_approximation(model, max_order, closure='scalar', *closure_args, **closure_kwargs):
r"""
A wrapper around :class:`~means.approximation.mea.moment_expansion_approximation.MomentExpansionApproximation`.
It performs moment expansion approximation (MEA) up to a given order of moment.
See :class:... |
java | protected ChatGlyph getHistorySubtitle (int index, Graphics2D layoutGfx)
{
// do a brute search (over a small set) for an already-created subtitle
for (int ii = 0, nn = _showingHistory.size(); ii < nn; ii++) {
ChatGlyph cg = _showingHistory.get(ii);
if (cg.histIndex == index)... |
java | public static String getProperty(ArgumentUnit argumentUnit, String propertyName)
{
Properties properties = ArgumentUnitUtils.getProperties(argumentUnit);
return (String) properties.get(propertyName);
} |
java | public void addGroupBy(String fieldName)
{
if (fieldName != null)
{
m_groupby.add(new FieldHelper(fieldName, false));
}
} |
java | public boolean needsMigration(Path pathToVault, String masterkeyFilename) throws IOException {
Path masterKeyPath = pathToVault.resolve(masterkeyFilename);
byte[] keyFileContents = Files.readAllBytes(masterKeyPath);
KeyFile keyFile = KeyFile.parse(keyFileContents);
return keyFile.getVersion() < Constants.VAULT_... |
python | def with_default_context(cls,
use_empty_init=False,
global_default_factory=None):
"""
:param use_empty_init: If set to True, object constructed without
arguments will be a global default object of the class.
:param global_default_factory: Function that constructs a global
... |
python | def __get_total_response_time(meta_datas_expanded):
""" caculate total response time of all meta_datas
"""
try:
response_time = 0
for meta_data in meta_datas_expanded:
response_time += meta_data["stat"]["response_time_ms"]
return "{:.2f}".format(response_time)
excep... |
java | public DescribeScheduledActionsResult withScheduledActions(ScheduledAction... scheduledActions) {
if (this.scheduledActions == null) {
setScheduledActions(new java.util.ArrayList<ScheduledAction>(scheduledActions.length));
}
for (ScheduledAction ele : scheduledActions) {
... |
java | public String getFullyQualifiedMethodName() {
if (!visitingMethod) {
throw new IllegalStateException("getFullyQualifiedMethodName called while not visiting method");
}
if (fullyQualifiedMethodName == null) {
getMethodName();
getDottedMethodSig();
S... |
python | def origin_mexico(origin):
"""\
Returns if the origin is Mexico.
`origin`
The origin to check.
"""
return origin in (u'CIUDADJUAREZ', u'GUADALAJARA', u'HERMOSILLO',
u'MATAMOROS', u'MERIDA', u'MEXICO', u'MONTERREY',
u'NOGALES',
... |
java | @Override
public SortedMap<String, Meter> getMeters(MetricFilter filter) {
return getSimplyNamedMetrics(Meter.class, Optional.of(filter));
} |
java | private static Object saveBindings(FacesContext context,
Map<String, ValueExpression> bindings) {
// Note: This code is copied from UIComponentBase. In a future
// version of the JSF spec, it would be useful to define a
// attribute/property/bindings/stat... |
java | public List<CmsProject> getAllAccessibleProjects(
CmsDbContext dbc,
CmsOrganizationalUnit orgUnit,
boolean includeSubOus)
throws CmsException {
Set<CmsProject> projects = new HashSet<CmsProject>();
// get the ous where the user has the project manager role
List<CmsO... |
java | public AbstractPubSubHub<ID, DATA> setMessageFactory(IMessageFactory<ID, DATA> messageFactory) {
this.messageFactory = messageFactory;
return this;
} |
java | void remove_document(int index)
{
ListIterator<Document<K>> listIterator = documents_.listIterator(index);
Document<K> document = listIterator.next();
listIterator.set(null);
composite_.sub_vector(document.feature());
} |
java | public void disableScheduling(String poolId, String nodeId, DisableComputeNodeSchedulingOption nodeDisableSchedulingOption, ComputeNodeDisableSchedulingOptions computeNodeDisableSchedulingOptions) {
disableSchedulingWithServiceResponseAsync(poolId, nodeId, nodeDisableSchedulingOption, computeNodeDisableScheduli... |
java | public InChIToStructure getInChIToStructure(String inchi, IChemObjectBuilder builder, List<String> options)
throws CDKException {
return (new InChIToStructure(inchi, builder, options));
} |
python | def summarize(group, fs=None, include_source=True):
"""
Tabulate and write the results of ComparisonBenchmarks to a file or standard out.
:param str group: name of the comparison group.
:param fs: file-like object (Optional)
"""
_line_break = '{0:-<120}\n'.format('')
... |
python | def custom_model(self, func):
""" Run custom model provided by user.
To Do,
1. Define custom function's parameters, its data types, and return types
Parameters
----------
func : function
Custom function
Returns
-------
dict
... |
python | def rbac_policy_create(request, **kwargs):
"""Create a RBAC Policy.
:param request: request context
:param target_tenant: target tenant of the policy
:param tenant_id: owner tenant of the policy(Not recommended)
:param object_type: network or qos_policy
:param object_id: object id of policy
... |
java | @Override
public void eUnset(int featureID)
{
switch (featureID)
{
case SimpleAntlrPackage.KEYWORD__VALUE:
setValue(VALUE_EDEFAULT);
return;
}
super.eUnset(featureID);
} |
java | public static String cleanPath(String path) throws InvalidPathException {
validatePath(path);
return FilenameUtils.separatorsToUnix(FilenameUtils.normalizeNoEndSeparator(path));
} |
python | def update_git_repo():
"""Because GitPython sucks (cmd.commit() hangs)
# pip install GitPython
# import git
# repo = git.Repo('.')
# g = git.cmd.Git('.')
# g.pull()
# g.push()
# g.commit()
"""
today
commands = """
git add docs/*.html
git add docs/images/
... |
python | def create_file_from_path(self, share_name, directory_name, file_name,
local_file_path, content_settings=None,
metadata=None, validate_content=False, progress_callback=None,
max_connections=2, timeout=None):
'''
Cr... |
java | public static long parseSpaceSize(String spaceSize) {
double alpha = 0.0001;
String ori = spaceSize;
String end = "";
int index = spaceSize.length() - 1;
while (index >= 0) {
if (spaceSize.charAt(index) > '9' || spaceSize.charAt(index) < '0') {
end = spaceSize.charAt(index) + end;
... |
java | public EEnum getFNDFtWdClass() {
if (fndFtWdClassEEnum == null) {
fndFtWdClassEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(35);
}
return fndFtWdClassEEnum;
} |
python | def _remove_account(self, accounts):
"""
:type accounts: Account|list[Account]
:param accounts: The accounts to be removed.
"""
for account in to_list(accounts):
if account not in self.accounts:
msg = 'attempt to remove unknown account %s' % account
... |
python | def build_groups(self):
"""
Generates the sql for the GROUP BY portion of the query
:return: the GROUP BY portion of the query
:rtype: str
"""
# check if there are any groupings
if len(self.groups):
groups = []
# get the group sql for eac... |
java | public ContainerDefinition withSystemControls(SystemControl... systemControls) {
if (this.systemControls == null) {
setSystemControls(new com.amazonaws.internal.SdkInternalList<SystemControl>(systemControls.length));
}
for (SystemControl ele : systemControls) {
this.syste... |
python | def t_REGULATION(self, token):
ur'(?P<indents>\s{4,})*-\s(?P<reg>[a-zA-Z0-9]+)\)\s*(?P<text>.+?[^ ])\n'
indents = token.lexer.lexmatch.group("indents")
indents = len(indents)/4 if indents else 0
reg = token.lexer.lexmatch.group("reg").decode("utf8")
text = token.lexer.lexmatch.gr... |
python | def resolve_value(value, types=type_registry):
"""
Returns the actual value for the given object, if it is a late-resolving object type.
If not, the value itself is simply returned.
:param value: Lazy object, registered type in :attr:`type_registry`, or a simple value. In the
latter case, the valu... |
python | def init_app(self, app, datastore=None, register_blueprint=None, **kwargs):
"""Initializes the Flask-Security extension for the specified
application and datastore implementation.
:param app: The application.
:param datastore: An instance of a user datastore.
:param register_blu... |
java | private static void printCodePointAsSurrogatePairHexDigits(Appendable out, int c)
throws IOException
{
for (final char unit : Character.toChars(c)) {
printCodePointAsFourHexDigits(out, unit);
}
} |
java | public int getIndexOfField(String fieldName) {
List<String> fnms = this.getFieldNames();
for (int i = 0; i < fnms.size(); i++) {
if (fnms.get(i).equals(fieldName))
return i;
}
return -1;
} |
java | public Date toDate(double x) {
if (Double.isNaN(x)) {
return null;
}
return new Date(Double.doubleToRawLongBits(x));
} |
java | public static IoBufferEx doEncode(IoBufferAllocatorEx<?> allocator, int flags, WsMessage message, int maskValue) {
final boolean mask = true;
IoBufferEx ioBuf = getBytes(allocator, flags, message);
ByteBuffer buf = ioBuf.buf();
boolean fin = message.isFin();
int remaining = buf.rema... |
java | public static String insert(String haystack, String needle, int index) {
StringBuffer val = new StringBuffer(haystack);
val.insert(index, needle);
return val.toString();
} |
python | def get(cls, user_id, client_id, token_type='', access_token=None):
"""Get RemoteToken for user.
:param user_id: The user id.
:param client_id: The client id.
:param token_type: The token type. (Default: ``''``)
:param access_token: If set, will filter also by access token.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.