8,037 Matching Annotations
  1. Aug 2022
    1. js function transclude(elementId) { var clone = document.getElementById(elementId).cloneNode(true), placeholder; clone.id = null; document.write('<br id="__placeholder__">'); placeholder = document.getElementById('__placeholder__'); placeholder.parentNode.insertBefore(clone, placeholder); placeholder.parentNode.removeChild(placeholder); return transclude; }

      ```html

      This is paragraph 1.

      This is paragraph 2.

      This is paragraph 3. It should contain paragraphs 1 and 2. <script>transclude("p1")("p2")</script>

      ```

    1. ```js / Adapted from: https://github.com/openannotation/annotator/blob/v1.2.x/src/plugin/document.coffee Annotator v1.2.10 https://github.com/openannotation/annotator Copyright 2015, the Annotator project contributors. Dual licensed under the MIT and GPLv3 licenses. https://github.com/openannotation/annotator/blob/master/LICENSE /

      /* * nb. The DocumentMetadata type is renamed to avoid a conflict with the * DocumentMetadata class below. * * @typedef {import('../../types/annotator').DocumentMetadata} Metadata /

      import { normalizeURI } from '../util/url';

      /* * @typedef Link * @prop {string} link.href * @prop {string} [link.rel] * @prop {string} [link.type] /

      /* * Extension of the Metadata type with non-optional fields for dc, eprints etc. * * @typedef HTMLDocumentMetadata * @prop {string} title * @prop {Link[]} link * @prop {Record<string, string[]>} dc * @prop {Record<string, string[]>} eprints * @prop {Record<string, string[]>} facebook * @prop {Record<string, string[]>} highwire * @prop {Record<string, string[]>} prism * @prop {Record<string, string[]>} twitter * @prop {string} [favicon] * @prop {string} [documentFingerprint] /

      / * HTMLMetadata reads metadata/links from the current HTML document. */ export class HTMLMetadata { / * @param {object} [options] * @param {Document} [options.document] */ constructor(options = {}) { this.document = options.document || document; }

      /* * Returns the primary URI for the document being annotated * * @return {string} / uri() { let uri = decodeURIComponent(this._getDocumentHref());

      // Use the `link[rel=canonical]` element's href as the URL if present.
      const links = this._getLinks();
      for (let link of links) {
        if (link.rel === 'canonical') {
          uri = link.href;
        }
      }
      
      return uri;
      

      }

      / * Return metadata for the current page. * * @return {HTMLDocumentMetadata} */ getDocumentMetadata() { / @type {HTMLDocumentMetadata} */ const metadata = { title: document.title, link: [],

        dc: this._getMetaTags('name', 'dc.'),
        eprints: this._getMetaTags('name', 'eprints.'),
        facebook: this._getMetaTags('property', 'og:'),
        highwire: this._getMetaTags('name', 'citation_'),
        prism: this._getMetaTags('name', 'prism.'),
        twitter: this._getMetaTags('name', 'twitter:'),
      };
      
      const favicon = this._getFavicon();
      if (favicon) {
        metadata.favicon = favicon;
      }
      
      metadata.title = this._getTitle(metadata);
      metadata.link = this._getLinks(metadata);
      
      const dcLink = metadata.link.find(link => link.href.startsWith('urn:x-dc'));
      if (dcLink) {
        metadata.documentFingerprint = dcLink.href;
      }
      
      return metadata;
      

      }

      / * Return an array of all the content values of <meta> tags on the page * where the value of the attribute begins with <prefix>. * * @param {string} attribute * @param {string} prefix - it is interpreted as a regex * @return {Record<string,string[]>} */ _getMetaTags(attribute, prefix) { / @type {Record<string,string[]>} */ const tags = {}; for (let meta of Array.from(this.document.querySelectorAll('meta'))) { const name = meta.getAttribute(attribute); const { content } = meta; if (name && content) { const match = name.match(RegExp(^${prefix}(.+)$, 'i')); if (match) { const key = match[1].toLowerCase(); if (tags[key]) { tags[key].push(content); } else { tags[key] = [content]; } } } } return tags; }

      /* @param {HTMLDocumentMetadata} metadata / _getTitle(metadata) { if (metadata.highwire.title) { return metadata.highwire.title[0]; } else if (metadata.eprints.title) { return metadata.eprints.title[0]; } else if (metadata.prism.title) { return metadata.prism.title[0]; } else if (metadata.facebook.title) { return metadata.facebook.title[0]; } else if (metadata.twitter.title) { return metadata.twitter.title[0]; } else if (metadata.dc.title) { return metadata.dc.title[0]; } else { return this.document.title; } }

      / * Get document URIs from <link> and <meta> elements on the page. * * @param {Pick<HTMLDocumentMetadata, 'highwire'|'dc'>} [metadata] - * Dublin Core and Highwire metadata parsed from <meta> tags. * @return {Link[]} */ _getLinks(metadata = { dc: {}, highwire: {} }) { / @type {Link[]} */ const links = [{ href: this._getDocumentHref() }];

      // Extract links from `<link>` tags with certain `rel` values.
      const linkElements = Array.from(this.document.querySelectorAll('link'));
      for (let link of linkElements) {
        if (
          !['alternate', 'canonical', 'bookmark', 'shortlink'].includes(link.rel)
        ) {
          continue;
        }
      
        if (link.rel === 'alternate') {
          // Ignore RSS feed links.
          if (link.type && link.type.match(/^application\/(rss|atom)\+xml/)) {
            continue;
          }
          // Ignore alternate languages.
          if (link.hreflang) {
            continue;
          }
        }
      
        try {
          const href = this._absoluteUrl(link.href);
          links.push({ href, rel: link.rel, type: link.type });
        } catch (e) {
          // Ignore URIs which cannot be parsed.
        }
      }
      
      // Look for links in scholar metadata
      for (let name of Object.keys(metadata.highwire)) {
        const values = metadata.highwire[name];
        if (name === 'pdf_url') {
          for (let url of values) {
            try {
              links.push({
                href: this._absoluteUrl(url),
                type: 'application/pdf',
              });
            } catch (e) {
              // Ignore URIs which cannot be parsed.
            }
          }
        }
      
        // Kind of a hack to express DOI identifiers as links but it's a
        // convenient place to look them up later, and somewhat sane since
        // they don't have a type.
        if (name === 'doi') {
          for (let doi of values) {
            if (doi.slice(0, 4) !== 'doi:') {
              doi = `doi:${doi}`;
            }
            links.push({ href: doi });
          }
        }
      }
      
      // Look for links in Dublin Core data
      for (let name of Object.keys(metadata.dc)) {
        const values = metadata.dc[name];
        if (name === 'identifier') {
          for (let id of values) {
            if (id.slice(0, 4) === 'doi:') {
              links.push({ href: id });
            }
          }
        }
      }
      
      // Look for a link to identify the resource in Dublin Core metadata
      const dcRelationValues = metadata.dc['relation.ispartof'];
      const dcIdentifierValues = metadata.dc.identifier;
      if (dcRelationValues && dcIdentifierValues) {
        const dcUrnRelationComponent =
          dcRelationValues[dcRelationValues.length - 1];
        const dcUrnIdentifierComponent =
          dcIdentifierValues[dcIdentifierValues.length - 1];
        const dcUrn =
          'urn:x-dc:' +
          encodeURIComponent(dcUrnRelationComponent) +
          '/' +
          encodeURIComponent(dcUrnIdentifierComponent);
        links.push({ href: dcUrn });
      }
      
      return links;
      

      }

      _getFavicon() { let favicon = null; for (let link of Array.from(this.document.querySelectorAll('link'))) { if (['shortcut icon', 'icon'].includes(link.rel)) { try { favicon = this._absoluteUrl(link.href); } catch (e) { // Ignore URIs which cannot be parsed. } } } return favicon; }

      /* * Convert a possibly relative URI to an absolute one. This will throw an * exception if the URL cannot be parsed. * * @param {string} url / _absoluteUrl(url) { return normalizeURI(url, this.document.baseURI); }

      // Get the true URI record when it's masked via a different protocol. // This happens when an href is set with a uri using the 'blob:' protocol // but the document can set a different uri through a <base> tag. _getDocumentHref() { const { href } = this.document.location; const allowedSchemes = ['http:', 'https:', 'file:'];

      // Use the current document location if it has a recognized scheme.
      const scheme = new URL(href).protocol;
      if (allowedSchemes.includes(scheme)) {
        return href;
      }
      
      // Otherwise, try using the location specified by the <base> element.
      if (
        this.document.baseURI &&
        allowedSchemes.includes(new URL(this.document.baseURI).protocol)
      ) {
        return this.document.baseURI;
      }
      
      // Fall back to returning the document URI, even though the scheme is not
      // in the allowed list.
      return href;
      

      } } ```

    1. yaml definitions: Annotation: type: object required: - user - uri properties: id: type: string description: Unique ID for this Annotation. uri: type: string description: URI which is the target of this Annotation. target: type: array items: - type: object properties: scope: type: array items: - type: string selector: type: array items: - type: object properties: type: description: Type of Selector--see Web Annotation Data Model. type: string source: type: string user: type: string description: User URI in the form of an `acct` prefixed URI. document: type: object description: Target document metadata schema: $ref: '#/definitions/DocumentMetadata' permissions: type: object description: Permissions for this Annotation. created: type: string format: date-time updated: type: string format: date-time AnnotationList: type: object properties: total: type: number rows: type: array items: $ref: '#/definitions/Annotation' DocumentMetadata: type: object properties: eprints: type: object title: type: string twitter: type: object properties: image:src: type: array items: type: string title: type: array items: type: string description: type: array items: type: string card: type: array items: type: string site: type: array items: type: string dc: type: object favicon: type: string prism: type: object highwire: type: object link: type: array items: type: object properties: href: type: string facebook: type: object properties: site_name: type: array items: type: string description: type: array items: type: string title: type: array items: type: string url: type: array items: type: string image: type: array items: type: string type: type: array items: type: string

    1. These are the key parameters.

      prop=revisions&rvprop=content&rvsection=0

      rvsection = 0 specifies to only return the lead section.

    1. For creating SXGs for testing purposes, you can create a self-signed certificate and enable chrome://flags/#allow-sxg-certs-without-extension to have your Chrome process the SXGs created with the certificate without the special extension.

      ```html

      <link rel="prefetch" href="https://your-site.com/sample.sxg" />

      Sample ```

    1. The clientHeight property returns the inner height of an element in pixels. The property includes padding but excludes borders, margins and horizontal scrollbars.Alternatively, you can use the offsetHeight property, which returns the height of the element in pixels, including vertical padding and borders.

      ```js useEffect(() => { setDivHeight(ref.current.offsetHeight); console.log('height: ', ref.current.offsetHeight);

      console.log('width: ', ref.current.offsetWidth); }, []); ```

    1. If your site is using multiple widgets you can set up Twitter widgets in your pages once, which will make your site faster, and widgets such as embedded Tweets will be more reliable for authors when using content management systems.

      ```html

      <script>window.twttr = (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0], t = window.twttr || {}; if (d.getElementById(id)) return t; js = d.createElement(s); js.id = id; js.src = "https://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs); t._e = []; t.ready = function(f) { t._e.push(f); }; return t; }(document, "script", "twitter-wjs"));</script>

      ```

    1. ```js export function Tweet({ tweetID, }) { const tweetRef = useRef(null); const [isLoading, setIsLoading] = useState(true);

      useEffect(() => { const tweetEl = tweetRef?.current if (window.twttr && tweetEl) (async() => { await window.twttr.ready(); await window.twttr.widgets.createTweet( tweetID, tweetEl, { align: 'center', conversation: 'none', dnt: true, } ); setIsLoading(false); console.log('Tweet loaded') })(); return () => { tweetEl?.remove(); } }, [tweetID, tweetRef]);

      return ( <div ref={tweetRef} className="w-full bg-gray-100 h-fit animate-fadeIn" id={tweetID}> {isLoading &&

      🐦

      } </div> ); }; ```

  2. Jul 2022
    1. A Solid Social Knowledge GraphBy networked these second brains together via the Fediverse, the MyHub.ai toolkit creates a distributed Social Knowledge Graph for each Hub Editor.

    2. Your Hub’s CMS: a Thinking Management System for writersEach Hub’s content management system (CMS) is actually a “Thinking Management System”: a thinking tool based on a Personal Knowledge Graph (PKG) which is custom-designed to support thinking and writing.

    1. ```js const versions = [ { version: 1, data: 1}, { version: 3, data: 3}, { version: 17, data: 17}, { version: 95, data: 95} ];

      function getNextVersion(v) { return versions.slice(0).reduceRight((a , b, i , arr) => b.version <= v ? (arr.length = 0, b) : b) } ```

    1. Here's a complete function that removes accents, replaces special characters with hyphens, also removing additional hyphens:

      ```js const replaceSpecialChars = (str) => { return str.normalize('NFD').replace(/[\u0300-\u036f]/g, '') // Remove accents .replace(/([^\w]+|\s+)/g, '-') // Replace space and other characters by hyphen .replace(/--+/g, '-') // Replaces multiple hyphens by one hyphen .replace(/(^-+|-+$)/g, ''); // Remove extra hyphens from beginning or end of the string }

      console.log(replaceSpecialChars('This is a sentence!!!')); ```

    1. ```js function replaceDiacritics(s) { var s;

      var diacritics =[ /[\300-\306]/g, /[\340-\346]/g, // A, a /[\310-\313]/g, /[\350-\353]/g, // E, e /[\314-\317]/g, /[\354-\357]/g, // I, i /[\322-\330]/g, /[\362-\370]/g, // O, o /[\331-\334]/g, /[\371-\374]/g, // U, u /[\321]/g, /[\361]/g, // N, n /[\307]/g, /[\347]/g, // C, c ];

      var chars = ['A','a','E','e','I','i','O','o','U','u','N','n','C','c'];

      for (var i = 0; i < diacritics.length; i++) { s = s.replace(diacritics[i],chars[i]); }

      document.write(s); } ```

    1. ```bash POST /news/comments/5 HTTP/1.1 Content-Type: text/xml

      <item> <title>Foo Bar</title> <author>joe@bitworking.org</author> <link>http://www.bar.com/</link> <description>My Excerpt</description> </item> ```

    1. ```js const dbName = 'CustomPeople';

      const exists = await Dexie.exists(dbName);

      if (exists) { var db = new Dexie(dbName); const dynamicDB = await db.open(); const existingVersionNumber = dynamicDB.verno; const columns = await ExternalDBService.getColumns(); db.close(); db = new Dexie(dbName); db.version(existingVersionNumber).stores({ People: columns }); return db.open(); } else { db = new Dexie(dbName); db.version(1).stores({ People: [] }); db.open(); } ```

    1. ```js function formatBytes(bytes, decimals = 2) { if (bytes === 0) return '0 Bytes';

      const k = 1024; const dm = decimals < 0 ? 0 : decimals; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; } ```

      1. Go to Settings > Network & internet.
      2. Select Advanced > Private DNS.
      3. Select the Private DNS provider hostname option.
      4. Enter one.one.one.one or 1dot1dot1dot1.cloudflare-dns.com and press Save.
    1. ```python doi_regexp = re.compile( r"(doi:\s|(?:https?://)?(?:dx.)?doi.org/)?(10.\d+(.\d+)/.+)$", flags=re.I ) """See http://en.wikipedia.org/wiki/Digital_object_identifier."""

      handle_regexp = re.compile( r"(hdl:\s|(?:https?://)?hdl.handle.net/)?" r"([^/.]+(.[^/.]+)/.)$", flags=re.I ) """See http://handle.net/rfc/rfc3651.html. <Handle> = <NamingAuthority> "/" <LocalName> <NamingAuthority> = (<NamingAuthority> ".") <NAsegment> <NAsegment> = Any UTF8 char except "/" and "." <LocalName> = Any UTF8 char """

      arxiv_post_2007_regexp = re.compile(r"(arxiv:)?(\d{4}).(\d{4,5})(v\d+)?$", flags=re.I) """See http://arxiv.org/help/arxiv_identifier and http://arxiv.org/help/arxiv_identifier_for_services."""

      arxiv_pre_2007_regexp = re.compile( r"(arxiv:)?([a-z-]+)(.[a-z]{2})?(/\d{4})(\d+)(v\d+)?$", flags=re.I ) """See http://arxiv.org/help/arxiv_identifier and http://arxiv.org/help/arxiv_identifier_for_services."""

      arxiv_post_2007_with_class_regexp = re.compile( r"(arxiv:)?(?:[a-z-]+)(?:.[a-z]{2})?/(\d{4}).(\d{4,5})(v\d+)?$", flags=re.I ) """Matches new style arXiv ID, with an old-style class specification; technically malformed, however appears in real data."""

      hal_regexp = re.compile(r"(hal:|HAL:)?([a-z]{3}[a-z]*-|(sic|mem|ijn)_)\d{8}(v\d+)?$") """Matches HAL identifiers (sic mem and ijn are old identifiers form)."""

      ads_regexp = re.compile(r"(ads:|ADS:)?(\d{4}[A-Za-z]\S{13}[A-Za-z.:])$") """See http://adsabs.harvard.edu/abs_doc/help_pages/data.html"""

      pmcid_regexp = re.compile(r"PMC\d+$", flags=re.I) """PubMed Central ID regular expression."""

      pmid_regexp = re.compile( r"(pmid:|https?://pubmed.ncbi.nlm.nih.gov/)?(\d+)/?$", flags=re.I ) """PubMed ID regular expression."""

      ark_suffix_regexp = re.compile(r"ark:/[0-9bcdfghjkmnpqrstvwxz]+/.+$") """See http://en.wikipedia.org/wiki/Archival_Resource_Key and https://confluence.ucop.edu/display/Curation/ARK."""

      lsid_regexp = re.compile(r"urn:lsid:[^:]+(:[^:]+){2,3}$", flags=re.I) """See http://en.wikipedia.org/wiki/LSID."""

      orcid_urls = ["http://orcid.org/", "https://orcid.org/"]

      gnd_regexp = re.compile( r"(gnd:|GND:)?(" r"(1|10)\d{7}[0-9X]|" r"[47]\d{6}-\d|" r"[1-9]\d{0,7}-[0-9X]|" r"3\d{7}[0-9X]" r")" ) """See https://www.wikidata.org/wiki/Property:P227."""

      gnd_resolver_url = "http://d-nb.info/gnd/"

      sra_regexp = re.compile(r"[SED]R[APRSXZ]\d+$") """Sequence Read Archive regular expression. See https://www.ncbi.nlm.nih.gov/books/NBK56913/#search.what_do_the_different_sra_accessi """

      bioproject_regexp = re.compile(r"PRJ(NA|EA|EB|DB)\d+$") """BioProject regular expression. See https://www.ddbj.nig.ac.jp/bioproject/faq-e.html#project-accession https://www.ebi.ac.uk/ena/submit/project-format https://www.ncbi.nlm.nih.gov/bioproject/docs/faq/#under-what-circumstances-is-it-n """

      biosample_regexp = re.compile(r"SAM(N|EA|D)\d+$") """BioSample regular expression. See https://www.ddbj.nig.ac.jp/biosample/faq-e.html https://ena-docs.readthedocs.io/en/latest/submit/samples/programmatic.html#accession-numbers-in-the-receipt-xml https://www.ncbi.nlm.nih.gov/biosample/docs/submission/faq/ """

      ensembl_regexp = re.compile( r"({prefixes})(E|FM|G|GT|P|R|T)\d{{11}}$".format( prefixes="|".join(ENSEMBL_PREFIXES) ) ) """Ensembl regular expression. See https://asia.ensembl.org/info/genome/stable_ids/prefixes.html """

      uniprot_regexp = re.compile( r"([A-NR-Z]0-9{1,2})|" r"([OPQ][0-9][A-Z0-9]{3}[0-9])(.\d+)?$" ) """UniProt regular expression. See https://www.uniprot.org/help/accession_numbers """

      refseq_regexp = re.compile( r"((AC|NC|NG|NT|NW|NM|NR|XM|XR|AP|NP|YP|XP|WP)|" r"NZ[A-Z]{4})\d+(.\d+)?$" ) """RefSeq regular expression. See https://academic.oup.com/nar/article/44/D1/D733/2502674 (Table 1) """

      genome_regexp = re.compile(r"GC[AF]_\d+.\d+$") """GenBank or RefSeq genome assembly accession. See https://www.ebi.ac.uk/ena/browse/genome-assembly-database """

      geo_regexp = re.compile(r"G(PL|SM|SE|DS)\d+$") """Gene Expression Omnibus (GEO) accession. See https://www.ncbi.nlm.nih.gov/geo/info/overview.html#org """

      arrayexpress_array_regexp = re.compile( r"A-({codes})-\d+$".format(codes="|".join(ARRAYEXPRESS_CODES)) ) """ArrayExpress array accession. See https://www.ebi.ac.uk/arrayexpress/help/accession_codes.html """

      arrayexpress_experiment_regexp = re.compile( r"E-({codes})-\d+$".format(codes="|".join(ARRAYEXPRESS_CODES)) ) """ArrayExpress array accession. See https://www.ebi.ac.uk/arrayexpress/help/accession_codes.html """

      ascl_regexp = re.compile(r"^ascl:[0-9]{4}.[0-9]{3,4}$", flags=re.I) """ASCL regular expression."""

      swh_regexp = re.compile( r"swh:1:(cnt|dir|rel|rev|snp):[0-9a-f]{40}" r"(;(origin|visit|anchor|path|lines)=\S+)*$" ) """Matches Software Heritage identifiers."""

      ror_regexp = re.compile(r"(?:https?://)?(?:ror.org/)?(0\w{6}\d{2})$", flags=re.I) """See https://ror.org/facts/#core-components.""" ```