问:
RangeError: Maximum call stack size exceeded caused by array.splice.apply?
I'm running a cheerio task and it throws an exception that prints this (Note that I added the log statements that print the size of spliceArgs and array:

```<code>    [14:17:08] Starting 'test:css'...
    SPLICE ARGS LENGTH:  4
    ARRAY LENGTH:  5
    SPLICE ARGS LENGTH:  132519
    ARRAY LENGTH:  0
    /home/ole/@superflycss/utilities-fonts/node_modules/cheerio/lib/api/manipulation.js:109
      return array.splice.apply(array, spliceArgs);
                          ^

    RangeError: Maximum call stack size exceeded
        at uniqueSplice (/home/ole/@superflycss/utilities-fonts/node_modules/cheerio/lib/api/manipulation.js:109:23)
        at /home/ole/Junk/@superflycss/utilities-fonts/node_modules/cheerio/lib/api/manipulation.js:133:3
        at initialize.<anonymous> (/home/ole/@superflycss/utilities-fonts/node_modules/cheerio/lib/api/manipulation.js
</code>```

The line of code within manipulation.js triggering this exception is:

```<code>  return array.splice.apply(array, spliceArgs);
</code>```

I also filed a bug report that has a link plus build and test instructions to the repository producing this exception.

Anyone know whether there is a NodeJS configuration setting that I can use to get around this?  The task is very sluggish in general and takes a long time to complete.

Update

Just adding some additional info.  The spliceArgs array has a 132,519 items on it when the exception occurs.  I logged what the last items looks like and it's a fairly heavy object like this:

```<code>    { type: 'tag',
      name: 'div',
      attribs: { class: 'Test_render' },
      children: [],
      next:
       { data: '\n      ',
         type: 'text',
         next: null,
         prev: [Circular],
         parent:
          { type: 'tag',
            name: 'div',
            attribs: [Object],
            children: [Array],
            next: [Object],
            prev: [Object],
            parent: [Object] } },
      prev:
       { data: '\n    ',
         type: 'text',
         next: [Circular],
         prev:
          { type: 'tag',
            name: 'div',
            attribs: [Object],
            children: [Array],
            next: [Circular],
            prev: [Object],
            parent: [Object] },
         parent:
          { type: 'tag',
            name: 'div',
            attribs: [Object],
            children: [Array],
            next: [Object],
            prev: [Object],
            parent: [Object] },
         root: null },
      parent:
       { type: 'tag',
         name: 'div',
         attribs: { class: 'Test_output' },
         children: [ [Object], [Object], [Object], [Object], [Object] ],
         next:
          { data: '\n    ',
            type: 'text',
            next: null,
            prev: [Circular],
            parent: [Object] },
         prev:
          { data: '\n      ',
            type: 'text',
            next: [Circular],
            prev: [Object],
            parent: [Object] },
         parent:
          { type: 'tag',
            name: 'div',
            attribs: [Object],
            children: [Array],
            next: [Object],
            prev: [Object],
            parent: [Object] } },
      root: null }
    SPLICE ARGS LENGTH:  4
    ARRAY LENGTH:  5
    SPLICE ARGS CONTENT: { data: '\n          ',
      type: 'text',
      next: null,
      prev:
       { type: 'tag',
         name: 'div',
         attribs: { class: 'u-flex u-flex-column u-width-40rem' },
         children: [ [Object], [Object], [Object], [Object], [Object] ],
         next: [Circular],
         prev:
          { data: '\n',
            type: 'text',
            next: [Circular],
            prev: [Object],
            parent: [Object],
            root: null },
         parent:
          { type: 'tag',
            name: 'div',
            attribs: [Object],
            children: [],
            next: [Object],
            prev: [Object],
            parent: [Object],
            root: null },
         root: null },
      parent:
       { type: 'tag',
         name: 'div',
         attribs: { class: 'Test_render' },
         children: [],
         next:
          { data: '\n      ',
            type: 'text',
            next: null,
            prev: [Circular],
            parent: [Object] },
         prev:
          { data: '\n    ',
            type: 'text',
            next: [Circular],
            prev: [Object],
            parent: [Object],
            root: null },
         parent:
          { type: 'tag',
            name: 'div',
            attribs: [Object],
            children: [Array],
            next: [Object],
            prev: [Object],
            parent: [Object] },
         root: null },
      root: null }
</code>```

So perhaps if we shoe horn in 132 thousand of these babies into an array that causes node to blow up?

Second update

Since the array instances length is zero at the time exception occurs, I just returned spliceArgs instead of actually doing the splice like this:

```<code>  if (array.length == 0) {
     return spliceArgs;
  }
</code>```

Now V8 runs out of memory:

```<code>      <--- Last few GCs --->

      [10392:0x247c600]    39418 ms: Mark-sweep 1404.6 (1451.9) -> 1404.4 (1428.9) MB, 2448.2 / 0.0 ms  (+ 0.0 ms in 0 steps since start of marking, biggest step 0.0 ms, walltime since start of marking 2448 ms) last resort
      [10392:0x247c600]    41855 ms: Mark-sweep 1404.4 (1428.9) -> 1404.4 (1428.9) MB, 2436.3 / 0.0 ms  last resort

      <--- JS stacktrace --->

      ==== JS stack trace =========================================

      Security context: 0x11ea432a9891 <JS Object>
          2: processKeywords [/home/ole/Junk/@superflycss/utilities-fonts/node_modules/highlight.js/lib/highlight.js:~366] [pc=0x39e06d9a7a8e](this=0x2b357c11c01 <JS Global Object>)
          3: processBuffer [/home/ole/Junk/@superflycss/utilities-fonts/node_modules/highlight.js/lib/highlight.js:~415] [pc=0x39e06d9a9cf9](this=0x2b357c11c01 <JS Global Object>)
          4: processLexeme [/home/ole/Junk/@superflyc...

      FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
       1: node::Abort() [gulp]
       2: 0x13647ec [gulp]
       3: v8::Utils::ReportOOMFailure(char const*, bool) [gulp]
       4: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [gulp]
       5: v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationSpace) [gulp]
       6: v8::internal::Runtime_AllocateInTargetSpace(int, v8::internal::Object**, v8::internal::Isolate*) [gulp]
       7: 0x39e06ce8437d
      Aborted (core dumped)
</code>```

Another update

This is not a cheerio issue.  I tried implementing the same thing in JSDOM and node still can't handle it even with 6GB of ram allocated:

```<code> node --max-old-space-size=6000 ./node_modules/.bin/gulp test:css
</code>```

I'm surprised by this because the html file, once the nunjucks loops have run, is 9X9X816 template blocks in size.  These are the loops:

```<code>      {% for font in ['abeezee', 'abel', 'abhaya-libre', 'abril-fatface', 'aclonica', 'acme', 'actor', 'adamina', 'advent-pro', 'aguafina-script', 'akronim', 'aladin', 'aldrich', 'alef', 'alegreya', 'alegreya-sc', 'alegreya-sans', 'alegreya-sans-sc', 'alex-brush', 'alfa-slab-one', 'alice', 'alike', 'alike-angular', 'allan', 'allerta', 'allerta-stencil', 'allura', 'almendra', 'almendra-display', 'almendra-sc', 'amarante', 'amaranth', 'amatic-sc', 'amatica-sc', 'amethysta', 'amiko', 'amiri', 'amita', 'anaheim', 'andada', 'andika', 'angkor', 'annie-use-your-telescope', 'anonymous-pro', 'antic', 'antic-didone', 'antic-slab', 'anton', 'arapey', 'arbutus', 'arbutus-slab', 'architects-daughter', 'archivo-black', 'archivo-narrow', 'aref-ruqaa', 'arima-madurai', 'arimo', 'arizonia', 'armata', 'arsenal', 'artifika', 'arvo', 'arya', 'asap', 'asar', 'asset', 'assistant', 'astloch', 'asul', 'athiti', 'atma', 'atomic-age', 'aubrey', 'audiowide', 'autour-one', 'average', 'average-sans', 'averia-gruesa-libre', 'averia-libre', 'averia-sans-libre', 'averia-serif-libre', 'bad-script', 'bahiana', 'baloo', 'baloo-bhai', 'baloo-bhaina', 'baloo-chettan', 'baloo-da', 'baloo-paaji', 'baloo-tamma', 'baloo-thambi', 'balthazar', 'bangers', 'barrio', 'basic', 'battambang', 'baumans', 'bayon', 'belgrano', 'belleza', 'benchnine', 'bentham', 'berkshire-swash', 'bevan', 'bigelow-rules', 'bigshot-one', 'bilbo', 'bilbo-swash-caps', 'biorhyme', 'biorhyme-expanded', 'biryani', 'bitter', 'black-ops-one', 'bokor', 'bonbon', 'boogaloo', 'bowlby-one', 'bowlby-one-sc', 'brawler', 'bree-serif', 'bubblegum-sans', 'bubbler-one', 'buda', 'buenard', 'bungee', 'bungee-hairline', 'bungee-inline', 'bungee-outline', 'bungee-shade', 'butcherman', 'butterfly-kids', 'cabin', 'cabin-condensed', 'cabin-sketch', 'caesar-dressing', 'cagliostro', 'cairo', 'calligraffitti', 'cambay', 'cambo', 'candal', 'cantarell', 'cantata-one', 'cantora-one', 'capriola', 'cardo', 'carme', 'carrois-gothic', 'carrois-gothic-sc', 'carter-one', 'catamaran', 'caudex', 'caveat', 'caveat-brush', 'cedarville-cursive', 'ceviche-one', 'changa', 'changa-one', 'chango', 'chathura', 'chau-philomene-one', 'chela-one', 'chelsea-market', 'chenla', 'cherry-cream-soda', 'cherry-swash', 'chewy', 'chicle', 'chivo', 'chonburi', 'cinzel', 'cinzel-decorative', 'clicker-script', 'coda', 'coda-caption', 'codystar', 'coiny', 'combo', 'comfortaa', 'coming-soon', 'concert-one', 'condiment', 'content', 'contrail-one', 'convergence', 'cookie', 'copse', 'corben', 'cormorant', 'cormorant-garamond', 'cormorant-infant', 'cormorant-sc', 'cormorant-unicase', 'cormorant-upright', 'courgette', 'cousine', 'coustard', 'covered-by-your-grace', 'crafty-girls', 'creepster', 'crete-round', 'crimson-text', 'croissant-one', 'crushed', 'cuprum', 'cutive', 'cutive-mono', 'damion', 'dancing-script', 'dangrek', 'david-libre', 'dawning-of-a-new-day', 'days-one', 'dekko', 'delius', 'delius-swash-caps', 'delius-unicase', 'della-respira', 'denk-one', 'devonshire', 'dhurjati', 'didact-gothic', 'diplomata', 'diplomata-sc', 'domine', 'donegal-one', 'doppio-one', 'dorsa', 'dosis', 'dr-sugiyama', 'droid-sans', 'droid-sans-mono', 'droid-serif', 'duru-sans', 'dynalight', 'eb-garamond', 'eagle-lake', 'eater', 'economica', 'eczar', 'ek-mukta', 'el-messiri', 'electrolize', 'elsie', 'elsie-swash-caps', 'emblema-one', 'emilys-candy', 'engagement', 'englebert', 'enriqueta', 'erica-one', 'esteban', 'euphoria-script', 'ewert', 'exo', 'exo-2', 'expletus-sans', 'fanwood-text', 'farsan', 'fascinate', 'fascinate-inline', 'faster-one', 'fasthand', 'fauna-one', 'federant', 'federo', 'felipa', 'fenix', 'finger-paint', 'fira-mono', 'fira-sans', 'fira-sans-condensed', 'fira-sans-extra-condensed', 'fjalla-one', 'fjord-one', 'flamenco', 'flavors', 'fondamento', 'fontdiner-swanky', 'forum', 'francois-one', 'frank-ruhl-libre', 'freckle-face', 'fredericka-the-great', 'fredoka-one', 'freehand', 'fresca', 'frijole', 'fruktur', 'fugaz-one', 'gfs-didot', 'gfs-neohellenic', 'gabriela', 'gafata', 'galada', 'galdeano', 'galindo', 'gentium-basic', 'gentium-book-basic', 'geo', 'geostar', 'geostar-fill', 'germania-one', 'gidugu', 'gilda-display', 'give-you-glory', 'glass-antiqua', 'glegoo', 'gloria-hallelujah', 'goblin-one', 'gochi-hand', 'gorditas', 'goudy-bookletter-1911', 'graduate', 'grand-hotel', 'gravitas-one', 'great-vibes', 'griffy', 'gruppo', 'gudea', 'gurajada', 'habibi', 'halant', 'hammersmith-one', 'hanalei', 'hanalei-fill', 'handlee', 'hanuman', 'happy-monkey', 'harmattan', 'headland-one', 'heebo', 'henny-penny', 'herr-von-muellerhoff', 'hind', 'hind-guntur', 'hind-madurai', 'hind-siliguri', 'hind-vadodara', 'holtwood-one-sc', 'homemade-apple', 'homenaje', 'im-fell-dw-pica', 'im-fell-dw-pica-sc', 'im-fell-double-pica', 'im-fell-double-pica-sc', 'im-fell-english', 'im-fell-english-sc', 'im-fell-french-canon', 'im-fell-french-canon-sc', 'im-fell-great-primer', 'im-fell-great-primer-sc', 'iceberg', 'iceland', 'imprima', 'inconsolata', 'inder', 'indie-flower', 'inika', 'inknut-antiqua', 'irish-grover', 'istok-web', 'italiana', 'italianno', 'itim', 'jacques-francois', 'jacques-francois-shadow', 'jaldi', 'jim-nightshade', 'jockey-one', 'jolly-lodger', 'jomhuria', 'josefin-sans', 'josefin-slab', 'joti-one', 'judson', 'julee', 'julius-sans-one', 'junge', 'jura', 'just-another-hand', 'just-me-again-down-here', 'kadwa', 'kalam', 'kameron', 'kanit', 'kantumruy', 'karla', 'karma', 'katibeh', 'kaushan-script', 'kavivanar', 'kavoon', 'kdam-thmor', 'keania-one', 'kelly-slab', 'kenia', 'khand', 'khmer', 'khula', 'kite-one', 'knewave', 'kotta-one', 'koulen', 'kranky', 'kreon', 'kristi', 'krona-one', 'kumar-one', 'kumar-one-outline', 'kurale', 'la-belle-aurore', 'laila', 'lakki-reddy', 'lalezar', 'lancelot', 'lateef', 'lato', 'league-script', 'leckerli-one', 'ledger', 'lekton', 'lemon', 'lemonada', 'libre-baskerville', 'libre-franklin', 'life-savers', 'lilita-one', 'lily-script-one', 'limelight', 'linden-hill', 'lobster', 'lobster-two', 'londrina-outline', 'londrina-shadow', 'londrina-sketch', 'londrina-solid', 'lora', 'love-ya-like-a-sister', 'loved-by-the-king', 'lovers-quarrel', 'luckiest-guy', 'lusitana', 'lustria', 'macondo', 'macondo-swash-caps', 'mada', 'magra', 'maiden-orange', 'maitree', 'mako', 'mallanna', 'mandali', 'marcellus', 'marcellus-sc', 'marck-script', 'margarine', 'marko-one', 'marmelad', 'martel', 'martel-sans', 'marvel', 'mate', 'mate-sc', 'maven-pro', 'mclaren', 'meddon', 'medievalsharp', 'medula-one', 'meera-inimai', 'megrim', 'meie-script', 'merienda', 'merienda-one', 'merriweather', 'merriweather-sans', 'metal', 'metal-mania', 'metamorphous', 'metrophobic', 'michroma', 'milonga', 'miltonian', 'miltonian-tattoo', 'miniver', 'miriam-libre', 'mirza', 'miss-fajardose', 'mitr', 'modak', 'modern-antiqua', 'mogra', 'molengo', 'molle', 'monda', 'monofett', 'monoton', 'monsieur-la-doulaise', 'montaga', 'montez', 'montserrat', 'montserrat-alternates', 'montserrat-subrayada', 'moul', 'moulpali', 'mountains-of-christmas', 'mouse-memoirs', 'mr-bedfort', 'mr-dafoe', 'mr-de-haviland', 'mrs-saint-delafield', 'mrs-sheppards', 'mukta-vaani', 'muli', 'mystery-quest', 'ntr', 'neucha', 'neuton', 'new-rocker', 'news-cycle', 'niconne', 'nixie-one', 'nobile', 'nokora', 'norican', 'nosifer', 'nothing-you-could-do', 'noticia-text', 'noto-sans', 'noto-serif', 'nova-cut', 'nova-flat', 'nova-mono', 'nova-oval', 'nova-round', 'nova-script', 'nova-slim', 'nova-square', 'numans', 'nunito', 'nunito-sans', 'odor-mean-chey', 'offside', 'old-standard-tt', 'oldenburg', 'oleo-script', 'oleo-script-swash-caps', 'open-sans', 'open-sans-condensed', 'oranienbaum', 'orbitron', 'oregano', 'orienta', 'original-surfer', 'oswald', 'over-the-rainbow', 'overlock', 'overlock-sc', 'overpass', 'overpass-mono', 'ovo', 'oxygen', 'oxygen-mono', 'pt-mono', 'pt-sans', 'pt-sans-caption', 'pt-sans-narrow', 'pt-serif', 'pt-serif-caption', 'pacifico', 'padauk', 'palanquin', 'palanquin-dark', 'pangolin', 'paprika', 'parisienne', 'passero-one', 'passion-one', 'pathway-gothic-one', 'patrick-hand', 'patrick-hand-sc', 'pattaya', 'patua-one', 'pavanam', 'paytone-one', 'peddana', 'peralta', 'permanent-marker', 'petit-formal-script', 'petrona', 'philosopher', 'piedra', 'pinyon-script', 'pirata-one', 'plaster', 'play', 'playball', 'playfair-display', 'playfair-display-sc', 'podkova', 'poiret-one', 'poller-one', 'poly', 'pompiere', 'pontano-sans', 'poppins', 'port-lligat-sans', 'port-lligat-slab', 'pragati-narrow', 'prata', 'preahvihear', 'press-start-2p', 'pridi', 'princess-sofia', 'prociono', 'prompt', 'prosto-one', 'proza-libre', 'puritan', 'purple-purse', 'quando', 'quantico', 'quattrocento', 'quattrocento-sans', 'questrial', 'quicksand', 'quintessential', 'qwigley', 'racing-sans-one', 'radley', 'rajdhani', 'rakkas', 'raleway', 'raleway-dots', 'ramabhadra', 'ramaraja', 'rambla', 'rammetto-one', 'ranchers', 'rancho', 'ranga', 'rasa', 'rationale', 'ravi-prakash', 'redressed', 'reem-kufi', 'reenie-beanie', 'revalia', 'rhodium-libre', 'ribeye', 'ribeye-marrow', 'righteous', 'risque', 'roboto', 'roboto-condensed', 'roboto-mono', 'roboto-slab', 'rochester', 'rock-salt', 'rokkitt', 'romanesco', 'ropa-sans', 'rosario', 'rosarivo', 'rouge-script', 'rozha-one', 'rubik', 'rubik-mono-one', 'ruda', 'rufina', 'ruge-boogie', 'ruluko', 'rum-raisin', 'ruslan-display', 'russo-one', 'ruthie', 'rye', 'sacramento', 'sahitya', 'sail', 'salsa', 'sanchez', 'sancreek', 'sansita', 'sarala', 'sarina', 'sarpanch', 'satisfy', 'scada', 'scheherazade', 'schoolbell', 'scope-one', 'seaweed-script', 'secular-one', 'sevillana', 'seymour-one', 'shadows-into-light', 'shadows-into-light-two', 'shanti', 'share', 'share-tech', 'share-tech-mono', 'shojumaru', 'short-stack', 'shrikhand', 'siemreap', 'sigmar-one', 'signika', 'signika-negative', 'simonetta', 'sintony', 'sirin-stencil', 'six-caps', 'skranji', 'slabo-13px', 'slabo-27px', 'slackey', 'smokum', 'smythe', 'sniglet', 'snippet', 'snowburst-one', 'sofadi-one', 'sofia', 'sonsie-one', 'sorts-mill-goudy', 'source-code-pro', 'source-sans-pro', 'source-serif-pro', 'space-mono', 'special-elite', 'spicy-rice', 'spinnaker', 'spirax', 'squada-one', 'sree-krushnadevaraya', 'sriracha', 'stalemate', 'stalinist-one', 'stardos-stencil', 'stint-ultra-condensed', 'stint-ultra-expanded', 'stoke', 'strait', 'sue-ellen-francisco', 'suez-one', 'sumana', 'sunshiney', 'supermercado-one', 'sura', 'suranna', 'suravaram', 'suwannaphum', 'swanky-and-moo-moo', 'syncopate', 'tangerine', 'taprom', 'tauri', 'taviraj', 'teko', 'telex', 'tenali-ramakrishna', 'tenor-sans', 'text-me-one', 'the-girl-next-door', 'tienne', 'tillana', 'timmana', 'tinos', 'titan-one', 'titillium-web', 'trade-winds', 'trirong', 'trocchi', 'trochut', 'trykker', 'tulpen-one', 'ubuntu', 'ubuntu-condensed', 'ubuntu-mono', 'ultra', 'uncial-antiqua', 'underdog', 'unica-one', 'unifrakturcook', 'unifrakturmaguntia', 'unkempt', 'unlock', 'unna', 'vt323', 'vampiro-one', 'varela', 'varela-round', 'vast-shadow', 'vesper-libre', 'vibur', 'vidaloka', 'viga', 'voces', 'volkhov', 'vollkorn', 'voltaire', 'waiting-for-the-sunrise', 'wallpoet', 'walter-turncoat', 'warnes', 'wellfleet', 'wendy-one', 'wire-one', 'work-sans', 'yanone-kaffeesatz', 'yantramanav', 'yatra-one', 'yellowtail', 'yeseva-one', 'yesteryear', 'yrsa', 'zeyada'] %}
      {% for weight in ['100','200','300','400','500','600','700','800','900']%}
      {% for size in ['100','200','300','400','500','600','700','800','900']%}
      <div class="u-flex u-flex-column u-width-40rem">
        <div class="u-flex u-width-40rem">
          <div class="u-flex-auto
                      u-padding-1rem
                      u-font-inconsolata
                      u-font-weight-400
                      u-font-size-300
                      u-border-style-solid
                      u-border-width-1px
                      u-border-color-gray">
                      u-font-weight-{{weight}}
          </div>
          <div class="u-flex-auto
                      u-padding-1rem
                      u-font-inconsolata
                      u-font-weight-400
                      u-font-size-300
                      u-border-style-solid
                      u-border-style-top-none
                      u-border-width-1px
                      u-border-color-gray">
                      u-font-size-{{size}}
          </div>
          <div class="u-flex-auto
                      u-padding-1rem
                      u-font-inconsolata
                      u-font-weight-400
                      u-font-size-300
                      u-border-style-solid
                      u-border-style-top-none
                      u-border-width-1px
                      u-border-color-gray">
                      u-font-{{font}}
          </div>
        </div>
        <div class="u-font-{{font}}
                    u-font-weight-{{weight}}
                    u-font-size-{{size}}
                    u-flex
                    u-flex-justify-center
                    u-width-100
                    u-padding-1rem
                    u-border-style-solid
                    u-border-top-style-none
                    u-border-width-1px
                    u-border-color-gray
                    margin-bottom-1rem
                    u-background-color-white
                    u-text-color-md-grey-900">
          Word to the Dalai Lama!
        </div>
      </div>
      {%- endfor %}
      {%- endfor %}
      {%- endfor %}
</code>```

So these render out and then the gulp task attempts to copy that block to another place in the document, before syntax highlighting is run on all of it.  Node runs into memory issues on the copy and append.

答:
I think you are hitting the maximum argument size allowed by apply. If you reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

The consequences of applying a function with too many arguments (think more than tens of thousands of arguments) vary across engines (JavaScriptCore has hard-coded argument limit of 65536), because the limit (indeed even the nature of any excessively-large-stack behavior) is unspecified.

Body:
I'm running a cheerio task and it throws an exception that prints this (Note that I added the log statements that print the size of spliceArgs and array:

    [14:17:08] Starting 'test:css'...
    SPLICE ARGS LENGTH:  4
    ARRAY LENGTH:  5
    SPLICE ARGS LENGTH:  132519
    ARRAY LENGTH:  0
    /home/ole/@superflycss/utilities-fonts/node_modules/cheerio/lib/api/manipulation.js:109
      return array.splice.apply(array, spliceArgs);
                          ^

    RangeError: Maximum call stack size exceeded
        at uniqueSplice (/home/ole/@superflycss/utilities-fonts/node_modules/cheerio/lib/api/manipulation.js:109:23)
        at /home/ole/Junk/@superflycss/utilities-fonts/node_modules/cheerio/lib/api/manipulation.js:133:3
        at initialize.<anonymous> (/home/ole/@superflycss/utilities-fonts/node_modules/cheerio/lib/api/manipulation.js

The line of code within manipulation.js triggering this exception is:

  return array.splice.apply(array, spliceArgs);

I also filed a bug report that has a link plus build and test instructions to the repository producing this exception.

Anyone know whether there is a NodeJS configuration setting that I can use to get around this?  The task is very sluggish in general and takes a long time to complete.

Update

Just adding some additional info.  The spliceArgs array has a 132,519 items on it when the exception occurs.  I logged what the last items looks like and it's a fairly heavy object like this:

    { type: 'tag',
      name: 'div',
      attribs: { class: 'Test_render' },
      children: [],
      next:
       { data: '\n      ',
         type: 'text',
         next: null,
         prev: [Circular],
         parent:
          { type: 'tag',
            name: 'div',
            attribs: [Object],
            children: [Array],
            next: [Object],
            prev: [Object],
            parent: [Object] } },
      prev:
       { data: '\n    ',
         type: 'text',
         next: [Circular],
         prev:
          { type: 'tag',
            name: 'div',
            attribs: [Object],
            children: [Array],
            next: [Circular],
            prev: [Object],
            parent: [Object] },
         parent:
          { type: 'tag',
            name: 'div',
            attribs: [Object],
            children: [Array],
            next: [Object],
            prev: [Object],
            parent: [Object] },
         root: null },
      parent:
       { type: 'tag',
         name: 'div',
         attribs: { class: 'Test_output' },
         children: [ [Object], [Object], [Object], [Object], [Object] ],
         next:
          { data: '\n    ',
            type: 'text',
            next: null,
            prev: [Circular],
            parent: [Object] },
         prev:
          { data: '\n      ',
            type: 'text',
            next: [Circular],
            prev: [Object],
            parent: [Object] },
         parent:
          { type: 'tag',
            name: 'div',
            attribs: [Object],
            children: [Array],
            next: [Object],
            prev: [Object],
            parent: [Object] } },
      root: null }
    SPLICE ARGS LENGTH:  4
    ARRAY LENGTH:  5
    SPLICE ARGS CONTENT: { data: '\n          ',
      type: 'text',
      next: null,
      prev:
       { type: 'tag',
         name: 'div',
         attribs: { class: 'u-flex u-flex-column u-width-40rem' },
         children: [ [Object], [Object], [Object], [Object], [Object] ],
         next: [Circular],
         prev:
          { data: '\n',
            type: 'text',
            next: [Circular],
            prev: [Object],
            parent: [Object],
            root: null },
         parent:
          { type: 'tag',
            name: 'div',
            attribs: [Object],
            children: [],
            next: [Object],
            prev: [Object],
            parent: [Object],
            root: null },
         root: null },
      parent:
       { type: 'tag',
         name: 'div',
         attribs: { class: 'Test_render' },
         children: [],
         next:
          { data: '\n      ',
            type: 'text',
            next: null,
            prev: [Circular],
            parent: [Object] },
         prev:
          { data: '\n    ',
            type: 'text',
            next: [Circular],
            prev: [Object],
            parent: [Object],
            root: null },
         parent:
          { type: 'tag',
            name: 'div',
            attribs: [Object],
            children: [Array],
            next: [Object],
            prev: [Object],
            parent: [Object] },
         root: null },
      root: null }

So perhaps if we shoe horn in 132 thousand of these babies into an array that causes node to blow up?

Second update

Since the array instances length is zero at the time exception occurs, I just returned spliceArgs instead of actually doing the splice like this:

  if (array.length == 0) {
     return spliceArgs;
  }

Now V8 runs out of memory:

      <--- Last few GCs --->

      [10392:0x247c600]    39418 ms: Mark-sweep 1404.6 (1451.9) -> 1404.4 (1428.9) MB, 2448.2 / 0.0 ms  (+ 0.0 ms in 0 steps since start of marking, biggest step 0.0 ms, walltime since start of marking 2448 ms) last resort
      [10392:0x247c600]    41855 ms: Mark-sweep 1404.4 (1428.9) -> 1404.4 (1428.9) MB, 2436.3 / 0.0 ms  last resort

      <--- JS stacktrace --->

      ==== JS stack trace =========================================

      Security context: 0x11ea432a9891 <JS Object>
          2: processKeywords [/home/ole/Junk/@superflycss/utilities-fonts/node_modules/highlight.js/lib/highlight.js:~366] [pc=0x39e06d9a7a8e](this=0x2b357c11c01 <JS Global Object>)
          3: processBuffer [/home/ole/Junk/@superflycss/utilities-fonts/node_modules/highlight.js/lib/highlight.js:~415] [pc=0x39e06d9a9cf9](this=0x2b357c11c01 <JS Global Object>)
          4: processLexeme [/home/ole/Junk/@superflyc...

      FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
       1: node::Abort() [gulp]
       2: 0x13647ec [gulp]
       3: v8::Utils::ReportOOMFailure(char const*, bool) [gulp]
       4: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [gulp]
       5: v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationSpace) [gulp]
       6: v8::internal::Runtime_AllocateInTargetSpace(int, v8::internal::Object**, v8::internal::Isolate*) [gulp]
       7: 0x39e06ce8437d
      Aborted (core dumped)

Another update

This is not a cheerio issue.  I tried implementing the same thing in JSDOM and node still can't handle it even with 6GB of ram allocated:

 node --max-old-space-size=6000 ./node_modules/.bin/gulp test:css

I'm surprised by this because the html file, once the nunjucks loops have run, is 9X9X816 template blocks in size.  These are the loops:

      {% for font in ['abeezee', 'abel', 'abhaya-libre', 'abril-fatface', 'aclonica', 'acme', 'actor', 'adamina', 'advent-pro', 'aguafina-script', 'akronim', 'aladin', 'aldrich', 'alef', 'alegreya', 'alegreya-sc', 'alegreya-sans', 'alegreya-sans-sc', 'alex-brush', 'alfa-slab-one', 'alice', 'alike', 'alike-angular', 'allan', 'allerta', 'allerta-stencil', 'allura', 'almendra', 'almendra-display', 'almendra-sc', 'amarante', 'amaranth', 'amatic-sc', 'amatica-sc', 'amethysta', 'amiko', 'amiri', 'amita', 'anaheim', 'andada', 'andika', 'angkor', 'annie-use-your-telescope', 'anonymous-pro', 'antic', 'antic-didone', 'antic-slab', 'anton', 'arapey', 'arbutus', 'arbutus-slab', 'architects-daughter', 'archivo-black', 'archivo-narrow', 'aref-ruqaa', 'arima-madurai', 'arimo', 'arizonia', 'armata', 'arsenal', 'artifika', 'arvo', 'arya', 'asap', 'asar', 'asset', 'assistant', 'astloch', 'asul', 'athiti', 'atma', 'atomic-age', 'aubrey', 'audiowide', 'autour-one', 'average', 'average-sans', 'averia-gruesa-libre', 'averia-libre', 'averia-sans-libre', 'averia-serif-libre', 'bad-script', 'bahiana', 'baloo', 'baloo-bhai', 'baloo-bhaina', 'baloo-chettan', 'baloo-da', 'baloo-paaji', 'baloo-tamma', 'baloo-thambi', 'balthazar', 'bangers', 'barrio', 'basic', 'battambang', 'baumans', 'bayon', 'belgrano', 'belleza', 'benchnine', 'bentham', 'berkshire-swash', 'bevan', 'bigelow-rules', 'bigshot-one', 'bilbo', 'bilbo-swash-caps', 'biorhyme', 'biorhyme-expanded', 'biryani', 'bitter', 'black-ops-one', 'bokor', 'bonbon', 'boogaloo', 'bowlby-one', 'bowlby-one-sc', 'brawler', 'bree-serif', 'bubblegum-sans', 'bubbler-one', 'buda', 'buenard', 'bungee', 'bungee-hairline', 'bungee-inline', 'bungee-outline', 'bungee-shade', 'butcherman', 'butterfly-kids', 'cabin', 'cabin-condensed', 'cabin-sketch', 'caesar-dressing', 'cagliostro', 'cairo', 'calligraffitti', 'cambay', 'cambo', 'candal', 'cantarell', 'cantata-one', 'cantora-one', 'capriola', 'cardo', 'carme', 'carrois-gothic', 'carrois-gothic-sc', 'carter-one', 'catamaran', 'caudex', 'caveat', 'caveat-brush', 'cedarville-cursive', 'ceviche-one', 'changa', 'changa-one', 'chango', 'chathura', 'chau-philomene-one', 'chela-one', 'chelsea-market', 'chenla', 'cherry-cream-soda', 'cherry-swash', 'chewy', 'chicle', 'chivo', 'chonburi', 'cinzel', 'cinzel-decorative', 'clicker-script', 'coda', 'coda-caption', 'codystar', 'coiny', 'combo', 'comfortaa', 'coming-soon', 'concert-one', 'condiment', 'content', 'contrail-one', 'convergence', 'cookie', 'copse', 'corben', 'cormorant', 'cormorant-garamond', 'cormorant-infant', 'cormorant-sc', 'cormorant-unicase', 'cormorant-upright', 'courgette', 'cousine', 'coustard', 'covered-by-your-grace', 'crafty-girls', 'creepster', 'crete-round', 'crimson-text', 'croissant-one', 'crushed', 'cuprum', 'cutive', 'cutive-mono', 'damion', 'dancing-script', 'dangrek', 'david-libre', 'dawning-of-a-new-day', 'days-one', 'dekko', 'delius', 'delius-swash-caps', 'delius-unicase', 'della-respira', 'denk-one', 'devonshire', 'dhurjati', 'didact-gothic', 'diplomata', 'diplomata-sc', 'domine', 'donegal-one', 'doppio-one', 'dorsa', 'dosis', 'dr-sugiyama', 'droid-sans', 'droid-sans-mono', 'droid-serif', 'duru-sans', 'dynalight', 'eb-garamond', 'eagle-lake', 'eater', 'economica', 'eczar', 'ek-mukta', 'el-messiri', 'electrolize', 'elsie', 'elsie-swash-caps', 'emblema-one', 'emilys-candy', 'engagement', 'englebert', 'enriqueta', 'erica-one', 'esteban', 'euphoria-script', 'ewert', 'exo', 'exo-2', 'expletus-sans', 'fanwood-text', 'farsan', 'fascinate', 'fascinate-inline', 'faster-one', 'fasthand', 'fauna-one', 'federant', 'federo', 'felipa', 'fenix', 'finger-paint', 'fira-mono', 'fira-sans', 'fira-sans-condensed', 'fira-sans-extra-condensed', 'fjalla-one', 'fjord-one', 'flamenco', 'flavors', 'fondamento', 'fontdiner-swanky', 'forum', 'francois-one', 'frank-ruhl-libre', 'freckle-face', 'fredericka-the-great', 'fredoka-one', 'freehand', 'fresca', 'frijole', 'fruktur', 'fugaz-one', 'gfs-didot', 'gfs-neohellenic', 'gabriela', 'gafata', 'galada', 'galdeano', 'galindo', 'gentium-basic', 'gentium-book-basic', 'geo', 'geostar', 'geostar-fill', 'germania-one', 'gidugu', 'gilda-display', 'give-you-glory', 'glass-antiqua', 'glegoo', 'gloria-hallelujah', 'goblin-one', 'gochi-hand', 'gorditas', 'goudy-bookletter-1911', 'graduate', 'grand-hotel', 'gravitas-one', 'great-vibes', 'griffy', 'gruppo', 'gudea', 'gurajada', 'habibi', 'halant', 'hammersmith-one', 'hanalei', 'hanalei-fill', 'handlee', 'hanuman', 'happy-monkey', 'harmattan', 'headland-one', 'heebo', 'henny-penny', 'herr-von-muellerhoff', 'hind', 'hind-guntur', 'hind-madurai', 'hind-siliguri', 'hind-vadodara', 'holtwood-one-sc', 'homemade-apple', 'homenaje', 'im-fell-dw-pica', 'im-fell-dw-pica-sc', 'im-fell-double-pica', 'im-fell-double-pica-sc', 'im-fell-english', 'im-fell-english-sc', 'im-fell-french-canon', 'im-fell-french-canon-sc', 'im-fell-great-primer', 'im-fell-great-primer-sc', 'iceberg', 'iceland', 'imprima', 'inconsolata', 'inder', 'indie-flower', 'inika', 'inknut-antiqua', 'irish-grover', 'istok-web', 'italiana', 'italianno', 'itim', 'jacques-francois', 'jacques-francois-shadow', 'jaldi', 'jim-nightshade', 'jockey-one', 'jolly-lodger', 'jomhuria', 'josefin-sans', 'josefin-slab', 'joti-one', 'judson', 'julee', 'julius-sans-one', 'junge', 'jura', 'just-another-hand', 'just-me-again-down-here', 'kadwa', 'kalam', 'kameron', 'kanit', 'kantumruy', 'karla', 'karma', 'katibeh', 'kaushan-script', 'kavivanar', 'kavoon', 'kdam-thmor', 'keania-one', 'kelly-slab', 'kenia', 'khand', 'khmer', 'khula', 'kite-one', 'knewave', 'kotta-one', 'koulen', 'kranky', 'kreon', 'kristi', 'krona-one', 'kumar-one', 'kumar-one-outline', 'kurale', 'la-belle-aurore', 'laila', 'lakki-reddy', 'lalezar', 'lancelot', 'lateef', 'lato', 'league-script', 'leckerli-one', 'ledger', 'lekton', 'lemon', 'lemonada', 'libre-baskerville', 'libre-franklin', 'life-savers', 'lilita-one', 'lily-script-one', 'limelight', 'linden-hill', 'lobster', 'lobster-two', 'londrina-outline', 'londrina-shadow', 'londrina-sketch', 'londrina-solid', 'lora', 'love-ya-like-a-sister', 'loved-by-the-king', 'lovers-quarrel', 'luckiest-guy', 'lusitana', 'lustria', 'macondo', 'macondo-swash-caps', 'mada', 'magra', 'maiden-orange', 'maitree', 'mako', 'mallanna', 'mandali', 'marcellus', 'marcellus-sc', 'marck-script', 'margarine', 'marko-one', 'marmelad', 'martel', 'martel-sans', 'marvel', 'mate', 'mate-sc', 'maven-pro', 'mclaren', 'meddon', 'medievalsharp', 'medula-one', 'meera-inimai', 'megrim', 'meie-script', 'merienda', 'merienda-one', 'merriweather', 'merriweather-sans', 'metal', 'metal-mania', 'metamorphous', 'metrophobic', 'michroma', 'milonga', 'miltonian', 'miltonian-tattoo', 'miniver', 'miriam-libre', 'mirza', 'miss-fajardose', 'mitr', 'modak', 'modern-antiqua', 'mogra', 'molengo', 'molle', 'monda', 'monofett', 'monoton', 'monsieur-la-doulaise', 'montaga', 'montez', 'montserrat', 'montserrat-alternates', 'montserrat-subrayada', 'moul', 'moulpali', 'mountains-of-christmas', 'mouse-memoirs', 'mr-bedfort', 'mr-dafoe', 'mr-de-haviland', 'mrs-saint-delafield', 'mrs-sheppards', 'mukta-vaani', 'muli', 'mystery-quest', 'ntr', 'neucha', 'neuton', 'new-rocker', 'news-cycle', 'niconne', 'nixie-one', 'nobile', 'nokora', 'norican', 'nosifer', 'nothing-you-could-do', 'noticia-text', 'noto-sans', 'noto-serif', 'nova-cut', 'nova-flat', 'nova-mono', 'nova-oval', 'nova-round', 'nova-script', 'nova-slim', 'nova-square', 'numans', 'nunito', 'nunito-sans', 'odor-mean-chey', 'offside', 'old-standard-tt', 'oldenburg', 'oleo-script', 'oleo-script-swash-caps', 'open-sans', 'open-sans-condensed', 'oranienbaum', 'orbitron', 'oregano', 'orienta', 'original-surfer', 'oswald', 'over-the-rainbow', 'overlock', 'overlock-sc', 'overpass', 'overpass-mono', 'ovo', 'oxygen', 'oxygen-mono', 'pt-mono', 'pt-sans', 'pt-sans-caption', 'pt-sans-narrow', 'pt-serif', 'pt-serif-caption', 'pacifico', 'padauk', 'palanquin', 'palanquin-dark', 'pangolin', 'paprika', 'parisienne', 'passero-one', 'passion-one', 'pathway-gothic-one', 'patrick-hand', 'patrick-hand-sc', 'pattaya', 'patua-one', 'pavanam', 'paytone-one', 'peddana', 'peralta', 'permanent-marker', 'petit-formal-script', 'petrona', 'philosopher', 'piedra', 'pinyon-script', 'pirata-one', 'plaster', 'play', 'playball', 'playfair-display', 'playfair-display-sc', 'podkova', 'poiret-one', 'poller-one', 'poly', 'pompiere', 'pontano-sans', 'poppins', 'port-lligat-sans', 'port-lligat-slab', 'pragati-narrow', 'prata', 'preahvihear', 'press-start-2p', 'pridi', 'princess-sofia', 'prociono', 'prompt', 'prosto-one', 'proza-libre', 'puritan', 'purple-purse', 'quando', 'quantico', 'quattrocento', 'quattrocento-sans', 'questrial', 'quicksand', 'quintessential', 'qwigley', 'racing-sans-one', 'radley', 'rajdhani', 'rakkas', 'raleway', 'raleway-dots', 'ramabhadra', 'ramaraja', 'rambla', 'rammetto-one', 'ranchers', 'rancho', 'ranga', 'rasa', 'rationale', 'ravi-prakash', 'redressed', 'reem-kufi', 'reenie-beanie', 'revalia', 'rhodium-libre', 'ribeye', 'ribeye-marrow', 'righteous', 'risque', 'roboto', 'roboto-condensed', 'roboto-mono', 'roboto-slab', 'rochester', 'rock-salt', 'rokkitt', 'romanesco', 'ropa-sans', 'rosario', 'rosarivo', 'rouge-script', 'rozha-one', 'rubik', 'rubik-mono-one', 'ruda', 'rufina', 'ruge-boogie', 'ruluko', 'rum-raisin', 'ruslan-display', 'russo-one', 'ruthie', 'rye', 'sacramento', 'sahitya', 'sail', 'salsa', 'sanchez', 'sancreek', 'sansita', 'sarala', 'sarina', 'sarpanch', 'satisfy', 'scada', 'scheherazade', 'schoolbell', 'scope-one', 'seaweed-script', 'secular-one', 'sevillana', 'seymour-one', 'shadows-into-light', 'shadows-into-light-two', 'shanti', 'share', 'share-tech', 'share-tech-mono', 'shojumaru', 'short-stack', 'shrikhand', 'siemreap', 'sigmar-one', 'signika', 'signika-negative', 'simonetta', 'sintony', 'sirin-stencil', 'six-caps', 'skranji', 'slabo-13px', 'slabo-27px', 'slackey', 'smokum', 'smythe', 'sniglet', 'snippet', 'snowburst-one', 'sofadi-one', 'sofia', 'sonsie-one', 'sorts-mill-goudy', 'source-code-pro', 'source-sans-pro', 'source-serif-pro', 'space-mono', 'special-elite', 'spicy-rice', 'spinnaker', 'spirax', 'squada-one', 'sree-krushnadevaraya', 'sriracha', 'stalemate', 'stalinist-one', 'stardos-stencil', 'stint-ultra-condensed', 'stint-ultra-expanded', 'stoke', 'strait', 'sue-ellen-francisco', 'suez-one', 'sumana', 'sunshiney', 'supermercado-one', 'sura', 'suranna', 'suravaram', 'suwannaphum', 'swanky-and-moo-moo', 'syncopate', 'tangerine', 'taprom', 'tauri', 'taviraj', 'teko', 'telex', 'tenali-ramakrishna', 'tenor-sans', 'text-me-one', 'the-girl-next-door', 'tienne', 'tillana', 'timmana', 'tinos', 'titan-one', 'titillium-web', 'trade-winds', 'trirong', 'trocchi', 'trochut', 'trykker', 'tulpen-one', 'ubuntu', 'ubuntu-condensed', 'ubuntu-mono', 'ultra', 'uncial-antiqua', 'underdog', 'unica-one', 'unifrakturcook', 'unifrakturmaguntia', 'unkempt', 'unlock', 'unna', 'vt323', 'vampiro-one', 'varela', 'varela-round', 'vast-shadow', 'vesper-libre', 'vibur', 'vidaloka', 'viga', 'voces', 'volkhov', 'vollkorn', 'voltaire', 'waiting-for-the-sunrise', 'wallpoet', 'walter-turncoat', 'warnes', 'wellfleet', 'wendy-one', 'wire-one', 'work-sans', 'yanone-kaffeesatz', 'yantramanav', 'yatra-one', 'yellowtail', 'yeseva-one', 'yesteryear', 'yrsa', 'zeyada'] %}
      {% for weight in ['100','200','300','400','500','600','700','800','900']%}
      {% for size in ['100','200','300','400','500','600','700','800','900']%}

                      u-font-weight-{{weight}}

                      u-font-size-{{size}}

                      u-font-{{font}}

        <div class="u-font-{{font}}
                    u-font-weight-{{weight}}
                    u-font-size-{{size}}
                    u-flex
                    u-flex-justify-center
                    u-width-100
                    u-padding-1rem
                    u-border-style-solid
                    u-border-top-style-none
                    u-border-width-1px
                    u-border-color-gray
                    margin-bottom-1rem
                    u-background-color-white
                    u-text-color-md-grey-900">
          Word to the Dalai Lama!

      {%- endfor %}
      {%- endfor %}
      {%- endfor %}

So these render out and then the gulp task attempts to copy that block to another place in the document, before syntax highlighting is run on all of it.  Node runs into memory issues on the copy and append.


来源: stackexchange

问:
using "like" to compare a string with two wildcards VBA
I am comparing two sheets of data. One on sheet, I have a bunch of strings like this: "Apples - are good (YES)" while on the other sheet, I have strings like this "Apples - YES" . in this scenario, the two strings should be compared as the same. When the original data was compiled, there was no naming standard between the two sources. This means that when im using the "like" function, I need it to handle two separate wildcards because there are two parts of the string that need to be compared. What I have right now:  </p>

```<code> Dim TorF as Boolean
 TorF = stringToCompare Like subString1 & "*YES*"
</code>```

<p>I know my function as a whole is sound, because previously I was only using one wildcard and simply ignoring any strings that contained "-". However, now I actually have to deal with the extra results. </p>

答:
You can do this by searching the substring1 and "YES" within your stringToCompare and proceed with your code when True:

```<code>If InStr(1, stringToCompare, subString1, vbTextCompare) > 0 And InStr(1, stringToCompare, "YES", vbTextCompare) > 0 Then
        'your code
End If
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am comparing two sheets of data. One on sheet, I have a bunch of strings like this: "Apples - are good (YES)" while on the other sheet, I have strings like this "Apples - YES" . in this scenario, the two strings should be compared as the same. When the original data was compiled, there was no naming standard between the two sources. This means that when im using the "like" function, I need it to handle two separate wildcards because there are two parts of the string that need to be compared. What I have right now:

 Dim TorF as Boolean
 TorF = stringToCompare Like subString1 & "*YES*"

I know my function as a whole is sound, because previously I was only using one wildcard and simply ignoring any strings that contained "-". However, now I actually have to deal with the extra results.

Body:
You can do this by searching the substring1 and "YES" within your stringToCompare and proceed with your code when True:

If InStr(1, stringToCompare, subString1, vbTextCompare) > 0 And InStr(1, stringToCompare, "YES", vbTextCompare) > 0 Then
        'your code
End If


问:
Rails Dynamic Controller Authentication (Devise + Cookie or Token + Headers)
SO...

I currently have 2 rails controllers: one for devise authentication and another for token authentication. I am trying to create a new controller that can be used to use devise authentication when a cookie is present or token authentication using headers when the cookie is not present.

My instinct is to have my new controller have 2 variables, one of each type of authentication controller and use a before_action or before_filter that will check for the cookie and forward the request to the correct controller.

Note that my devise authentication controller has a before_action :authenticate_user! and my token authentication controller has a before_action :authenticate_using_headers, but I only would like 1 called depending on the manner of which my API is hit.

Any insight on how I can achieve this elegantly with minimal changes to my existing controllers is appreciated.

答:
If authenticate_using_headers returns nil or false if the authentication fails, you can do this in your application_controller

```<code>def authenticate_token_or_user!
  authenticate_using_headers || authenticate_user!
end
</code>```

Then in controllers where you want to enable both:

```<code>before_filter :authenticate_token_or_user!
</code>```

Body:
If authenticate_using_headers returns nil or false if the authentication fails, you can do this in your application_controller

def authenticate_token_or_user!
  authenticate_using_headers || authenticate_user!
end

Then in controllers where you want to enable both:

before_filter :authenticate_token_or_user!


问:
Eclipse action/macros
Does anybody know how to force Eclipse to do some actions after its starting?
e.g. to open a file, to click some menu item, to change properties in dialog etc.

Thanks

答: Escripts is an eclipse scripting plugin. At this link you will see, that after installing and creating your script, how you can have it executed by simply changing your shortcut you use to start eclipse.</p>

ContentLicense: CC BY-SA 2.5

Title: Eclipse action/macros


问:
.NET Core serving HTML file outside wwwroot can't load JS files
I am experimenting with different ways to secure an Angular CLI app with .NET Core Authorization.

To make it as secure as possible, I would like to keep all of the Angular CLI output files from being publicly available and keep them in the default "dist" folder preconfigured by the CLI.

I can load the index.html from an authorized controller by returning a PhysicalFileResult...

```<code>public IActionResult Index()
{
    return PhysicalFile(Path.Combine(Directory.GetCurrentDirectory(), "dist", "index.html"),"text/HTML");
}
</code>```

But I get 404s on all of the bundle.js files when the page loads.

Is it possible to serve the app this way without involving the static file middleware or making the files publicly available (preferably without having to manually change the src for each bundled js file in index.html)?

答: Take a look at this article from the asp.net core docs (excerpt included below): https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files#static-file-authorization

Body:
I am experimenting with different ways to secure an Angular CLI app with .NET Core Authorization.

To make it as secure as possible, I would like to keep all of the Angular CLI output files from being publicly available and keep them in the default "dist" folder preconfigured by the CLI.

I can load the index.html from an authorized controller by returning a PhysicalFileResult...

public IActionResult Index()
{
    return PhysicalFile(Path.Combine(Directory.GetCurrentDirectory(), "dist", "index.html"),"text/HTML");
}

But I get 404s on all of the bundle.js files when the page loads.

Is it possible to serve the app this way without involving the static file middleware or making the files publicly available (preferably without having to manually change the src for each bundled js file in index.html)?


问:
Excel macro - Export to PDF
I have a work book that has many macros to export various worksheets as pdfs in the same location the workbook is saved.

My issue is, if the workbook is saved in a folder on the desktop, then the PDFs are generated just fine.

When the workbook is saved on a network location, the pdfs don't generate. below is a sample of the macro:

```<code>Sub PDF_CStmtP()

    Application.ScreenUpdating = False

    ThisWorkbook.Sheets(Array("C Stmt - P")).Select

    pdfname = fileSaveName
    ChDir ActiveWorkbook.Path & "\"
    fileSaveName = "Closing Statement (Purchase)"

     ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        fileSaveName _
        , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
        :=False, OpenAfterPublish:=False

    Application.ScreenUpdating = True

    ActiveWorkbook.Sheets("Main Menu").Activate

    MsgBox "File Saved " & " " & fileSaveName
End Sub
</code>```

答:
Your issue is the ChDir command, see here for an explanation: https://www.techonthenet.com/excel/formulas/chdir.php

The important part of this is "The CHDIR statement lets you change the current directory on the current drive. If you need to change drives, try using the CHDRIVE statement first."

When you are trying to save to a network drive you are changing the drive letter from C:\ to whatever the network drive is mapped to, in my case it was U:\ .

The simple fix to your code is to move the Path from ChDir to just being in the filename, so your code should look like:

```<code>Sub PDF_CStmtP()

Application.ScreenUpdating = False

ThisWorkbook.Sheets(Array("C Stmt - P")).Select

pdfname = fileSaveName
'ChDir ActiveWorkbook.Path & "\"
fileSaveName = ActiveWorkbook.Path & "\" & "Closing Statement (Purchase)"

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= fileSaveName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False

Application.ScreenUpdating = True

ActiveWorkbook.Sheets("Main Menu").Activate

MsgBox "File Saved " & " " & fileSaveName
End Sub
</code>```

There are a few other edits you could make to clean it up, but this will solve the issue at hand.

**Based on the comment about the message box, you could change the code to this:

```<code>Sub PDF_CStmtP()

Application.ScreenUpdating = False

ThisWorkbook.Sheets(Array("C Stmt - P")).Select

pdfname = "Closing Statement (Purchase)"
'ChDir ActiveWorkbook.Path & "\"
fileSaveName = ActiveWorkbook.Path & "\" & pdfname

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= fileSaveName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False

Application.ScreenUpdating = True

ActiveWorkbook.Sheets("Main Menu").Activate

MsgBox "File Saved " & " " & pdfname
End Sub
</code>```

Title: Excel macro - Export to PDF

Body:
I have a work book that has many macros to export various worksheets as pdfs in the same location the workbook is saved.

My issue is, if the workbook is saved in a folder on the desktop, then the PDFs are generated just fine.

When the workbook is saved on a network location, the pdfs don't generate. below is a sample of the macro:

Sub PDF_CStmtP()

    Application.ScreenUpdating = False

    ThisWorkbook.Sheets(Array("C Stmt - P")).Select

    pdfname = fileSaveName
    ChDir ActiveWorkbook.Path & "\"
    fileSaveName = "Closing Statement (Purchase)"

     ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        fileSaveName _
        , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
        :=False, OpenAfterPublish:=False

    Application.ScreenUpdating = True

    ActiveWorkbook.Sheets("Main Menu").Activate

    MsgBox "File Saved " & " " & fileSaveName
End Sub

Body:
Your issue is the ChDir command, see here for an explanation: https://www.techonthenet.com/excel/formulas/chdir.php

The important part of this is "The CHDIR statement lets you change the current directory on the current drive. If you need to change drives, try using the CHDRIVE statement first."

When you are trying to save to a network drive you are changing the drive letter from C:\ to whatever the network drive is mapped to, in my case it was U:\ .

The simple fix to your code is to move the Path from ChDir to just being in the filename, so your code should look like:

Sub PDF_CStmtP()

Application.ScreenUpdating = False

ThisWorkbook.Sheets(Array("C Stmt - P")).Select

pdfname = fileSaveName
'ChDir ActiveWorkbook.Path & "\"
fileSaveName = ActiveWorkbook.Path & "\" & "Closing Statement (Purchase)"

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= fileSaveName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False

Application.ScreenUpdating = True

ActiveWorkbook.Sheets("Main Menu").Activate

MsgBox "File Saved " & " " & fileSaveName
End Sub

There are a few other edits you could make to clean it up, but this will solve the issue at hand.

**Based on the comment about the message box, you could change the code to this:

Sub PDF_CStmtP()

Application.ScreenUpdating = False

ThisWorkbook.Sheets(Array("C Stmt - P")).Select

pdfname = "Closing Statement (Purchase)"
'ChDir ActiveWorkbook.Path & "\"
fileSaveName = ActiveWorkbook.Path & "\" & pdfname

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= fileSaveName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False

Application.ScreenUpdating = True

ActiveWorkbook.Sheets("Main Menu").Activate

MsgBox "File Saved " & " " & pdfname
End Sub


问:
Autoprefixer hell - Rails
So, I'm trying to precompile my assets in Ruby on Rails, but every time I do it gives me:

autoprefixer: /Desktop/Job/RailsApp/app/assets/stylesheets/application.scss:32473:3: Gradient has outdated direction syntax. New syntax is liketo leftinstead ofright.

Now, I understand that the linear-gradientnew syntax should be like it says, "to left" instead of "right". And if it's "top" then it should be "to bottom". I've gone through all of my css files and changed all of those lines of code to conform to the syntax.

But, I'm still getting that "error"? Which seems to be slowing down my page loading on my web-rails/app.

More or less, my question is if anyone knows how to fix this?

Also, is there any way for me to look at the application.scss and decifer the ":32473:3"? I've looked in that file and formatted the code for scss, but when I look at the 32,473rd line there isn't any "linear-gradient" there...

I have a mix of scss and css files, I don't know if that makes a difference when precompiling?

I'm using:

Rails 4.2.6

ruby 2.2.3p173

答:
Despite autoprefixer saying "New syntax is like to left instead of right" it had to do with the top to bottom syntax for me.

ERROR:

```<code> background: linear-gradient(top, #f5c304 50%,#d6a900 100%);
</code>```

NO ERROR:

```<code> background: linear-gradient(to bottom, #f5c304 50%,#d6a900 100%);
</code>```

Title: Autoprefixer hell - Rails

Body:
Despite autoprefixer saying "New syntax is like to left instead of right" it had to do with the top to bottom syntax for me.

ERROR:

 background: linear-gradient(top, #f5c304 50%,#d6a900 100%);

NO ERROR:

 background: linear-gradient(to bottom, #f5c304 50%,#d6a900 100%);


问:
Chaining & to_proc on symbol
It's well known to Rubyist & will call to_proc on a symbol, so

```<code>[:a, :b, :c].map(&:to_s)
</code>```

is equivalent to

```<code>[:a, :b, :c].map { |e| e.to_s } # => ["a", "b", "c"]
</code>```

Say I want to call another method right after to_s, these two implementations will work:

```<code>[:a, :b, :c].map { |e| e.to_s.upcase }
[:a, :b, :c].map(&:to_s).map(&:upcase)
</code>```

My question is, is there a way to chain the & Symbol#to_proc call in one parameter? Something like:

```<code>[:a, :b, :c].map(&:to_s:upcase)
</code>```

Thanks!

答:
So just for fun (and to prove that almost anything is possible in ruby if one puts in a bit of effort) we could define a method on Symbol (we'll call it Symbol#chain) to provide this functionality and a little more

```<code>class Symbol
  def proc_chain(*args)
    args.inject(self.to_proc) do |memo,meth|
      meth, *passable_args = [meth].flatten
      passable_block = passable_args.pop if passable_args.last.is_a?(Proc)
      Proc.new do |obj|
        memo.call(obj).__send__(meth,*passable_args,&passable_block)
      end
    end
  end
  alias_method :chain, :proc_chain
end
</code>```

This can then be called like so

```<code>[:a, :b, :c].map(&:to_s.chain(:upcase))
#=> ["A","B","C"]
# Or with Arguments & blocks
[1,2,3,4,5].map(&:itself.chain([:to_s,2],:chars,[:map,->(e){ "#{e}!!!!"}]))
#=>  => [["1!!!!"], ["1!!!!", "0!!!!"], ["1!!!!", "1!!!!"],
#        ["1!!!!","0!!!!", "0!!!!"], ["1!!!!", "0!!!!", "1!!!!"]]
</code>```

Can even be used as a standalone

```<code>p = :to_s.chain([:split,'.'])
p.call(123.45)
#=> ["123","45"]
# Or even
[123.45,76.75].map(&p)
#=> => [["123", "45"], ["76", "75"]]
</code>```

Title: Chaining & to_proc on symbol

Body:
It's well known to Rubyist & will call to_proc on a symbol, so

[:a, :b, :c].map(&:to_s)

is equivalent to

[:a, :b, :c].map { |e| e.to_s } # => ["a", "b", "c"]

Say I want to call another method right after to_s, these two implementations will work:

[:a, :b, :c].map { |e| e.to_s.upcase }
[:a, :b, :c].map(&:to_s).map(&:upcase)

My question is, is there a way to chain the & Symbol#to_proc call in one parameter? Something like:

[:a, :b, :c].map(&:to_s:upcase)

Thanks!

Body:
So just for fun (and to prove that almost anything is possible in ruby if one puts in a bit of effort) we could define a method on Symbol (we'll call it Symbol#chain) to provide this functionality and a little more

class Symbol
  def proc_chain(*args)
    args.inject(self.to_proc) do |memo,meth|
      meth, *passable_args = [meth].flatten
      passable_block = passable_args.pop if passable_args.last.is_a?(Proc)
      Proc.new do |obj|
        memo.call(obj).__send__(meth,*passable_args,&passable_block)
      end
    end
  end
  alias_method :chain, :proc_chain
end

This can then be called like so

[:a, :b, :c].map(&:to_s.chain(:upcase))
#=> ["A","B","C"]
# Or with Arguments & blocks
[1,2,3,4,5].map(&:itself.chain([:to_s,2],:chars,[:map,->(e){ "#{e}!!!!"}]))
#=>  => [["1!!!!"], ["1!!!!", "0!!!!"], ["1!!!!", "1!!!!"],
#        ["1!!!!","0!!!!", "0!!!!"], ["1!!!!", "0!!!!", "1!!!!"]]

Can even be used as a standalone

p = :to_s.chain([:split,'.'])
p.call(123.45)
#=> ["123","45"]
# Or even
[123.45,76.75].map(&p)
#=> => [["123", "45"], ["76", "75"]]


问:
Android custom enum for xml tag
I want to declare enum somewhere in xml/java class, no matter.

Just simple

```<code>enum myEnum {
    FIRST,
    SECOND
}
</code>```

Or declare it somehow in xml.

And then use it in xml.

What I need as result:

```<code><TextView>
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:tag="myEnum/FIRST"
</TextView>

<Button>
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:tag="myEnum/SECOND"
</Button>
</code>```

etc.

Is something like that possible?

PS. I need something, that would work with any standart view.

答:
In attrs.xml add following:

```<code>  <declare-styleable name="TextView">
    <attr name="font" format="enum">
        <enum name="light" value="0" />
        <enum name="normal" value="1" />
        <enum name="bold" value="2" />
        <enum name="roboto_light" value="3" />
        <enum name="roboto_regular" value="4" />
    </attr>
</declare-styleable>
</code>```

Use in following way in custom text view:

```<code>package com.rxmedicalapp.customviews;

public class TextView extends AppCompatTextView {
public TextView(Context context) {
    super(context);
    init(null);
}

public TextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(attrs);
}

public TextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(attrs);
}

private void init(AttributeSet attrs) {
    if (attrs != null) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.TextView);
        int fontCode = a.getInt(R.styleable.TextView_font,Integer.MAX_VALUE);

        Typeface myTypeface=null;
        switch (fontCode){
            case 0:
                myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/helvetica_light.ttf");
                break;

            case 1:
                myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/helvetica_regular.ttf");
                break;

            case 2:
                myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/helvetica_bold.ttf");
                break;

            case 3:
                myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/robotolight.ttf");
                break;

            case 4:
                myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/robotoregular.ttf");
                break;

            default:
                myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/robotoregular.ttf");
                break;

        }

        setTypeface(myTypeface);

        a.recycle();
    }
}

public void setUnderLine(boolean underlined){

}
</code>```

}

Title: Android custom enum for xml tag

Body:
I want to declare enum somewhere in xml/java class, no matter.

Just simple

enum myEnum {
    FIRST,
    SECOND
}

Or declare it somehow in xml.

And then use it in xml.

What I need as result:

<TextView>
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:tag="myEnum/FIRST"
</TextView>

<Button>
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:tag="myEnum/SECOND"
</Button>

etc.

Is something like that possible?

PS. I need something, that would work with any standart view.

Body:
In attrs.xml add following:

  <declare-styleable name="TextView">
    <attr name="font" format="enum">
        <enum name="light" value="0" />
        <enum name="normal" value="1" />
        <enum name="bold" value="2" />
        <enum name="roboto_light" value="3" />
        <enum name="roboto_regular" value="4" />
    </attr>
</declare-styleable>

Use in following way in custom text view:

package com.rxmedicalapp.customviews;

public class TextView extends AppCompatTextView {
public TextView(Context context) {
    super(context);
    init(null);
}

public TextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init(attrs);
}

public TextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(attrs);
}

private void init(AttributeSet attrs) {
    if (attrs != null) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.TextView);
        int fontCode = a.getInt(R.styleable.TextView_font,Integer.MAX_VALUE);

        Typeface myTypeface=null;
        switch (fontCode){
            case 0:
                myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/helvetica_light.ttf");
                break;

            case 1:
                myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/helvetica_regular.ttf");
                break;

            case 2:
                myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/helvetica_bold.ttf");
                break;

            case 3:
                myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/robotolight.ttf");
                break;

            case 4:
                myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/robotoregular.ttf");
                break;

            default:
                myTypeface = Typeface.createFromAsset(getContext().getAssets(), "fonts/robotoregular.ttf");
                break;

        }

        setTypeface(myTypeface);

        a.recycle();
    }
}

public void setUnderLine(boolean underlined){

}

}


问:
Why is this python loop containing consecutive duplicate items breaking?
I am attempting solve this problem. In the problem am required to iterate over a list of directions (NORTH, SOUTH, EAST, WEST) and discard any adjacent opposite directions (NORTH and SOUTH, EAST and WEST) to return a reduced array containing only non-redundant directions. When I iterate over a list that does not contain consecutive duplicates, such as ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"], my code works fine, but it breaks when I iterate over a list with consecutive duplicates, like ['EAST', 'EAST', 'WEST']. Why is my code doing this, and how can I fix it to handle consecutive duplicates?

```<code>def dirReduc(arr):
  for direction in arr[:-1]:
    try:
      gotdata = arr[arr.index(direction)+1]
    except IndexError:
      gotdata = 'null'
    except ValueError:
      gotdata = 'null'
    if gotdata is 'null':
      if arr == dirReduc(arr):
        return arr
      else:
        return dirReduc(arr)
    elif cancel_pair(direction, arr[arr.index(direction)+1]):
      del arr[arr.index(direction):arr.index(direction)+2]
  return arr

def cancel_pair(dir1, dir2):
  if dir1 in ('NORTH') and dir2 in ('SOUTH') or dir1 in ('SOUTH') and dir2 in ('NORTH'):
    return True
  elif dir1 in ('WEST') and dir2 in ('EAST') or dir1 in ('EAST') and dir2 in ('WEST'):
    return True
  return False
</code>```

答:
A for loop is not a good match for this problem. If you delete a pair of items, you may need to backtrack to see if a new pair was created. A while loop is much more natural:

```<code>opposite_directions = {
    "NORTH": "SOUTH",
    "SOUTH": "NORTH",
    "EAST": "WEST",
    "WEST": "EAST"
}

def dirReduc(arr):
    i = 0
    while i < len(arr) - 1:
        if arr[i] == opposite_directions[arr[i+1]]:
            del arr[i:i+2]
            if i > 0:
                i -= 1 # back up a step if we just deleted some moves from the middle
        else:
            i += 1
    return arr
</code>```

I also replaced your cancel_pairs function with a simple dictionary lookup. Python's dictionaries are great, and they're often a better choice than a complicated if/else block.

Body:
I am attempting solve this problem. In the problem am required to iterate over a list of directions (NORTH, SOUTH, EAST, WEST) and discard any adjacent opposite directions (NORTH and SOUTH, EAST and WEST) to return a reduced array containing only non-redundant directions. When I iterate over a list that does not contain consecutive duplicates, such as ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"], my code works fine, but it breaks when I iterate over a list with consecutive duplicates, like ['EAST', 'EAST', 'WEST']. Why is my code doing this, and how can I fix it to handle consecutive duplicates?

def dirReduc(arr):
  for direction in arr[:-1]:
    try:
      gotdata = arr[arr.index(direction)+1]
    except IndexError:
      gotdata = 'null'
    except ValueError:
      gotdata = 'null'
    if gotdata is 'null':
      if arr == dirReduc(arr):
        return arr
      else:
        return dirReduc(arr)
    elif cancel_pair(direction, arr[arr.index(direction)+1]):
      del arr[arr.index(direction):arr.index(direction)+2]
  return arr

def cancel_pair(dir1, dir2):
  if dir1 in ('NORTH') and dir2 in ('SOUTH') or dir1 in ('SOUTH') and dir2 in ('NORTH'):
    return True
  elif dir1 in ('WEST') and dir2 in ('EAST') or dir1 in ('EAST') and dir2 in ('WEST'):
    return True
  return False

Body:
A for loop is not a good match for this problem. If you delete a pair of items, you may need to backtrack to see if a new pair was created. A while loop is much more natural:

opposite_directions = {
    "NORTH": "SOUTH",
    "SOUTH": "NORTH",
    "EAST": "WEST",
    "WEST": "EAST"
}

def dirReduc(arr):
    i = 0
    while i < len(arr) - 1:
        if arr[i] == opposite_directions[arr[i+1]]:
            del arr[i:i+2]
            if i > 0:
                i -= 1 # back up a step if we just deleted some moves from the middle
        else:
            i += 1
    return arr

I also replaced your cancel_pairs function with a simple dictionary lookup. Python's dictionaries are great, and they're often a better choice than a complicated if/else block.


问:
min and max in multidimensional-array
hi i am trying to find min and max values of x and y how can i find this min and max functions is not working correctly</p>

```<code>$dataPoints = array(
 array('x' => 2343, 'y' => 4322),
  array('x' => 103, 'y' => 303 ),
  array('x' => 2345,'y' => 2321 ),
  array('x' => 310, 'y' => 2044 ),
  array('x' => 173, 'y' => 793 ),
  array('x' => 456, 'y' => 2675),
  array('x' => 24, 'y' => 819 ));
</code>```

答:
I thinik you will have to write your own function:</p>

```<code><?php
    function max_with_key($array, $key) {
        if (!is_array($array) || count($array) == 0) return false;
        $max = $array[0][$key];
        foreach($array as $a) {
            if($a[$key] > $max) {
                $max = $a[$key];
            }
        }
        return $max;
    }

    $dataPoints = array(
     array('x' => 2343, 'y' => 4322),
      array('x' => 103, 'y' => 303 ),
      array('x' => 2345,'y' => 2321 ),
      array('x' => 310, 'y' => 2044 ),
      array('x' => 173, 'y' => 793 ),
      array('x' => 456, 'y' => 2675),
      array('x' => 24, 'y' => 819 ));

    $max_x = max_with_key($dataPoints, 'x');  //2343
    $max_y = max_with_key($dataPoints, 'y');  //4322
?>
</code>```

Title: min and max in multidimensional-array

Body:
hi i am trying to find min and max values of x and y how can i find this min and max functions is not working correctly

$dataPoints = array(
 array('x' => 2343, 'y' => 4322),
  array('x' => 103, 'y' => 303 ),
  array('x' => 2345,'y' => 2321 ),
  array('x' => 310, 'y' => 2044 ),
  array('x' => 173, 'y' => 793 ),
  array('x' => 456, 'y' => 2675),
  array('x' => 24, 'y' => 819 ));

Body:
I thinik you will have to write your own function:

<?php
    function max_with_key($array, $key) {
        if (!is_array($array) || count($array) == 0) return false;
        $max = $array[0][$key];
        foreach($array as $a) {
            if($a[$key] > $max) {
                $max = $a[$key];
            }
        }
        return $max;
    }

    $dataPoints = array(
     array('x' => 2343, 'y' => 4322),
      array('x' => 103, 'y' => 303 ),
      array('x' => 2345,'y' => 2321 ),
      array('x' => 310, 'y' => 2044 ),
      array('x' => 173, 'y' => 793 ),
      array('x' => 456, 'y' => 2675),
      array('x' => 24, 'y' => 819 ));

    $max_x = max_with_key($dataPoints, 'x');  //2343
    $max_y = max_with_key($dataPoints, 'y');  //4322
?>


问:
Django foreign key selection
I am making a simple Django application that records the performance of running athletes. The models for the application look like this:

```<code>class Athlete(models.Model):
    name = models.CharField(max_length=30)
    nationality = models.CharField(max_length=30)

class TrainingSession(models.Model):
    training_date = models.DateTimeField()
    location = models.CharField(max_length=30)
    athlete = models.ForeignKey(Athlete)

class Run(models.Model):
    run_time = models.IntegerField()
    training = models.ForeignKey(TrainingSession)
</code>```

An athlete has multiple training sessions and in each of those sessions, the athlete runs multiple times (each time, his time will be recorded in seconds).

I found out that I can easily make queries between these models, however, I still struggle with the following problem:
I want to select the runners that CONSISTENTLY run between for example 20 and 30 seconds. When I select runners like this:

```<code>athletes = Athlete.filter(trainingsession__run__run_time__range=[20,30]).distinct()
</code>```

I get all athletes that once ran between 20 and 30 seconds, but also athletes that once ran 35 seconds. Can you help me to solve this? Hopefully, there's a Django query that makes this easy!

答:
You can find one more queryset of athletes who ran in <20 or >30 seconds and exclude them from your athletes queryset. you can use Q()
to perform an OR query.

```<code>excluded_athletes = Athlete.filter(Q(trainingsession__run__run_time__gte=30)|Q(trainingsession__run__run_time__lte=20)).distinct().values_list('id',flat=True)
athletes = Athlete.filter(trainingsession__run__run_time__range=[20,30]).distinct()
athletes.exclude(id__in=excluded_athletes)
</code>```

Title: Django foreign key selection

Body:
I am making a simple Django application that records the performance of running athletes. The models for the application look like this:

class Athlete(models.Model):
    name = models.CharField(max_length=30)
    nationality = models.CharField(max_length=30)

class TrainingSession(models.Model):
    training_date = models.DateTimeField()
    location = models.CharField(max_length=30)
    athlete = models.ForeignKey(Athlete)

class Run(models.Model):
    run_time = models.IntegerField()
    training = models.ForeignKey(TrainingSession)

An athlete has multiple training sessions and in each of those sessions, the athlete runs multiple times (each time, his time will be recorded in seconds).

I found out that I can easily make queries between these models, however, I still struggle with the following problem:
I want to select the runners that CONSISTENTLY run between for example 20 and 30 seconds. When I select runners like this:

athletes = Athlete.filter(trainingsession__run__run_time__range=[20,30]).distinct()

I get all athletes that once ran between 20 and 30 seconds, but also athletes that once ran 35 seconds. Can you help me to solve this? Hopefully, there's a Django query that makes this easy!

Body:
You can find one more queryset of athletes who ran in <20 or >30 seconds and exclude them from your athletes queryset. you can use Q()
to perform an OR query.

excluded_athletes = Athlete.filter(Q(trainingsession__run__run_time__gte=30)|Q(trainingsession__run__run_time__lte=20)).distinct().values_list('id',flat=True)
athletes = Athlete.filter(trainingsession__run__run_time__range=[20,30]).distinct()
athletes.exclude(id__in=excluded_athletes)


问:
Setting up Node.js with express.js on my 'portfolio' site
I'm completely new to node.js but i'm trying to implement it on my personal site so that I start learning it. I have the node server running but i'm trying to set up the routing using express.js . All my files are typical static files .html, .js, .cs, .png , etc. Currently, the route gives me my index page on the 'home' page which is goo. If I attempt to navigate to the index of another diectory, I just get the 404 error page. My file structure is like this:

Server.js
package.json
node_modules
 -- views (Folder)
    -index.html (File in views)
    --Projects (Folder in Views)
      -index.html (File in Projects)

my Server.js looks like

```<code>var express = require("express");
var app = express();
var router = express.Router();
var path = __dirname + '/views/';

router.use(function (req, res, next) {
    console.log("/" + req.method);
    next();
});

router.get("/", function (req, res) {
    res.sendFile(path + "index.html");
});

router.get("/Projects", function (req, res) {
    res.sendFile(path + "Projects/index.html");
});

app.use("/", router);

/*app.use("*", function (req, res) {
    res.sendFile(path + "404.html");
});*/

app.listen(3000, function () {
    console.log("Live at Port 3000");
});
</code>```

I've looked for the past ~18 hours at various resources and i'm just missing something i'm sure. My current idea of the issue is the navigation links in the html, however I've attempted changing those with no progress.

答:
If you have only public file (like html, css, ..) you can put everything on a /public folder and add this instead of a router.

```<code>app.use(express.static('public'))
</code>```

Doc: https://expressjs.com/en/starter/static-files.html

Every file will be accessible:

/public/my-folder/my-file.png > www.my-dmain.com/my-folder/my-file.png

Body:
I'm completely new to node.js but i'm trying to implement it on my personal site so that I start learning it. I have the node server running but i'm trying to set up the routing using express.js . All my files are typical static files .html, .js, .cs, .png , etc. Currently, the route gives me my index page on the 'home' page which is goo. If I attempt to navigate to the index of another diectory, I just get the 404 error page. My file structure is like this:

Server.js
package.json
node_modules
 -- views (Folder)
    -index.html (File in views)
    --Projects (Folder in Views)
      -index.html (File in Projects)

my Server.js looks like

var express = require("express");
var app = express();
var router = express.Router();
var path = __dirname + '/views/';

router.use(function (req, res, next) {
    console.log("/" + req.method);
    next();
});

router.get("/", function (req, res) {
    res.sendFile(path + "index.html");
});

router.get("/Projects", function (req, res) {
    res.sendFile(path + "Projects/index.html");
});

app.use("/", router);

/*app.use("*", function (req, res) {
    res.sendFile(path + "404.html");
});*/

app.listen(3000, function () {
    console.log("Live at Port 3000");
});

I've looked for the past ~18 hours at various resources and i'm just missing something i'm sure. My current idea of the issue is the navigation links in the html, however I've attempted changing those with no progress.

Body:
If you have only public file (like html, css, ..) you can put everything on a /public folder and add this instead of a router.

app.use(express.static('public'))

Doc: https://expressjs.com/en/starter/static-files.html

Every file will be accessible:

/public/my-folder/my-file.png > www.my-dmain.com/my-folder/my-file.png


问:
Angular 2/4, "ngStyle". Apply different style depeding its father element active o inactive
I need to apply a style to an element when it parent element is actived. I'm using routerLinkActive to apply CSS Class and works fine, but deppending if the father element is actite apply one inline style (display: block), in other cases apply another (display: none).

If parent element is active:

```<code><li class="active">
   <ul class="sub-menu" style="display: block;">
</li>
<li>
   <ul class="sub-menu" style="display: none;">
</li>
</code>```

When I choose another element:

```<code><li>
   <ul class="sub-menu" style="display: none;">
</li>
<li class="active">
   <ul class="sub-menu" style="display: block;">
</li>
</code>```

I have an extended list of items with their respectives Links. Each "sub-menu" has its own list of elements.

答:
If you use a boolean flag template variable:

```<code><li [class.active]="flag">
   <ul class="sub-menu" [style.display]="flag ? 'block' : 'none'">
</li>
<li>
   <ul class="sub-menu" [style.display]="flag ? 'none' : 'block'">
</li>
</code>```

You can also use the router active directive to control the flag:

```<code><li [class.active]="link.isActive" #link="routerLinkActive">
</code>```

And use link.isActive instead of flag elsewhere.

Body:
I need to apply a style to an element when it parent element is actived. I'm using routerLinkActive to apply CSS Class and works fine, but deppending if the father element is actite apply one inline style (display: block), in other cases apply another (display: none).

If parent element is active:

When I choose another element:

I have an extended list of items with their respectives Links. Each "sub-menu" has its own list of elements.

Body:
If you use a boolean flag template variable:

<li [class.active]="flag">
   <ul class="sub-menu" [style.display]="flag ? 'block' : 'none'">
</li>
<li>
   <ul class="sub-menu" [style.display]="flag ? 'none' : 'block'">
</li>

You can also use the router active directive to control the flag:

<li [class.active]="link.isActive" #link="routerLinkActive">

And use link.isActive instead of flag elsewhere.


答:
Try something like this:</p>

```<code>foreach($dataPoints as $point) {
    if (!isset($x) || $point['x'] > $x) {
        $x = $point['x'];
    }
    if (!isset($y) || $point['y'] > $y) {
        $y = $point['y'];
    }
}
</code>```

Title: min and max in multidimensional-array

Body:
Try something like this:

foreach($dataPoints as $point) {
    if (!isset($x) || $point['x'] > $x) {
        $x = $point['x'];
    }
    if (!isset($y) || $point['y'] > $y) {
        $y = $point['y'];
    }
}


答:
Q objects can help build more complex queries:
https://docs.djangoproject.com/en/1.11/topics/db/queries/#complex-lookups-with-q-objects

Maybe something like this:

```<code>athletes = Athlete.filter(
    Q(trainingsession__run__run_time__gt=20) &
    Q(trainingsession__run__run_time__lt=30)).distinct()
</code>```

Also there are some gotchas when using .distinct(). Order plays a role, and you can specify what fields to distinct on.
See the docs: https://docs.djangoproject.com/en/1.11/ref/models/querysets/#django.db.models.query.QuerySet.distinct

Title: Django foreign key selection

Body:
Q objects can help build more complex queries:
https://docs.djangoproject.com/en/1.11/topics/db/queries/#complex-lookups-with-q-objects

Maybe something like this:

athletes = Athlete.filter(
    Q(trainingsession__run__run_time__gt=20) &
    Q(trainingsession__run__run_time__lt=30)).distinct()

Also there are some gotchas when using .distinct(). Order plays a role, and you can specify what fields to distinct on.
See the docs: https://docs.djangoproject.com/en/1.11/ref/models/querysets/#django.db.models.query.QuerySet.distinct


问:
"Add to Homescreen" Banner in Rails PWA
I've made a small PWA in RoR; following and I followed Google's guide on having "Add to Homescreen" banners. Everything in devtools is fine: the service worker is registered, the manifest.json is found, the "Add to Homescreen" link is displayed and runs in the tool drawer.

I even installed Lighthouse like they said and ran the report; it says everything should work. However, I have yet to see the banner (yes, it isn't already on my homescreen; yes, I visited at least five minutes apart).

Does anyone have an idea on what the threshold is WRT users activity to make the banner appear?

(ps. does anyone want to try it out here?)

答:
There's actually a google chrome flag for bypassing those engagement checks, it's called "Bypass user engagement checks".

So you'll need to go to chrome://flags, then find that flag, enable it, and then restart chrome.

The banner should show up every time once that flag is enabled, assuming everything is in line with your manifest.json and service worker.

Title: "Add to Homescreen" Banner in Rails PWA


问:
Updating HBase data with HappyBase
I am trying to write a function to update Data from a table saved in HBase. I have a function that will get called to Update it and I have a pretty good start but I am a little bit lost on the end of finishing it. I can update single rows based one string to another, but when comparing log times, I can not seem to figure out how to do that, since there are no set log times. I am storing all of values from the table into a dictionary. Here is my code:

```<code>def updateHBase(row):

dict = row.asDict() #create a dictionary from Row

columns = dict.keys()
    for col in columns: #creates the colfamily:colname for happybase format
        dict["DriveInfo:" +col] = dict.pop(col) #adds data into rows

del dict[DriveInfo:serialnumb] #removes the row key that HBase uses, serialnum

x = table.row(row.serialnum)

if (len(x) == 0) #length of row is zero, row key does not exist
    table.put(row.serialnum, dict) #add new row is row key does not exist

else #check for health
    if (dict['health'].lower() != 'healthy') #if the row isnt healthy... next steps

        if (dict['health'].lower() != 'archived' and x['health'] == 'archived' and dict['logtime'] < x['logtime']) #update a row with a health status of archived
            table.put(row.serialnum, dict)

        else #if the row that is being replaced isn't archived, just replace the row
            table.put(row.serialnum, dict)
        return

    elif (dict['logtime'] > x['logtime'] and dict['health'].lower() == 'healthy') # new log time > old log time and health is healthy, replace the row with new data
        table.put(row.serialnum, dict)

    else
        return
</code>```

EDIT: In all of my if statements should ... dict['health'] ... be x['health']?

答:
Figured it out...</p>

```<code>def updateHBase(row):

dict = row.asDict() #create a dictionary from Row

columns = dict.keys()
    for col in columns: #creates the colfamily:colname for happybase format
        dict["DriveInfo:" +col] = dict.pop(col) #adds data into rows

del dict[DriveInfo:serialnumb] #removes the row key that HBase uses, serialnum

x = table.row(row.serialnum)

if (len(x) == 0) #length of row is zero, row key does not exist
    table.put(row.serialnum, dict) #add new row is row key does not exist

else #check for health
    if (x['health'].lower() != 'healthy') #if the row isnt healthy... next steps

        if (x['health'].lower() != 'archived' and x['health'] == 'archived') #update a row with a health status of archived
            table.put(row.serialnum, dict)

        else #if the row that is being replaced isn't archived, just replace the row
            table.put(row.serialnum, dict)
        return

    elif (x['logtime'] > row.logtime and x['health'].lower() == 'healthy') # new log time > old log time and health is healthy, replace the row with new data
        table.put(row.serialnum, dict)

    else
        return
</code>```

Title: Updating HBase data with HappyBase

Body:
I am trying to write a function to update Data from a table saved in HBase. I have a function that will get called to Update it and I have a pretty good start but I am a little bit lost on the end of finishing it. I can update single rows based one string to another, but when comparing log times, I can not seem to figure out how to do that, since there are no set log times. I am storing all of values from the table into a dictionary. Here is my code:

def updateHBase(row):

dict = row.asDict() #create a dictionary from Row

columns = dict.keys()
    for col in columns: #creates the colfamily:colname for happybase format
        dict["DriveInfo:" +col] = dict.pop(col) #adds data into rows

del dict[DriveInfo:serialnumb] #removes the row key that HBase uses, serialnum

x = table.row(row.serialnum)

if (len(x) == 0) #length of row is zero, row key does not exist
    table.put(row.serialnum, dict) #add new row is row key does not exist

else #check for health
    if (dict['health'].lower() != 'healthy') #if the row isnt healthy... next steps

        if (dict['health'].lower() != 'archived' and x['health'] == 'archived' and dict['logtime'] < x['logtime']) #update a row with a health status of archived
            table.put(row.serialnum, dict)

        else #if the row that is being replaced isn't archived, just replace the row
            table.put(row.serialnum, dict)
        return

    elif (dict['logtime'] > x['logtime'] and dict['health'].lower() == 'healthy') # new log time > old log time and health is healthy, replace the row with new data
        table.put(row.serialnum, dict)

    else
        return

EDIT: In all of my if statements should ... dict['health'] ... be x['health']?

Body:
Figured it out...

def updateHBase(row):

dict = row.asDict() #create a dictionary from Row

columns = dict.keys()
    for col in columns: #creates the colfamily:colname for happybase format
        dict["DriveInfo:" +col] = dict.pop(col) #adds data into rows

del dict[DriveInfo:serialnumb] #removes the row key that HBase uses, serialnum

x = table.row(row.serialnum)

if (len(x) == 0) #length of row is zero, row key does not exist
    table.put(row.serialnum, dict) #add new row is row key does not exist

else #check for health
    if (x['health'].lower() != 'healthy') #if the row isnt healthy... next steps

        if (x['health'].lower() != 'archived' and x['health'] == 'archived') #update a row with a health status of archived
            table.put(row.serialnum, dict)

        else #if the row that is being replaced isn't archived, just replace the row
            table.put(row.serialnum, dict)
        return

    elif (x['logtime'] > row.logtime and x['health'].lower() == 'healthy') # new log time > old log time and health is healthy, replace the row with new data
        table.put(row.serialnum, dict)

    else
        return


问:
XSLT equivalent for JSON
Is there an XSLT equivalent for JSON? Something to allow me to do transformations on JSON like XSLT does to XML.</p>

答:
One approach not yet given is to use a parser generator to create a parser in XSLT which parses JSON and produces an XML output.

One option that gets mentioned a lot at the XML conferences is the ReX parser generator (http://www.bottlecaps.de/rex/) - although totally undocumented on the site, recipes are available on searching.

Title: XSLT equivalent for JSON


问:
Getting all branches from bitbucket
I need to hand off a visual studio project that has multiple branches. Bitbucket is being used as the repo. I am trying to find a way to download the entire repo with every branch. I'm not sure if there is a solution using GIT or some feature in bitbucket that I can't find. When I try to download directly from Bitbucket I only get the master branch</p>

答:
I needed to download all branches so I could send them to a client via FTP who I couldn't give repository access to. The following worked:

git archive --format zip --output ~/pathToWhereYouWantToSave HEAD

Title: Getting all branches from bitbucket


问:
How to get the real extension type of Multipart file
I have  checked answer here, but here first they are saving it to some place and then reading it's stream and trying to check Mime type of that file

Get real file extension -Java code

But I want to know the file type before even saving it to the hard disk or at some place.

I know I can do it in these 2 more ways

```<code>File savedFile = new File(fileHandler.createTodayFolder(fileLocation) + "/" + name);
            Path path = Paths.get(file.get);
            Tika tika = new Tika();
            String checkType = tika.detect(path.toFile());
</code>```

and

```<code>          Path path = Paths.get(savedFile.getPath());
          Files.probeContentType(path)
</code>```

But in these both cases they are using somefile which is already at some location in hard disk.
I want code something like this

```<code>  public @ResponseBody ResponseEntity<?> importResume(@RequestParam(value = "name", required = false) String name,
        @RequestParam("file") MultipartFile file) {

     if (file!=DESIRED_TYPE)
     {
       return Exception;
     }
}
</code>```

Is there any way of doing this ???

答:
Given the String filename, you can do:

```<code>filename.substring(filename.lastIndexOf(".") + 1);
</code>```

Body:
I have  checked answer here, but here first they are saving it to some place and then reading it's stream and trying to check Mime type of that file

Get real file extension -Java code

But I want to know the file type before even saving it to the hard disk or at some place.

I know I can do it in these 2 more ways

File savedFile = new File(fileHandler.createTodayFolder(fileLocation) + "/" + name);
            Path path = Paths.get(file.get);
            Tika tika = new Tika();
            String checkType = tika.detect(path.toFile());

and

          Path path = Paths.get(savedFile.getPath());
          Files.probeContentType(path)

But in these both cases they are using somefile which is already at some location in hard disk.
I want code something like this

  public @ResponseBody ResponseEntity<?> importResume(@RequestParam(value = "name", required = false) String name,
        @RequestParam("file") MultipartFile file) {

     if (file!=DESIRED_TYPE)
     {
       return Exception;
     }
}

Is there any way of doing this ???

Body:
Given the String filename, you can do:

filename.substring(filename.lastIndexOf(".") + 1);

ContentLicense: CC BY-SA 4.0


问:
Julia:passing argument to the `include("file.jl")`
I was wondering if it is possible to pass arguments to include("file.jl"). For example we parse the ARGS in the file.jl and use them in there. Similar to what we do in a command line by passing arguments.

答:
Reassigning ARGS to make file.jl think it received arguments works, but leads to a warning (because it overwrites Base.ARGS). A better methods perhaps is to use isdefined to check for a different source of parameters before using ARGS in file.jl.

For example, file main.jl would be:

```<code>newARGS = String["adios","amigos"]
include("file.jl")
</code>```

and file.jl would be:

```<code>localARGS = isdefined(:newARGS) ? newARGS : ARGS
@show localARGS
</code>```

Now:

```<code>$ julia file.jl hello world
localARGS = String["hello","world"]

$ julia main.jl
localARGS = String["adios","amigos"]
</code>```

This also allows communicating deeper through several levels of inclusion.

Body:
Reassigning ARGS to make file.jl think it received arguments works, but leads to a warning (because it overwrites Base.ARGS). A better methods perhaps is to use isdefined to check for a different source of parameters before using ARGS in file.jl.

For example, file main.jl would be:

newARGS = String["adios","amigos"]
include("file.jl")

and file.jl would be:

localARGS = isdefined(:newARGS) ? newARGS : ARGS
@show localARGS

Now:

$ julia file.jl hello world
localARGS = String["hello","world"]

$ julia main.jl
localARGS = String["adios","amigos"]

This also allows communicating deeper through several levels of inclusion.