language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def splitIntoLines(self, maxWidth, maxHeight, splitted=False): """ Split text into lines and calculate X positions. If we need more space in height than available we return the rest of the text """ self.lines = [] self.height = 0 self.maxWidth = self.width = maxWi...
java
public boolean insideRange(Calendar startDate, Calendar endDate) { // make a copy of the start time so that it is safe to modify it without // affecting the input parameter Calendar mutableStartDate = (Calendar)(startDate.clone()); return isInRange(mutableStartDate, endDate); }
python
def reject(self): """User rejected the rectangle.""" self.canvas.unsetMapTool(self.tool) if self.previous_map_tool != self.tool: self.canvas.setMapTool(self.previous_map_tool) self.tool.reset() self.extent_selector_closed.emit() super(ExtentSelectorDialog, sel...
java
public void marshall(RemoveTagsRequest removeTagsRequest, ProtocolMarshaller protocolMarshaller) { if (removeTagsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(removeTagsRequest.getResourc...
java
@XmlElementDecl(namespace = "http://www.ibm.com/websphere/wim", name = "cn") public JAXBElement<String> createCn(String value) { return new JAXBElement<String>(_Cn_QNAME, String.class, null, value); }
python
def confirmMapIdentity(self, subject, vendorSpecific=None): """See Also: confirmMapIdentityResponse() Args: subject: vendorSpecific: Returns: """ response = self.confirmMapIdentityResponse(subject, vendorSpecific) return self._read_boolean_response(...
java
public void insert_us(final DeviceData deviceData, final int[] argin) { final short[] val = new short[argin.length]; for (int i = 0 ; i<argin.length ; i++) { val[i] = (short) (argin[i] & 0xFFFF); } DevVarUShortArrayHelper.insert(deviceData.getAny(), val); }
python
def reset(self, align=8, clip=80, code=False, derive=False, detail=0, ignored=True, infer=False, limit=100, stats=0, stream=None): '''Reset options, state, etc. The available options and default values are: *align=8* -- size alignment ...
python
def init(self): """ Performs a clone or a fetch, depending on whether the repository has been previously cloned or not. """ if os.path.isdir(self.path): self.fetch() else: self.clone()
java
public Set<Page> getInlinks() { Session session = wiki.__getHibernateSession(); session.beginTransaction(); session.buildLockRequest(LockOptions.NONE).lock(hibernatePage); // Have to copy links here since getPage later will close the session. Set<Integer> pageIDs = new UnmodifiableArraySet<Integer>(hibernate...
java
private static String generateStorageObjectName(String topologyName, String filename) { return String.format("%s/%s", topologyName, filename); }
java
protected int createNonPersistentAutomaticTimers(String appName, String moduleName, List<AutomaticTimerBean> timerBeans) { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "createNonPersistentAutomaticTimers: " + moduleName); ...
java
public static void setDefaultValues(List<ProtocolConfiguration> protocol_configs, List<Protocol> protocols, StackType ip_version) throws Exception { InetAddress default_ip_address=Util.getNonLoopbackAddress(); if(default_ip_address == null) { log.warn(...
java
@Override public void validate() throws OpsGenieClientValidationException { super.validate(); if (username == null && id == null) throw OpsGenieClientValidationException.missingMultipleMandatoryProperty(OpsGenieClientConstants.API.USERNAME, OpsGenieClientConstants.API.ID); }
java
public static String formatLongitude(final Longitude longitude, final PointLocationFormatType formatType) throws FormatterException { if (longitude == null) { throw new FormatterException("No point location provided"); } if (formatType == null) { ...
java
public void fill(List<CmsSitemapEntryBean> entries) { clear(); for (CmsSitemapEntryBean entry : entries) { CmsLazyTreeItem item = createItem(entry); addWidgetToList(item); } m_initialized = true; onContentChange(); }
java
private boolean isEditorCompatible(A_CmsXmlContentValue schemaType) throws CmsXmlException { boolean result = false; I_CmsXmlContentHandler contentHandler = schemaType.getContentDefinition().getContentHandler(); // We don't care about the old editor for the 'inheritable' widget configuratio...
java
@SuppressWarnings("nls") private void load() { URL url = Version.class.getResource("version.properties"); if (url == null) { this.versionString = "Unknown"; this.versionDate = new Date().toString(); } else { allProperties = new Properties(); tr...
python
def dumps(self): r"""Convert the container to a string in latex syntax.""" content = self.dumps_content() if not content.strip() and self.omit_if_empty: return '' string = '' start = Command(self.latex_name, arguments=self.arguments, option...
java
static PrefsTransform getLanguageTransform(TypeName type) { String typeName = type.toString(); if (Integer.class.getCanonicalName().equals(typeName)) { return new IntegerPrefsTransform(true); } if (Boolean.class.getCanonicalName().equals(typeName)) { return new BooleanPrefsTransform(true); } if (Long...
python
def load_state_machine_from_path(base_path, state_machine_id=None): """Loads a state machine from the given path :param base_path: An optional base path for the state machine. :return: a tuple of the loaded container state, the version of the state and the creation time :raises ValueError: if the provi...
python
def contains_group(store, path=None): """Return True if the store contains a group at the given logical path.""" path = normalize_storage_path(path) prefix = _path_to_prefix(path) key = prefix + group_meta_key return key in store
java
public <T extends IGeneratorParameter<S>, S> S get(Class<T> paramType) { return getParameter(paramType).getValue(); }
python
def findFirst(self, tableClass, comparison=None, offset=None, sort=None, default=None): """ Usage:: s.findFirst(tableClass [, query arguments except 'limit']) Example:: class YourItemType(Item): a = integer() b = text()...
python
def ascii2h5(dat_fname, h5_fname): """ Converts from the original ASCII format of the Chen+ (2014) 3D dust map to the HDF5 format. Args: dat_fname (:obj:`str`): Filename of the original ASCII .dat file. h5_fname (:obj:`str`): Output filename to write the resulting HDF5 file to. """ ...
java
public void setFailed(java.util.Collection<BatchResultErrorEntry> failed) { if (failed == null) { this.failed = null; return; } this.failed = new com.amazonaws.internal.SdkInternalList<BatchResultErrorEntry>(failed); }
java
public JcsegServer registerHandler() { String basePath = this.getClass().getPackage().getName()+".controller"; AbstractRouter router = new DynamicRestRouter(basePath, MainController.class); router.addMapping("/extractor/keywords", KeywordsController.class); router.addMapping("/extrac...
java
public int appendCount(TimeUnit unit, boolean omitCount, boolean useDigitPrefix, int count, int cv, boolean useSep, String name, boolean last, StringBuffer sb) { if (cv == ECountVariant.HALF_FRACTION && dr.halves == null) { cv = ECo...
python
def GetScriptHashesForVerifying(self): """ Get the script hash used for verification. Raises: Exception: if the verification script is invalid, or no header could be retrieved from the Blockchain. Returns: list: with a single UInt160 representing the next consen...
java
public void setIndexInfo(String info) { //ns=phobos_sindex:set=longevity:indexname=str_100_idx:num_bins=1:bins=str_100_bin:type=TEXT:sync_state=synced:state=RW; //ns=test:set=Customers:indexname=mail_index_userss:bin=email:type=STRING:indextype=LIST:path=email:sync_state=synced:state=RW if (!info.isEmpty()) { ...
python
def t_defexpr_CONTINUE(self, t): r'[\\_]\r?\n' t.lexer.lineno += 1 t.value = t.value[1:] return t
python
def _AnalyzeFileObject(self, mediator, file_object): """Processes a file-like object with analyzers. Args: mediator (ParserMediator): mediates the interactions between parsers and other components, such as storage and abort signals. file_object (dfvfs.FileIO): file-like object to process....
python
def command_health(self): """Check package health """ if len(self.args) == 1 and self.args[0] == "health": PackageHealth(mode="").test() elif (len(self.args) == 2 and self.args[0] == "health" and self.args[1] == "--silent"): PackageHealth(mode=self...
java
Entry<String, Point2d[]> createEntry(final IAtomContainer container) { try { final int n = container.getAtomCount(); final int[] ordering = new int[n]; final String smiles = cansmi(container, ordering); // build point array that is in the canonical output order ...
java
private void flush(final Collection<Writer> writers) { for (Writer writer : writers) { try { writer.flush(); } catch (Exception ex) { InternalLogger.log(Level.ERROR, ex, "Failed to flush writer"); } } }
python
def clean_up_datetime(obj_map): """convert datetime objects to dictionaries for storage""" clean_map = {} for key, value in obj_map.items(): if isinstance(value, datetime.datetime): clean_map[key] = { 'year': value.year, 'month': value.month, ...
java
public void setResourceComplianceSummaryItems(java.util.Collection<ResourceComplianceSummaryItem> resourceComplianceSummaryItems) { if (resourceComplianceSummaryItems == null) { this.resourceComplianceSummaryItems = null; return; } this.resourceComplianceSummaryItems = n...
java
protected ISFSArray parseObjectArray(GetterMethodCover method, Object[] array) { return parseObjectArray(method.getReturnClass(), array); }
java
public Register getRegister(int index) { if (registers == null) { throw new IndexOutOfBoundsException("No registers defined!"); } if (index < 0) { throw new IndexOutOfBoundsException("Negative index: " + index); } if (index >= getWordCount()) { ...
python
def reduce(self, f): """ Reduces the elements of this RDD using the specified commutative and associative binary operator. Currently reduces partitions locally. >>> from operator import add >>> sc.parallelize([1, 2, 3, 4, 5]).reduce(add) 15 >>> sc.parallelize((2 ...
python
def adapt(obj, to_cls): """ Will adapt `obj` to an instance of `to_cls`. First sees if `obj` has an `__adapt__` method and uses it to adapt. If that fails it checks if `to_cls` has an `__adapt__` classmethod and uses it to adapt. IF that fails, MRO is used. If that fails, a `TypeError` is raise...
python
def _parse_disambiguate(disambiguatestatsfilename): """Parse disambiguation stats from given file. """ disambig_stats = [0, 0, 0] with open(disambiguatestatsfilename, "r") as in_handle: for i, line in enumerate(in_handle): fields = line.strip().split("\t") if i == 0: ...
python
def _sample_variant_file_in_population(x): """Check if a sample file is the same as the population file. This is true for batches where we don't extract into samples and do not run decomposition for gemini. '""" if "population" in x: a = _get_project_vcf(x) b = _get_variant_file(x, ...
python
def _guessunit(self): """Guess the unit of the period as the largest one, which results in an integer duration. """ if not self.days % 1: return 'd' elif not self.hours % 1: return 'h' elif not self.minutes % 1: return 'm' elif ...
python
def user_delete(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/users#delete-user" api_path = "/api/v2/users/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, method="DELETE", **kwargs)
java
@TargetApi(Build.VERSION_CODES.LOLLIPOP) private static Drawable getDrawable(Context context, @DrawableRes int drawableResId) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return context.getDrawable(drawableResId); } else { return context.getResources().getDr...
java
public static TimeZone toTimeZone(final DateTimeZone dtz) { TimeZone tz = new TimeZone() { @Override public void setRawOffset(int n) { throw new UnsupportedOperationException(); } @Override public boolean useDaylightTime() { ...
java
public Thread newThread(String name, Runnable task) { Assert.hasText(name, "Thread name must be specified"); Assert.notNull(task, "Thread task must not be null"); Thread thread = new Thread(getThreadGroup(), task, name); thread.setContextClassLoader(getContextClassLoader()); thread.setDaemon(isDae...
java
private void addContainerproperties() { /* Create HierarchicalContainer container */ container.addContainerProperty(SPUILabelDefinitions.NAME, String.class, null); container.addContainerProperty(SPUILabelDefinitions.VAR_CREATED_BY, String.class, null); container.addContainerProperty(SPUI...
java
private SegmentIdWithShardSpec getSegment( final InputRow row, final String sequenceName, final boolean skipSegmentLineageCheck ) throws IOException { synchronized (segments) { final DateTime timestamp = row.getTimestamp(); final SegmentIdWithShardSpec existing = getAppendableSegme...
python
async def download_file_by_id(self, file_id: base.String, destination=None, timeout: base.Integer = 30, chunk_size: base.Integer = 65536, seek: base.Boolean = True): """ Download file by file_id to destination if You want to au...
python
def materialize_entity(ctx, etype, unique=None): ''' Low-level routine for creating a BIBFRAME resource. Takes the entity (resource) type and a data mapping according to the resource type. Implements the Libhub Resource Hash Convention As a convenience, if a vocabulary base is provided in the context, c...
java
public QuestionStructure getMainPart(String question, List<edu.stanford.nlp.ling.Word> words) { QuestionStructure questionStructure = new QuestionStructure(); questionStructure.setQuestion(question); Tree tree = LP.apply(words); LOG.info("句法树: "); tree.pennPrint(); quest...
java
public void setTables(final List<Table> tables) { this.tablesMap.clear(); for (final Table table : tables) this.addTableConfig(table.getConfigEntry()); }
java
public SFBaseResultSet execute(String sql, Map<String, ParameterBindingDTO> parametersBinding, CallingMethod caller) throws SQLException, SFException { sanityCheckQuery(sql); session.injectedDelay(); ...
java
public static Type getAndCheckType(EntityDataModel entityDataModel, Class<?> javaType) { Type type = entityDataModel.getType(javaType); if (type == null) { throw new ODataSystemException("No type found in the entity data model for Java type: " + javaType.getName()); ...
java
public void packSymbols(int first, int end) { int src; int dest; boolean touched; dest = first; for (src = first; src < end; src++) { touched = renameSymbol(src, dest); if (touched) { dest++; } else { // src not...
python
def aes_encrypt(self, plain, sec_key, enable_b64=True): """ 使用 ``aes`` 加密数据, 并由 ``base64编码`` 加密后的数据 - ``sec_key`` 加密 ``msg``, 最后选择 ``是否由base64编码数据`` - msg长度为16位数, 不足则补 'ascii \\0' .. warning:: msg长度为16位数, 不足则补 'ascii \\0' :param plain: :type pl...
java
public static ProjectWriter getProjectWriter(String name) throws InstantiationException, IllegalAccessException { int index = name.lastIndexOf('.'); if (index == -1) { throw new IllegalArgumentException("Filename has no extension: " + name); } String extension = name.substring...
python
def prompt_file(prompt, default=None, must_exist=True, is_dir=False, show_default=True, prompt_suffix=': ', color=None): """ Prompt a filename using using glob for autocompetion. If must_exist is True (default) then you can be sure that the value returned is an existing filename or dir...
python
def analyze( self, trees: List[ET.ElementTree], comments: OrderedDict ) -> Dict: outputDict = {} ast = [] # Parse through the ast once to identify and grab all the functions # present in the Fortran file. for tree in trees: self.loadFunction(tree) ...
python
def fac2real(pp_file=None,factors_file="factors.dat",out_file="test.ref", upper_lim=1.0e+30,lower_lim=-1.0e+30,fill_value=1.0e+30): """A python replication of the PEST fac2real utility for creating a structure grid array from previously calculated kriging factors (weights) Parameters -----...
java
private String doKerberosAuth(HttpServletRequest request) throws HttpAuthenticationException { // Try authenticating with the http/_HOST principal if (httpUGI != null) { try { return httpUGI.doAs(new HttpKerberosServerAction(request, httpUGI)); } catch (Exception e) { LOG.info(...
java
private static OptionalEntity<BadWord> getEntity(final CreateForm form, final String username, final long currentTime) { switch (form.crudMode) { case CrudMode.CREATE: return OptionalEntity.of(new BadWord()).map(entity -> { entity.setCreatedBy(username); entit...
java
private boolean rule2(double sample) { if (!hasMean()) { return false; } if (sample > mean.getResult()) { if (rule2Count > 0) { ++rule2Count; } else { rule2Count = 1; } } else { if (rule2Count < ...
python
def create_html_select( options, name=None, selected=None, disabled=None, multiple=False, attrs=None, **other_attrs): """ Create an HTML select box. >>> print create_html_select(["foo", "bar"], selected="bar", name="baz") <select name="baz...
java
public static boolean toBoolean(final String str, final String trueString, final String falseString) { if (str == trueString) { return true; } else if (str == falseString) { return false; } else if (str != null) { if (str.equals(trueString)) { ...
java
public void setGlobalScopes(Iterable<GlobalScope> globalScopes) { this.globalScopes = Lists.newArrayList(Iterables.concat(globalScopes, serviceGlobalScopes)); }
python
def import_rsakey_from_private_pem(pem, scheme='rsassa-pss-sha256', password=None): """ <Purpose> Import the private RSA key stored in 'pem', and generate its public key (which will also be included in the returned rsakey object). In addition, a keyid identifier for the RSA key is generated. The objec...
java
void writeObjectStart() throws IOException { output.append('{'); currentIndent = currentIndent + indent; commaDepth++; commaState.set(commaDepth, false); }
java
public ServiceCall<Environment> createEnvironment(CreateEnvironmentOptions createEnvironmentOptions) { Validator.notNull(createEnvironmentOptions, "createEnvironmentOptions cannot be null"); String[] pathSegments = { "v1/environments" }; RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructH...
python
def api(server, command, *args, **kwargs): ''' Call the Spacewalk xmlrpc api. CLI Example: .. code-block:: bash salt-run spacewalk.api spacewalk01.domain.com systemgroup.create MyGroup Description salt-run spacewalk.api spacewalk01.domain.com systemgroup.create arguments='["MyGroup", ...
java
public final void synpred38_DRL5Expressions_fragment() throws RecognitionException { // src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:654:9: ( DOT ID ) // src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:654:10: DOT ID { match(input,DOT,FOLLOW_DOT_in_synpred38_DRL5Expressions3848); ...
python
def dumps(value,encoding=None): """dumps(object,encoding=None) -> string This function dumps a python object as a tnetstring. """ # This uses a deque to collect output fragments in reverse order, # then joins them together at the end. It's measurably faster # than creating all the intermedi...
java
private void waitForCallback(final String uuid, final long timeout) throws TimeoutException { synchronized (lock) { this.message = null; this.hasTimeout = true; try { lock.wait(timeout); } catch (InterruptedException iex) { logger.warn("", iex); } // remove timed out callback if (thi...
java
public <R> Plan0<R> then(Func7<T1, T2, T3, T4, T5, T6, T7, R> selector) { if (selector == null) { throw new NullPointerException(); } return new Plan7<T1, T2, T3, T4, T5, T6, T7, R>(this, selector); }
java
private boolean hasOutputChanged(ChannelHandlerContext ctx, boolean first) { if (observeOutput) { // We can take this shortcut if the ChannelPromises that got passed into write() // appear to complete. It indicates "change" on message level and we simply assume // that there...
python
def interpolate(self, factor, minFont, maxFont, round=True, suppressError=True): """ Interpolate all possible data in the font. >>> font.interpolate(0.5, otherFont1, otherFont2) >>> font.interpolate((0.5, 2.0), otherFont1, otherFont2, round=False) Th...
java
public static <T extends Number & Comparable<?>> NumberOperation<T> numberOperation(Class<? extends T> type, Operator operator, Expression<?>... args) { return new NumberOperation<T>(type, operator, args); }
python
def export_polydata_str(obj, **kwargs): """ Saves control points or evaluated points in VTK Polydata format (string). Please see the following document for details: http://www.vtk.org/VTK/img/file-formats.pdf Keyword Arguments: * ``point_type``: **ctrlpts** for control points or **evalpts** for ev...
python
def create_storage_policy(policy_name, policy_dict, service_instance=None): ''' Creates a storage policy. Supported capability types: scalar, set, range. policy_name Name of the policy to create. The value of the argument will override any existing name in ``policy_dict``. ...
java
@Override public ChronoZonedDateTime<D> plus(long amountToAdd, TemporalUnit unit) { if (unit instanceof ChronoUnit) { return with(dateTime.plus(amountToAdd, unit)); } return ChronoZonedDateTimeImpl.ensureValid(getChronology(), unit.addTo(this, amountToAdd)); /// TODO: Generics ...
java
protected long getDelta (long timeStamp, long maxValue) { boolean even = (evenBase > oddBase); long base = even ? evenBase : oddBase; long delta = timeStamp - base; // make sure this timestamp is not sufficiently old that we can't // generate a delta time with it if ...
java
public static java.util.List<com.liferay.commerce.product.model.CPOption> getCPOptions( int start, int end) { return getService().getCPOptions(start, end); }
java
public UnicodeSet retainAll(UnicodeSet c) { checkFrozen(); retain(c.list, c.len, 0); strings.retainAll(c.strings); return this; }
java
private LinkedHashMap<String, String> getSortList(boolean includeType) { LinkedHashMap<String, String> list = new LinkedHashMap<String, String>(); list.put(SortParams.title_asc.name(), Messages.get().key(Messages.GUI_SORT_LABEL_TITLE_ASC_0)); list.put(SortParams.title_desc.name(), Messages.get(...
python
def is_sock_ok(self, timeout_select): """check if socket is OK""" self._socket_lock.acquire() try: ret = self._is_socket_ok(timeout_select) finally: self._socket_lock.release() return ret
python
def _list_audio_files(self, root, skip_rows=0): """Populates synsets - a map of index to label for the data items. Populates the data in the dataset, making tuples of (data, label) """ self.synsets = [] self.items = [] if not self._train_csv: # The audio files...
java
public PreparedStatement prepareStatement(final String sql) throws SQLException { return internalPrepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY, Statement.NO_GENERATED_KEYS); }
java
public static void unescapeJava(final String text, final Writer writer) throws IOException { if (writer == null) { throw new IllegalArgumentException("Argument 'writer' cannot be null"); } if (text == null) { return; } if (text.indexOf('\\') <...
python
def _request(self, url, method='GET', params=None, api_call=None, json_encoded=False): """Internal request method""" method = method.lower() params = params or {} func = getattr(self.client, method) if isinstance(params, dict) and json_encoded is False: params, files...
python
def _get_module_path(name, fail=False, install_path=None): """ Find the path to the jpy jni modules. """ import imp module = imp.find_module(name) if not module and fail: raise RuntimeError("can't find module '" + name + "'") path = module[1] if not path and fail: raise RuntimeE...
python
def next(self): """ Handles the next debug event. @see: L{cont}, L{dispatch}, L{wait}, L{stop} @raise WindowsError: Raises an exception on error. If the wait operation causes an error, debugging is stopped (meaning all debugees are either killed or detached fro...
java
public static boolean cholL( DMatrix5x5 A ) { A.a11 = Math.sqrt(A.a11); A.a12 = 0; A.a13 = 0; A.a14 = 0; A.a15 = 0; A.a21 = (A.a21)/A.a11; A.a22 = Math.sqrt(A.a22-A.a21*A.a21); A.a23 = 0; A.a24 = 0; A.a25 = 0; A.a31 = (A.a31)/A.a11...
java
public List<DbHistory> getPipePropertyHistory(String pipeName, String propertyName) throws DevFailed { return database.getClassPipePropertyHistory(className, pipeName, propertyName); }
java
public static int decodeInteger(ByteBuffer buf) { DerId id = DerId.decode(buf); if (!id.matches(DerId.TagClass.UNIVERSAL, DerId.EncodingType.PRIMITIVE, ASN1_INTEGER_TAG_NUM)) { throw new IllegalArgumentException("Expected INTEGER identifier, received " + id); } int len = DerU...
python
def import_lookup_class(lookup_class): """ Import lookup_class as a dotted base and ensure it extends LookupBase """ from selectable.base import LookupBase if isinstance(lookup_class, string_types): mod_str, cls_str = lookup_class.rsplit('.', 1) mod = import_module(mod_str) l...
python
def red(numbers): """Encode the deltas to reduce entropy.""" line = 0 deltas = [] for value in numbers: deltas.append(value - line) line = value return b64encode(compress(b''.join(chr(i).encode('latin1') for i in deltas))).decode('latin1')
python
def install(cls, uninstallable, prefix, path_items, root=None, warning=None): """Install an importer for modules found under ``path_items`` at the given import ``prefix``. :param bool uninstallable: ``True`` if the installed importer should be uninstalled and any imports it perfo...
python
def add_checkpoint(html_note, counter): """Recursively adds checkpoints to html tree. """ if html_note.text: html_note.text = (html_note.text + CHECKPOINT_PREFIX + str(counter) + CHECKPOINT_SUFFIX) else: html_note.text = (CHECKPOINT_PREFIX + str(counter) + ...