language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
@XmlElement(name = "pageRequest", required = true) @JsonProperty(value = "pageRequest", required = true) @ApiModelProperty(value = "The page request.", position = 1, required = true) @Override public PageRequestDto getPageRequest() { if (this.pageRequest == null) { this.pageRequest =...
python
def memory_map(self): """! @brief MemoryMap object.""" # Lazily construct the memory map. if self._memory_map is None: self._build_memory_regions() self._build_flash_regions() # Warn if there was no boot memory. if not self._saw_startup: ...
python
def _debug_mode_responses(self, request, response): """Extra functionality available in debug mode. - If pretty printed output was requested, force the content type to text. This causes the browser to not try to format the output in any way. - If SQL profiling is turned on, return a p...
python
def standard_settings(self): """Sets up standard settings for a nice visualization.""" cmd.set('bg_rgb', [1.0, 1.0, 1.0]) # White background cmd.set('depth_cue', 0) # Turn off depth cueing (no fog) cmd.set('cartoon_side_chain_helper', 1) # Improve combined visualization of sticks and ...
java
@Override protected void prepareActions() throws QTasteTestFailException { mIndex = Integer.parseInt(mData[0].toString()); if (component instanceof ComboBox) { ComboBox<?> combo = (ComboBox<?>) component; if (combo.getItems().size() < mIndex) { throw new QTast...
java
public JsonObject toJson() { JsonObject body = new JsonObject(); body.add(JsonRpcProtocol.ID, id()); if (isError()) { body.add(JsonRpcProtocol.ERROR, error().toJson()); } else { body.add(JsonRpcProtocol.RESULT, result()); } return body; }
java
public static int searchLast(long[] longArray, long value, int occurrence) { if(occurrence <= 0 || occurrence > longArray.length) { throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than " + "the array length: " + occurrence); } ...
python
def event_handlers(self): """ The list of handlers registered for this node. If the node is not a `Flow` and does not have its own list of `handlers` the handlers registered at the level of the flow are returned. This trick allows one to registered different handlers at the leve...
java
static Path resolvePath(final Path base, final String... paths) { return Paths.get(base.toString(), paths); }
python
def load_model(file_path): """ Loads an ONNX model to a ProtoBuf object. :param file_path: ONNX file (full file name) :return: ONNX model. Example: :: from onnxmltools.utils import load_model onnx_model = load_model("SqueezeNet.onnx") """ if not path.exists(file_path)...
python
def format(self): """Handles the actual behaviour involved with formatting. To change the behaviour, this method should be overridden. Returns -------- list A paginated output of the help command. """ values = {} title = "Description" ...
python
def get_filters(self, request, **resources): """ Make filters from GET variables. :return dict: filters """ filters = dict() if not self._meta.fields: return filters for field in request.GET.iterkeys(): tokens = field.split(LOOKUP_SEP) ...
python
def is_try(task, source_env_prefix): """Determine if a task is a 'try' task (restricted privs). This goes further than get_repo. We may or may not want to keep this. This checks for the following things:: * ``task.payload.env.GECKO_HEAD_REPOSITORY`` == "https://hg.mozilla.org/try/" *...
java
public static String[] expandArguments(String[] args) throws Exception { List<String> options = new ArrayList<String>(); for (int i = 0; i < args.length; i++) { if (args[i].equals(OPTIONS_FILE)) { if (i == args.length - 1) { throw new Exception("Missing o...
python
def add_developer_certificate(self, name, **kwargs): """Add a new developer certificate. :param str name: name of the certificate (Required) :param str description: Human readable description of this certificate, not longer than 500 characters. :returns: Certificate object ...
python
def apply_translation(self, translation): """ Translate the current mesh. Parameters ---------- translation : (3,) float Translation in XYZ """ translation = np.asanyarray(translation, dtype=np.float64) if translation.shape != (3,): ...
python
def noun_phrases_as_tokens(text): '''Generate a bag of lists of unnormalized tokens representing noun phrases from ``text``. This is built around python's nltk library for getting Noun Phrases (NPs). This is all documented in the NLTK Book http://www.nltk.org/book/ch03.html and blog posts that cite...
python
def load_last_visible_toolbars(self): """Loads the last visible toolbars from the .ini file.""" toolbars_names = CONF.get('main', 'last_visible_toolbars', default=[]) if toolbars_names: dic = {} for toolbar in self.toolbarslist: dic[toolbar.objectN...
java
@XmlElementDecl(namespace = "urn:oasis:names:tc:xacml:2.0:policy:schema:os", name = "Policy") public JAXBElement<PolicyType> createPolicy(PolicyType value) { return new JAXBElement<PolicyType>(_Policy_QNAME, PolicyType.class, null, value); }
java
public void marshall(ResourceInventory resourceInventory, ProtocolMarshaller protocolMarshaller) { if (resourceInventory == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(resourceInventory.getResourc...
python
def submit(self, command_line, name = None, array = None, dependencies = [], exec_dir = None, log_dir = "logs", dry_run = False, verbosity = 0, stop_on_failure = False, **kwargs): """Submits a job that will be executed in the grid.""" # add job to database self.lock() job = add_job(self.session, command...
python
def choose_database_name(metadata, config): """ Choose the database name to use. As a default, databases should be named after the service that uses them. In addition, database names should be different between unit testing and runtime so that there is no chance of a unit test dropping a real datab...
python
def FromStream(cls, stream): """Create a DataStreamSelector from a DataStream. Args: stream (DataStream): The data stream that we want to convert. """ if stream.system: specifier = DataStreamSelector.MatchSystemOnly else: specifier = DataStre...
java
Collection<LifecycleQueryInstalledChaincodesProposalResponse> lifecycleQueryInstalledChaincodes(LifecycleQueryInstalledChaincodesRequest lifecycleQueryInstalledChaincodesRequest, Collection<Peer> peers) throws InvalidArgumentException, ProposalException { logger.trace("LifecycleQueryInstalledChaincodes"); ...
python
def user_stats(request): """ JSON of user stats of the user GET parameters: html (bool): turn on the HTML version of the API, defaults to false user (int): identifier of the user, defaults to logged user concepts (list): list of identifiers of concepts, defaults to...
java
@Override public EClass getIfcColourSpecification() { if (ifcColourSpecificationEClass == null) { ifcColourSpecificationEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(103); } return ifcColourSpecificationEClass; }
python
def add_upsert(self, action, meta_action, doc_source, update_spec): """ Function which stores sources for "insert" actions and decide if for "update" action has to add docs to get source buffer """ # Whenever update_spec is provided to this method # it means that...
java
@ShellMethod(key = "generate-anonymous-user", value = "Generate an anonymous (persistent) username identifier") public void generateUsername( @ShellOption(value = {"username"}, help = "Authenticated username") final String username, @ShellOption(value = {"service"}, help = "S...
java
private void confirmMatchForDsTypeModel(ValidationResult result, DsTypeModel typeModel, String contentModelPid, ObjectInfo object) { String id = typeModel.getId(); Datastre...
python
def write(s, path, encoding="utf-8"): """Write string to text file. """ is_gzip = is_gzip_file(path) with open(path, "wb") as f: if is_gzip: f.write(zlib.compress(s.encode(encoding))) else: f.write(s.encode(encoding))
python
def response_type_is_in_registered_response_types(provider, authentication_request): """ Verifies that the requested response type is allowed for the client making the request. :param provider: provider instance :param authentication_request: authentication request to verify :raise InvalidAuthentica...
python
def origin(self): """Return an URL with scheme, host and port parts only. user, password, path, query and fragment are removed. """ # TODO: add a keyword-only option for keeping user/pass maybe? if not self.is_absolute(): raise ValueError("URL should be absolute") ...
python
def extend(self, other): """ Return a new HyperparameterDefaults instance containing the hyperparameters from the current instance combined with those from other. It is an error if self and other have any hyperparameters in common. """ overlap = [key for ...
python
def stringToTextValues(s, listSeparator=',', charList=None, strict=False): """ Returns list of strings. """ if charList is None: charList = escapableCharList def escapableChar (c): return c in charList def error(msg): if strict: raise ParseError(msg) ...
python
def matrix_transpose(m): """ Transposes the input matrix. The input matrix :math:`m` is a 2-dimensional array. :param m: input matrix with dimensions :math:`(n \\times m)` :type m: list, tuple :return: transpose matrix with dimensions :math:`(m \\times n)` :rtype: list """ num_cols = l...
java
@SuppressWarnings("unchecked") private void prepareListeners() { if (preparedListeners != null && preparedUnspecifiedListeners != null) { // Already created, skip return; } preparedListeners = new ConcurrentHashMap<>(); Stream<Class<? extends GloballyAttachabl...
python
def githubWebHookConsumer(self, *args, **kwargs): """ Consume GitHub WebHook Capture a GitHub event and publish it via pulse, if it's a push, release or pull request. This method is ``experimental`` """ return self._makeApiCall(self.funcinfo["githubWebHookConsu...
python
def do_exec(self, filename): """ :: Usage: exec FILENAME executes the commands in the file. See also the script command. Arguments: FILENAME The name of the file """ if not filename: Console.error("...
python
def filename(self): """ Build and return a filename from the various components. """ if self.buildver: buildver = '-' + self.buildver else: buildver = '' pyver = '.'.join(self.pyver) abi = '.'.join(self.abi) arch = '.'.join(self.arc...
java
@Override EntityManager getEMInvocationInfo(boolean requireTx, LockModeType mode) { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) { Tr.entry(tc, "getEMInvocationInfo : " + requireTx + " : " + ((mode == null) ? "null" : ...
java
static private void collectStats(double elapsedSec1,double elapsedSec2,List saved,List result,double[] stats) { stats[0] += elapsedSec1; stats[1] += elapsedSec2; Set fastVals = new HashSet(); Set slowVals = new HashSet(); for (int i=0; i<saved.size(); i++) { ...
java
static ZoneRules generateZoneRules(String zoneId) { TimeZone timeZone = TimeZone.getFrozenTimeZone(zoneId); // Assumption #0 verify(timeZone instanceof OlsonTimeZone, zoneId, "Unexpected time zone class " + timeZone.getClass()); OlsonTimeZone tz = (OlsonTimeZone) timeZone...
java
boolean addContext(boolean isRoot, Vector names, Mode mode) { if (modeMap == null) modeMap = new ContextMap(); return modeMap.put(isRoot, names, mode); }
java
public static <T extends MethodDescription> ElementMatcher.Junction<T> isOverriddenFromGeneric(ElementMatcher<? super TypeDescription.Generic> matcher) { return new MethodOverrideMatcher<T>(matcher); }
java
@SuppressWarnings("PMD.AvoidDeeplyNestedIfStmts") // agreed PMD, fixme private void clean(RallyCollector collector, List<RallyProject> existingProjects) { Set<ObjectId> uniqueIDs = new HashSet<>(); for (com.capitalone.dashboard.model.Component comp : dbComponentRepository.findAll()) { if (comp.getCollectorItems...
python
def raw_chroma_accuracy(ref_voicing, ref_cent, est_voicing, est_cent, cent_tolerance=50): """Compute the raw chroma accuracy given two pitch (frequency) sequences in cents and matching voicing indicator sequences. The first pitch and voicing arrays are treated as the reference (truth...
java
public void execute() { try { final IntermediateModel intermediateModel = new IntermediateModelBuilder(models, codeGenBinDirectory).build(); // Dump the intermediate model to a file writeIntermediateModel(intermediateModel); emitCode(intermed...
java
@SuppressWarnings("unchecked") public void commitValue(CmsWidgetDialog dialog) throws CmsException { if (m_baseCollection == null) { PropertyUtilsBean bean = new PropertyUtilsBean(); ConvertUtilsBean converter = new ConvertUtilsBean(); Object value = null; tr...
java
synchronized void startLogSegment(final long segmentTxId, boolean writeHeaderTxn) throws IOException { LOG.info("Starting log segment at " + segmentTxId); if (segmentTxId < 0) { throw new IOException("Bad txid: " + segmentTxId); } if (state != State.BETWEEN_LOG_SEGMENTS) { throw new IO...
java
public void visitDefault(GroovySourceAST t,int visit) { if (visit == OPENING_VISIT) { print(t,visit,"<" + tokenNames[t.getType()] + ">"); //out.print("<" + t.getType() + ">"); } else { print(t,visit,"</" + tokenNames[t.getType()] + ">"); //out.print("</" +...
java
protected void add(CmsResource resource, boolean check) throws IllegalArgumentException { if (check) { // it is essential that this method is only visible within the db package! if (resource.getState().isUnchanged()) { throw new CmsIllegalArgumentException( ...
java
public EClass getIfcStructuredDimensionCallout() { if (ifcStructuredDimensionCalloutEClass == null) { ifcStructuredDimensionCalloutEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(568); } return ifcStructuredDimensionCalloutEClass; }
java
public OvhFirewallNetworkRule ip_firewall_ipOnFirewall_rule_POST(String ip, String ipOnFirewall, OvhFirewallActionEnum action, Long destinationPort, OvhFirewallProtocolEnum protocol, OvhFirewallSequenceRangeEnum sequence, String source, Long sourcePort, OvhFirewallOptionTCP tcpOption) throws IOException { String qPat...
java
synchronized private JaspiConfig readConfigFile(final File configFile) throws PrivilegedActionException { if (tc.isEntryEnabled()) Tr.entry(tc, "readConfigFile", new Object[] { configFile }); if (configFile == null) { // TODO handle persistence // String msg = Message...
java
public static void removeSimilaritiesAndSaveFiles(List<String> filepathes, Log logging, Boolean isWindows) throws IOException { List<File> files = new LinkedList<File>(); for (String path : filepathes) { files.add(new File(path)); } FileComparer fcomparer; ...
java
boolean _close() throws SIResourceException { if (tc.isEntryEnabled()) SibTr.entry(tc, "_close"); boolean closedNow = false; // Indicate that this connection is closed. synchronized (this) { if (!_closed) closedNow = true; _closed = true; } // En...
python
def AddContract(self, contract): """ Add a contract to the database. Args: contract(neo.SmartContract.Contract): a Contract instance. """ super(UserWallet, self).AddContract(contract) try: db_contract = Contract.get(ScriptHash=contract.ScriptHash...
java
protected boolean parentExists(String path) throws IOException { // Assume root always has a parent if (isRoot(path)) { return true; } String parentKey = getParentPath(path); return parentKey != null && isDirectory(parentKey); }
java
public Class<?> getPropertyType() { Class<?> result = null; if (getter != null) { result = getter.getReturnType(); } else if (setter != null) { Class<?>[] parameterTypes = setter.getParameterTypes(); result = parameterTypes[0]; } return result;...
python
def getTemplate(self, uri, meta=None): """Return the template for an action. Cache the result. Can use an optional meta parameter with meta information""" if not meta: metaKey = self.cacheKey + '_templatesmeta_cache_' + uri meta = cache.get(metaKey, None) if not m...
java
@Override public void onDestroyView() { mHandler.removeCallbacks(mRequestFocus); mList = null; mListShown = false; mEmptyView = mProgressContainer = mListContainer = null; mStandardEmptyView = null; super.onDestroyView(); }
java
public Block getBlock(String sqlquery, Collection queryParams, int startIndex, int count) { return blockStrategy.getBlock(sqlquery, queryParams, startIndex, count); }
java
void error(int e) { String s = "Error " + e + " at line " + fLineNum + " column " + fCharNum; IllegalArgumentException ex = new IllegalArgumentException(s); throw ex; }
python
def client(self, id): """Returns the client object in the database given a certain id. Raises an error if that does not exist.""" return self.query(Client).filter(Client.id==id).one()
python
def get_size(vm_): ''' Return the VM's size. Used by create_node(). ''' sizes = avail_sizes() vm_size = six.text_type(config.get_cloud_config_value( 'size', vm_, __opts__, search_global=False )) for size in sizes: if vm_size.lower() == sizes[size]['slug']: return ...
java
public IfcWindowTypePartitioningEnum createIfcWindowTypePartitioningEnumFromString(EDataType eDataType, String initialValue) { IfcWindowTypePartitioningEnum result = IfcWindowTypePartitioningEnum.get(initialValue); if (result == null) throw new IllegalArgumentException( "The value '" + initialValue ...
python
def isNewerThan(self, other): """ Compare if the version of this app is newer that the other """ if self.getValue("name") == other.getValue("name"): if other.getValue("version"): if not other.getValue("version"): return False else: ...
java
protected void registerLabelAttributes() { addAttributeProcessor(new EllipsisLmlAttribute(), "ellipsis"); addAttributeProcessor(new LabelAlignmentLmlAttribute(), "labelAlign", "labelAlignment"); addAttributeProcessor(new LineAlignmentLmlAttribute(), "lineAlign", "lineAlignment"); addAttr...
python
def _set_overlay_service_policy_brief_state(self, v, load=False): """ Setter method for overlay_service_policy_brief_state, mapped from YANG variable /overlay_service_policy_brief_state (container) If this variable is read-only (config: false) in the source YANG file, then _set_overlay_service_policy_br...
python
def write_file(self, filename, contents): """ Write a text file and provide feedback to the user. :param filename: The pathname of the file to write (a string). :param contents: The new contents of the file (a string). """ logger.info("Writing file: %s", format_path(file...
java
protected boolean shouldAuthorize(Authentication authentication, Authorizable controlledObject) { Assert.state(getAccessDecisionManager() != null, "The AccessDecisionManager can not be null!"); boolean authorize = false; try { if (authentication != null) { ...
python
def updateFeatureService(self, efs_config): """Updates a feature service. Args: efs_config (list): A list of JSON configuration feature service details to update. Returns: dict: A dictionary of results objects. """ if self.securityhandler...
python
def cfht_megacam_tap_query(ra_deg=180.0, dec_deg=0.0, width=1, height=1, date=None): """Do a query of the CADC Megacam table. Get all observations inside the box (right now it turns width/height into a radius, should not do this). @rtype : Table @param ra_deg: center of search region, in degrees @...
java
protected EndpointInfo createEndpointInfo() throws BusException { String transportId = getTransportId(); if (transportId == null && getAddress() != null) { DestinationFactory df = getDestinationFactory(); if (df == null) { DestinationFactoryManager dfm = getBus()....
python
def always_iterable(obj, base_type=(str, bytes)): """If *obj* is iterable, return an iterator over its items:: >>> obj = (1, 2, 3) >>> list(always_iterable(obj)) [1, 2, 3] If *obj* is not iterable, return a one-item iterable containing *obj*:: >>> obj = 1 >>> list(alwa...
java
private static HeaderMap wrapMultiMap(MultiMap headers) { return new HeaderMap() { private static final long serialVersionUID = -1406124274678587935L; @Override() public String get(String key) { return headers.get(key); } }; }
java
public static <E, R extends Collection<E>> R all(Iterable<E> iterable, Supplier<R> supplier) { dbc.precondition(iterable != null, "cannot call all with a null iterable"); final Function<Iterator<E>, R> consumer = new ConsumeIntoCollection<>(supplier); return consumer.apply(iterable.iterator()); ...
python
def find_seq_id(block, name, case_sensitive=True): """Given part of a sequence ID, find the first actual ID that contains it. Example:: >>> find_seq_id(block, '2QG5') 'gi|158430190|pdb|2QG5|A' Raise a ValueError if no matching key is found. """ # logging.warn("DEPRECATED: Try to u...
python
def find_deadlocks(self): """ This function detects deadlocks Return: named tuple with the tasks grouped in: deadlocks, runnables, running """ # Find jobs that can be submitted and and the jobs that are already in the queue. runnables = [] for work in...
java
private static IAction createAction(String action) { IAction actn = null; if (!StringUtils.isEmpty(action)) { if ((actn = ActionRegistry.getRegisteredAction(action)) == null) { actn = ActionUtil.createAction(null, action); } } ret...
java
public Observable<String> getMetadataAsync(String scope) { return getMetadataWithServiceResponseAsync(scope).map(new Func1<ServiceResponse<String>, String>() { @Override public String call(ServiceResponse<String> response) { return response.body(); } }...
python
def _build_predict(self, Xnew, full_cov=False): """ Compute the mean and variance of the latent function at some new points Xnew. """ _, _, Luu, L, _, _, gamma = self._build_common_terms() Kus = features.Kuf(self.feature, self.kern, Xnew) # size M x Xnew w = tf...
python
def execute(self, triple_map, output, **kwargs): """Method executes mapping between CSV source and output RDF args: triple_map(SimpleNamespace): Triple Map """ subject = self.generate_term(term_map=triple_map.subjectMap, **kwargs)...
python
def from_dict(cls, copula_dict): """Set attributes with provided values.""" instance = cls() instance.fitted = copula_dict['fitted'] instance.constant_value = copula_dict['constant_value'] if instance.fitted and not instance.constant_value: instance.model = scipy.st...
python
def put(self, measurementId): """ Initiates a new measurement. Accepts a json payload with the following attributes; * duration: in seconds * startTime OR delay: a date in YMD_HMS format or a delay in seconds * description: some free text information about the measurement ...
java
public Observable<ContentKeyPolicyInner> createOrUpdateAsync(String resourceGroupName, String accountName, String contentKeyPolicyName, ContentKeyPolicyInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, contentKeyPolicyName, parameters).map(new Func1<ServiceRespons...
python
def put_bug(self, bugid, bug_update): '''http://bugzilla.readthedocs.org/en/latest/api/core/v1/bug.html#update-bug''' assert type(bug_update) is DotDict if (not 'ids' in bug_update): bug_update.ids = [bugid] return self._put('bug/{bugid}'.format(bugid=bugid), ...
python
def set(self, **kwargs): """Sets an internal setting for acquistion, using keywords. Available parameters to set: :param acqtime: duration of recording (input) window (seconds) :type acqtime: float :param aifs: sample rate of the recording (input) operation (Hz) ...
python
def install_plugin(pkgpath, plugin_type, install_path, register_func): """Install specified plugin. :param pkgpath: Name of plugin to be downloaded from online repo or path to plugin folder or zip file. :param install_path: Path where plugin will be installed. :param register_func: Method used to regis...
java
private void addParent(MavenPomDescriptor pomDescriptor, Model model, ScannerContext context) { Parent parent = model.getParent(); if (null != parent) { ArtifactResolver resolver = getArtifactResolver(context); MavenArtifactDescriptor parentDescriptor = resolver.resolve(new Paren...
python
def from_spcm(filepath, name=None, *, delimiter=",", parent=None, verbose=True) -> Data: """Create a ``Data`` object from a Becker & Hickl spcm file (ASCII-exported, ``.asc``). If provided, setup parameters are stored in the ``attrs`` dictionary of the ``Data`` object. See the `spcm`__ software hompage fo...
python
def _post(url:str, params:dict, headers:dict) -> dict: """ Make a POST call. """ response = requests.post(url, params=params, headers=headers) data = response.json() if response.status_code != 200 or "error" in data: raise GoogleApiError({"status_code": response.status_code, ...
java
private static int compressionLevel(int blockSize) { int compressionLevel = 32 - Integer.numberOfLeadingZeros(blockSize - 1); // ceil of log2 assert (1 << compressionLevel) >= blockSize; assert blockSize * 2 > (1 << compressionLevel); compressionLevel = Math.max(0, compressionLevel - COMPRESSION_LEVEL_BASE); ...
python
def is_writer(self, check_pending=True): """Returns if the caller is the active writer or a pending writer.""" me = self._current_thread() if self._writer == me: return True if check_pending: return me in self._pending_writers else: return Fals...
java
private static Stream<Class<?>> getSuperclassesAsStream(Class<?> clazz, boolean includeArgument) { return Stream.concat(includeArgument ? Stream.of(clazz) : Stream.empty(), Optional.ofNullable(clazz.getSuperclass()) .map(Stream::of) ...
python
def apply_dependencies(self, hosts): """Wrapper to loop over services and call Service.fill_daddy_dependency() :return: None """ for service in self: if service.host and service.host_dependency_enabled: host = hosts[service.host] if host.activ...
java
public int getIDFromCode(String strCode) { int iID = 0; try { iID = Integer.parseInt(strCode); // Special case - if an integer, just convert it. } catch (NumberFormatException ex) { iID = 0; } if (iID == 0) { Record record = t...
java
@Override public byte[] getBinaryValue(Base64Variant b64variant) throws IOException { Object n = currentNode(); if (n instanceof byte[]) { return (byte[]) n; } else if (n instanceof org.bson.types.ObjectId) { return ((org.bson.types.ObjectId) n).toByteArray(); ...
python
def _parse_content(self, text): '''Try to parse as HAL, but on failure use an empty dict''' try: return super(OrphanHALNavigator, self)._parse_content(text) except exc.UnexpectedlyNotJSON: return {}
python
def add_idle(self, callback, *args, **kwds): """Add an idle callback. An idle callback can return True, False or None. These mean: - None: remove the callback (don't reschedule) - False: the callback did no work; reschedule later - True: the callback did some work; reschedule soon If the cal...