text:
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

///
/// HTTPManager is a simplified class to download/upload text files
/// <remarks>
/// Multiple files can be downloaded at the same time,  with one coroutine per download. Only one GameObject will be created for all connections.</remarks>
class HTTPManager
{
    private static GameObject network_go = null;

    ///
    /// Download a text file, and call action() when done.
    /// <param name="url">Url of the file to download</param>
    /// <param name="action">Callback with content in string or error in case of problem, and bool containing download status (true:success).</param>
    public static void Get(string url, Action<string, bool, Uri> action)
    {
        if (network_go == null)
        {
            network_go = new GameObject("NetworkManager");
            network_go.tag = Game.BG_TASKS;
        }

        //Use WebClient Class
        DataDownloader dd = network_go.AddComponent<DataDownloader>();

        dd.DownloadAsync(url, action);
    }

    ///
    /// Download an image file, and call action() when done.
    /// <param name="url">Url of the file to download</param>
    /// <param name="action">Callback with content in string or error in case of problem, and bool containing download status (true:success).</param>
    public static void GetImage(string url, Action<Texture2D, bool, Uri> action)
    {
        if (network_go == null)
        {
            network_go = new GameObject("NetworkManager");
            network_go.tag = Game.BG_TASKS;
        }

        //Use WebClient Class
        DataDownloaderImage ddi = network_go.AddComponent<DataDownloaderImage>();

        ddi.DownloadImageAsync(url, action);
    }

    ///
    /// HTTP POST content to a URL, and call action() when done.
    /// <param name="url">Url of the form to upload to</param>
    /// <param name="content">Content to POST</param>
    /// <param name="action">Callback with error in string in case of problem, and bool containing upload status (true:success).</param>
    public static void Upload(string url, WWWForm content, Action<string, bool> action)
    {
        if (network_go == null)
        {
            network_go = new GameObject("NetworkManager");
            network_go.tag = Game.BG_TASKS;
        }

        //Use WebClient Class
        DataUploader du = network_go.AddComponent<DataUploader>();

        du.PostFormAsync(url, content, action);
    }

}

class DataDownloader : MonoBehaviour
{
    private Uri uri = null;
    private Action<string, bool, Uri> callback_action=null;

    public void DownloadAsync(string url, Action<string, bool, Uri> action)
    {
        uri = new Uri(url);
        callback_action = action;

        StartCoroutine(GetData());
    }

    private IEnumerator GetData()
    {
        UnityWebRequest www_get = UnityWebRequest.Get(uri);
        yield return www_get.SendWebRequest();

        if (www_get.isNetworkError)
        {
            // Most probably a connection error
            Debug.Log("Error downloading data : most probably a connectivity issue (please check your internet connection)");
            callback_action("ERROR NETWORK", true, uri);
        }
        else if (www_get.isHttpError)
        {
            // Most probably a connection error
            Debug.Log("Error downloading data : HTTP error " + www_get.responseCode + " most probably a connection error (server error)");
            callback_action(www_get.error + " " + www_get.responseCode, true, uri);
        }
        else
        {
            // download OK
            callback_action(www_get.downloadHandler.text, false, uri);
        }
    }
}

class DataDownloaderImage : MonoBehaviour
{
    private Uri uri = null;
    private Action<Texture2D, bool, Uri> callback_action_img = null;

    public void DownloadImageAsync(string url, Action<Texture2D, bool, Uri> action)
    {
        uri = new Uri(url);
        callback_action_img = action;

        StartCoroutine(GetData());
    }

    private IEnumerator GetData()
    {
        UnityWebRequest www_get = UnityWebRequestTexture.GetTexture(uri);
        yield return www_get.SendWebRequest();

        if (www_get.isNetworkError)
        {
            // Most probably a connection error
            Debug.Log("Error downloading data : most probably a connectivity issue (please check your internet connection)");
            callback_action_img(null, true, uri);
        }
        else if (www_get.isHttpError)
        {
            // Most probably a connection error
            Debug.Log("Error downloading data : HTTP error " + www_get.responseCode + " most probably a connection error (server error)");
            callback_action_img(null, true, uri);
        }
        else
        {
            // download OK
            callback_action_img(DownloadHandlerTexture.GetContent(www_get), false, uri);
        }
    }
}

class DataUploader : MonoBehaviour
{
    private Uri uri = null;
    private WWWForm formFields = null;
    private Action<string, bool> callback_action = null;

    public void PostFormAsync(string url, WWWForm content, Action<string, bool> action)
    {
        uri = new Uri(url);
        formFields = content;
        callback_action = action;

        StartCoroutine(PostForm());
    }

    private IEnumerator PostForm()
    {
        UnityWebRequest www_post = UnityWebRequest.Post(uri, formFields);

        yield return www_post.SendWebRequest();

        if (www_post.isNetworkError)
        {
            // Most probably a connection error
            callback_action("ERROR NETWORK", true);
            Debug.Log("Error uploading data : most probably a connectivity issue (please check your internet connection)");
        }
        else if (www_post.isHttpError)
        {
            // Most probably a connection error
            callback_action(www_post.error + " " + www_post.responseCode, true);
            Debug.Log("Error uploading data : most probably a connection error (server error)");
        }
        else
        {
            // download OK
            callback_action(www_post.downloadHandler.text, false);
        }

    }
}


text:
import { DestinyAccount } from 'app/accounts/destiny-account';
import { createLoadoutShare } from 'app/dim-api/dim-api';
import Sheet from 'app/dim-ui/Sheet';
import UserGuideLink from 'app/dim-ui/UserGuideLink';
import { t } from 'app/i18next-t';
import { convertDimLoadoutToApiLoadout } from 'app/loadout-drawer/loadout-type-converters';
import { Loadout } from 'app/loadout-drawer/loadout-types';
import { showNotification } from 'app/notifications/notifications';
import ErrorPanel from 'app/shell/ErrorPanel';
import { copyIcon, shareIcon } from 'app/shell/icons';
import AppIcon from 'app/shell/icons/AppIcon';
import { copyString, count } from 'app/utils/util';
import React, { useEffect, useState } from 'react';
import styles from './LoadoutShareSheet.m.scss';

// Cache shares to loadouts weakly, to cut down on creating shares
const loadoutShares = new WeakMap<Loadout, string>();

export default function LoadoutShareSheet({
  account,
  loadout,
  onClose,
}: {
  account: DestinyAccount;
  loadout: Loadout;
  onClose: () => void;
}) {
  const [shareUrl, setShareUrl] = useState<string | undefined>(loadoutShares.get(loadout));
  const [shareError, setShareError] = useState<Error>();

  useEffect(() => {
    let canceled = false;
    (async () => {
      try {
        const shareUrl =
          loadoutShares.get(loadout) ??
          (await createLoadoutShare(account.membershipId, convertDimLoadoutToApiLoadout(loadout)));
        loadoutShares.set(loadout, shareUrl);
        if (!canceled) {
          setShareUrl(shareUrl);
        }
      } catch (e) {
        if (!canceled) {
          setShareError(e);
        }
      }
    })();
    return () => {
      canceled = true;
    };
  }, [account.membershipId, loadout]);

  const handleCopy = () => {
    if (!shareUrl) {
      return;
    }
    copyString(shareUrl);
    showNotification({
      type: 'success',
      title: t('Loadouts.Share.Copied'),
    });
  };

  const handleShare = async (closeSheet: () => void) => {
    if (!shareUrl || !('share' in navigator)) {
      return;
    }
    await navigator.share({ url: shareUrl });
    closeSheet();
  };

  const handleFocusUrl = (e: React.FocusEvent<HTMLInputElement>) => e.target.select();

  const canShare = 'canShare' in navigator && navigator.canShare({ url: shareUrl });

  const numMods = loadout.parameters?.mods?.length ?? 0;
  const numItems = count(loadout.items, (i) => !i.socketOverrides);
  const hasFashion = Boolean(loadout.parameters?.modsByBucket);
  const hasSubclass = loadout.items.some((i) => i.equip && i.socketOverrides);
  const hasLoParams =
    loadout.parameters &&
    (loadout.parameters.query ||
      loadout.parameters.exoticArmorHash ||
      loadout.parameters.statConstraints?.some(
        (s) => s.maxTier !== undefined || s.minTier !== undefined
      ));

  return (
    <Sheet
      onClose={onClose}
      header={
        <>

{t('Loadouts.Share.Title', { name: loadout.name })}

          <UserGuideLink topic="Share-Loadouts" />
        </>
      }
      sheetClassName={styles.sheet}
    >
      {({ onClose }) => (

          {shareError ? (
            <ErrorPanel title={t('Loadouts.Share.Error')} error={shareError} />
          ) : (

                {t('Loadouts.Share.Summary')}

                  {numItems > 0 &&
{t('Loadouts.Share.NumItems', { count: numItems })}
}
                  {numMods > 0 &&
{t('Loadouts.Share.NumMods', { count: numItems })}
}
                  {hasFashion &&
{t('Loadouts.Share.Fashion')}
}
                  {hasSubclass &&
{t('Loadouts.Share.Subclass')}
}
                  {hasLoParams &&
{t('Loadouts.Share.LoadoutOptimizer')}
}
                  {loadout.notes &&
{t('Loadouts.Share.Notes')}
}

                <input
                  onFocus={handleFocusUrl}
                  value={shareUrl ?? ''}
                  placeholder={t('Loadouts.Share.Placeholder')}
                  readOnly
                />
                {canShare ? (
                  <button
                    type="button"
                    className="dim-button"
                    onClick={() => handleShare(onClose)}
                    disabled={!shareUrl}
                  >
                    <AppIcon icon={shareIcon} /> {t('Loadouts.Share.NativeShare')}
                  </button>
                ) : (
                  <button
                    type="button"
                    className="dim-button"
                    onClick={handleCopy}
                    disabled={!shareUrl}
                  >
                    <AppIcon icon={copyIcon} /> {t('Loadouts.Share.CopyButton')}
                  </button>
                )}

          )}

      )}
    </Sheet>
  );
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView android:textStyle="bold" android:id="@id/title" android:paddingRight="7.0dip" android:layout_width="wrap_content" android:layout_height="wrap_content" android:paddingEnd="7.0dip" />
    <TextView android:id="@id/content" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_toRightOf="@id/title" android:layout_toEndOf="@id/title" />
</RelativeLayout>


text:
#ifndef sodium_version_H
#define sodium_version_H

#include <sodium/export.h>

/* IMPORTANT: As we don't use autotools, these version are not automatically
   updated if we change submodules. They need to be changed manually.
*/

#define SODIUM_VERSION_STRING "1.0.12-idf"

/* Note: these are not the same as the overall version, see
   configure.ac for the relevant macros */
#define SODIUM_LIBRARY_VERSION_MAJOR 9
#define SODIUM_LIBRARY_VERSION_MINOR 4

#ifdef __cplusplus
extern "C" {
#endif

SODIUM_EXPORT
const char *sodium_version_string(void);

SODIUM_EXPORT
int         sodium_library_version_major(void);

SODIUM_EXPORT
int         sodium_library_version_minor(void);

#ifdef __cplusplus
}
#endif

#endif


text:
  <form class="form-signin">

Sign up

    Email address
    <input type="email" id="inputEmail" ng-model="user.email" class="form-control" placeholder="Email address" required autofocus>

    Phone
    <input type="text" id="inputPhone" ng-model="user.phone" class="form-control" placeholder="Phone" required>

    Password
    <input type="password" id="inputPassword" class="form-control" placeholder="Password" required>

Already have an account? Sign in here.

    <button ng-click="doRegister()" class="btn btn-lg btn-primary btn-block" type="button">Sign up</button>
  </form>


text:
> Surround the content of a file with another content.

## Getting Started
This plugin requires Grunt `~0.4.1`

If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

```shell
npm install grunt-surround --save-dev
```

One the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

```js
grunt.loadNpmTasks('grunt-surround');
```

## The "surround" task

### Overview
In your project's Gruntfile, add a section named `surround` to the data object passed into `grunt.initConfig()`.

```js
grunt.initConfig({
  surround: {
    options: {
      // Task-specific options go here.
    },
    your_target: {
      // Target-specific file lists and/or options go here.
    },
  },
})
```

### Options

#### options.prepend
Type: `String`
Default value: '' (empty String)

A string value that is prepended to the content.

#### options.append
Type: `String`
Default value: '' (empty String)

A string value that is appended to the content.

#### options.overwrite
Type: `Boolean`
Default value: false

Set this option to true to overwrite the source file instead of the destination file.
Note: If you set this option to true, there is no need to specify a destination file.

#### options.linefeed
Type: `String`
Default value: `grunt.util.linefeed`

The value for the linefeed.

#### options.ignoreRepetition
Type: `Boolean`
Default value: false

Set this option to true to check if your content already starts or ends with the specified 'prepend' or 'append' option.
If a match is found, your content will not be modified to avoid repetitions.

### Usage Examples

```js
grunt.initConfig({
  wraps: {
    options: {
      prepend: ';(function() {',
      append: '})()'
    },
    files: [{
      src: 'src/source.js',
      dest: 'dest/destination.js'
    }]
  }
})
```

## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).

## Release History
* 2013-06-18   v0.1.0   First release


text:
    cd vendor/engines/whats_new_stories
    gem build refinerycms-whats_new_stories.gempspec
    gem install refinerycms-whats_new_stories.gem

    # Sign up for a http://rubygems.org/ account and publish the gem
    gem push refinerycms-whats_new_stories.gem


text:
class CreateDescriptionTypes < ActiveRecord::Migration
  def self.up
    create_table :description_types, :options => 'ENGINE=MyISAM, CHARACTER SET=utf8 COLLATE=utf8_general_ci' do |t|
      t.column :title, :string, :limit => 100, :null => false
    end
    add_index :description_types, :title, :unique => true
    DescriptionType.create :title => 'General'
  end

  def self.down
    drop_table :description_types
  end
end


text:
require "spec_helper"

describe MetaHash do

    before(:each) do
      m = TestObject.new(metadata: h, name: "MetaHash")
      m.save
    end

    after(:each) do
      TestObject.destroy_all
    end

    it "converts the chose field to Metadata" do
      p = TestObject.last
      expect(p.metadata).to be_kind_of(Metadata)
    end

    it "instantiates with an empty hash if the field is nil" do
      p = TestObject.new
      p.metadata = nil
      p = TestObject.last
      expect(p.metadata).to_not be_nil
      expect(p.metadata).to be_kind_of(Metadata)
    end

    it "does not modify the original contents of the chosen field on initialization" do
      p = TestObject.last
      expect(p.metadata.to_hash).to eq Metadata.new(h)
    end

    it "creates an alias for the original field's data" do
      p = TestObject.last
      expect(p.metadata_original).to eq Metadata.new(h)
    end

    it "doesn't error when a the attribute is not included in the retrieval of a record" do
      expect{
        p = TestObject.select("name")
      }.to_not raise_error
    end

    it "converts the field back to a Hash before saving to the database" do
      db = ActiveRecord::Base.connection.select_all("
          SELECT metadata
          FROM test_objects
        ").last
      p = db["metadata"]
      expect(JSON.load(p)).to eq JSON.load(h.to_json)
    end

end


text:
<?php
/**
 * Created by PhpStorm.
 * User: mariusngaboyamahina
 * Date: 4/2/17
 * Time: 10:39 PM
 */
/* @var $upcoming_events backend\models\Event */
use yii\helpers\Html;
use yii\helpers\Url;

?>

<?php $upcoming_events = $this->context->getUpcomingEvents();
if (!empty($upcoming_events)): ?>

<?php echo Yii::t('app', 'Upcoming Events') ?>

        <?php foreach ($upcoming_events as $upcoming_event): ?>

                        <a target="_blank" href="<?php echo $upcoming_event->getEventUrl() ?>">
                            <img class="img-responsive img-alt-thumbnail_tn"
                                 src="<?php echo $upcoming_event->getBanner(); ?>"
                                 alt="<?php echo $upcoming_event->name; ?>">

                            <a target="_blank"
                               href="<?php echo $upcoming_event->getEventUrl() ?>"> <?php echo $upcoming_event->name; ?>

                            <a target="_blank"
                               href="<?php echo $upcoming_event->getEventUrl() ?>"><?php echo $upcoming_event->address; ?>

<?php echo $upcoming_event->getDate(); ?>

        <?php endforeach; ?>

<?php endif; ?>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="Source to the Rust file `C:/bot/slave/nightly-dist-rustc-win-64/build/src/libsyntax\parse\token.rs`.">
    <meta name="keywords" content="rust, rustlang, rust-lang">

    <title>token.rs.html -- source</title>

    <link rel="stylesheet" type="text/css" href="../../../../main.css">

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778

// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

pub use self::BinOpToken::*;
pub use self::Nonterminal::*;
pub use self::DelimToken::*;
pub use self::IdentStyle::*;
pub use self::Lit::*;
pub use self::Token::*;

use ast;
use ext::mtwt;
use ptr::P;
use util::interner::{RcStr, StrInterner};
use util::interner;

use serialize::{Decodable, Decoder, Encodable, Encoder};
use std::fmt;
use std::mem;
use std::ops::Deref;
use std::old_path::BytesContainer;
use std::rc::Rc;

#[allow(non_camel_case_types)]
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
pub enum BinOpToken {
    Plus,
    Minus,
    Star,
    Slash,
    Percent,
    Caret,
    And,
    Or,
    Shl,
    Shr,
}

/// A delimiter token
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
pub enum DelimToken {
    /// A round parenthesis: `(` or `)`
    Paren,
    /// A square bracket: `[` or `]`
    Bracket,
    /// A curly brace: `{` or `}`
    Brace,
}

#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
pub enum IdentStyle {
    /// `::` follows the identifier with no whitespace in-between.
    ModName,
    Plain,
}

#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
pub enum SpecialMacroVar {
    /// `$crate` will be filled in with the name of the crate a macro was
    /// imported from, if any.
    CrateMacroVar,
}

impl SpecialMacroVar {
    pub fn as_str(self) -> &'static str {
        match self {
            SpecialMacroVar::CrateMacroVar => "crate",
        }
    }
}

#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug, Copy)]
pub enum Lit {
    Byte(ast::Name),
    Char(ast::Name),
    Integer(ast::Name),
    Float(ast::Name),
    Str_(ast::Name),
    StrRaw(ast::Name, usize), /* raw str delimited by n hash symbols */
    Binary(ast::Name),
    BinaryRaw(ast::Name, usize), /* raw binary str delimited by n hash symbols */
}

impl Lit {
    pub fn short_name(&self) -> &'static str {
        match *self {
            Byte(_) => "byte",
            Char(_) => "char",
            Integer(_) => "integer",
            Float(_) => "float",
            Str_(_) | StrRaw(..) => "str",
            Binary(_) | BinaryRaw(..) => "binary str"
        }
    }
}

#[allow(non_camel_case_types)]
#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Debug)]
pub enum Token {
    /* Expression-operator symbols. */
    Eq,
    Lt,
    Le,
    EqEq,
    Ne,
    Ge,
    Gt,
    AndAnd,
    OrOr,
    Not,
    Tilde,
    BinOp(BinOpToken),
    BinOpEq(BinOpToken),

    /* Structural symbols */
    At,
    Dot,
    DotDot,
    DotDotDot,
    Comma,
    Semi,
    Colon,
    ModSep,
    RArrow,
    LArrow,
    FatArrow,
    Pound,
    Dollar,
    Question,
    /// An opening delimiter, eg. `{`
    OpenDelim(DelimToken),
    /// A closing delimiter, eg. `}`
    CloseDelim(DelimToken),

    /* Literals */
    Literal(Lit, Option<ast::Name>),

    /* Name components */
    Ident(ast::Ident, IdentStyle),
    Underscore,
    Lifetime(ast::Ident),

    /* For interpolation */
    Interpolated(Nonterminal),
    // Can be expanded into several tokens.
    /// Doc comment
    DocComment(ast::Name),
    // In left-hand-sides of MBE macros:
    /// Parse a nonterminal (name to bind, name of NT, styles of their idents)
    MatchNt(ast::Ident, ast::Ident, IdentStyle, IdentStyle),
    // In right-hand-sides of MBE macros:
    /// A syntactic variable that will be filled in by macro expansion.
    SubstNt(ast::Ident, IdentStyle),
    /// A macro variable with special meaning.
    SpecialVarNt(SpecialMacroVar),

    // Junk. These carry no data because we don't really care about the data
    // they *would* carry, and don't really want to allocate a new ident for
    // them. Instead, users could extract that from the associated span.

    /// Whitespace
    Whitespace,
    /// Comment
    Comment,
    Shebang(ast::Name),

    Eof,
}

impl Token {
    /// Returns `true` if the token can appear at the start of an expression.
    pub fn can_begin_expr(&self) -> bool {
        match *self {
            OpenDelim(_)                => true,
            Ident(_, _)                 => true,
            Underscore                  => true,
            Tilde                       => true,
            Literal(_, _)               => true,
            Not                         => true,
            BinOp(Minus)                => true,
            BinOp(Star)                 => true,
            BinOp(And)                  => true,
            BinOp(Or)                   => true, // in lambda syntax
            OrOr                        => true, // in lambda syntax
            AndAnd                      => true, // double borrow
            DotDot                      => true, // range notation
            ModSep                      => true,
            Interpolated(NtExpr(..))    => true,
            Interpolated(NtIdent(..))   => true,
            Interpolated(NtBlock(..))   => true,
            Interpolated(NtPath(..))    => true,
            _                           => false,
        }
    }

    /// Returns `true` if the token is any literal
    pub fn is_lit(&self) -> bool {
        match *self {
            Literal(_, _) => true,
            _          => false,
        }
    }

    /// Returns `true` if the token is an identifier.
    pub fn is_ident(&self) -> bool {
        match *self {
            Ident(_, _) => true,
            _           => false,
        }
    }

    /// Returns `true` if the token is an interpolated path.
    pub fn is_path(&self) -> bool {
        match *self {
            Interpolated(NtPath(..))    => true,
            _                           => false,
        }
    }

    /// Returns `true` if the token is a path that is not followed by a `::`
    /// token.
    #[allow(non_upper_case_globals)]
    pub fn is_plain_ident(&self) -> bool {
        match *self {
            Ident(_, Plain) => true,
            _               => false,
        }
    }

    /// Returns `true` if the token is a lifetime.
    pub fn is_lifetime(&self) -> bool {
        match *self {
            Lifetime(..) => true,
            _            => false,
        }
    }

    /// Returns `true` if the token is either the `mut` or `const` keyword.
    pub fn is_mutability(&self) -> bool {
        self.is_keyword(keywords::Mut) ||
        self.is_keyword(keywords::Const)
    }

    /// Maps a token to its corresponding binary operator.
    pub fn to_binop(&self) -> Option<ast::BinOp_> {
        match *self {
            BinOp(Star)     => Some(ast::BiMul),
            BinOp(Slash)    => Some(ast::BiDiv),
            BinOp(Percent)  => Some(ast::BiRem),
            BinOp(Plus)     => Some(ast::BiAdd),
            BinOp(Minus)    => Some(ast::BiSub),
            BinOp(Shl)      => Some(ast::BiShl),
            BinOp(Shr)      => Some(ast::BiShr),
            BinOp(And)      => Some(ast::BiBitAnd),
            BinOp(Caret)    => Some(ast::BiBitXor),
            BinOp(Or)       => Some(ast::BiBitOr),
            Lt              => Some(ast::BiLt),
            Le              => Some(ast::BiLe),
            Ge              => Some(ast::BiGe),
            Gt              => Some(ast::BiGt),
            EqEq            => Some(ast::BiEq),
            Ne              => Some(ast::BiNe),
            AndAnd          => Some(ast::BiAnd),
            OrOr            => Some(ast::BiOr),
            _               => None,
        }
    }

    /// Returns `true` if the token is a given keyword, `kw`.
    #[allow(non_upper_case_globals)]
    pub fn is_keyword(&self, kw: keywords::Keyword) -> bool {
        match *self {
            Ident(sid, Plain) => kw.to_name() == sid.name,
            _                      => false,
        }
    }

    pub fn is_keyword_allow_following_colon(&self, kw: keywords::Keyword) -> bool {
        match *self {
            Ident(sid, _) => { kw.to_name() == sid.name }
            _ => { false }
        }
    }

    /// Returns `true` if the token is either a special identifier, or a strict
    /// or reserved keyword.
    #[allow(non_upper_case_globals)]
    pub fn is_any_keyword(&self) -> bool {
        match *self {
            Ident(sid, Plain) => {
                let n = sid.name;

                   n == SELF_KEYWORD_NAME
                || n == STATIC_KEYWORD_NAME
                || n == SUPER_KEYWORD_NAME
                || n == SELF_TYPE_KEYWORD_NAME
                || STRICT_KEYWORD_START <= n
                && n <= RESERVED_KEYWORD_FINAL
            },
            _ => false
        }
    }

    /// Returns `true` if the token may not appear as an identifier.
    #[allow(non_upper_case_globals)]
    pub fn is_strict_keyword(&self) -> bool {
        match *self {
            Ident(sid, Plain) => {
                let n = sid.name;

                   n == SELF_KEYWORD_NAME
                || n == STATIC_KEYWORD_NAME
                || n == SUPER_KEYWORD_NAME
                || n == SELF_TYPE_KEYWORD_NAME
                || STRICT_KEYWORD_START <= n
                && n <= STRICT_KEYWORD_FINAL
            },
            Ident(sid, ModName) => {
                let n = sid.name;

                   n != SELF_KEYWORD_NAME
                && n != SUPER_KEYWORD_NAME
                && STRICT_KEYWORD_START <= n
                && n <= STRICT_KEYWORD_FINAL
            }
            _ => false,
        }
    }

    /// Returns `true` if the token is a keyword that has been reserved for
    /// possible future use.
    #[allow(non_upper_case_globals)]
    pub fn is_reserved_keyword(&self) -> bool {
        match *self {
            Ident(sid, Plain) => {
                let n = sid.name;

                   RESERVED_KEYWORD_START <= n
                && n <= RESERVED_KEYWORD_FINAL
            },
            _ => false,
        }
    }

    /// Hygienic identifier equality comparison.
    ///
    /// See `styntax::ext::mtwt`.
    pub fn mtwt_eq(&self, other : &Token) -> bool {
        match (self, other) {
            (&Ident(id1,_), &Ident(id2,_)) | (&Lifetime(id1), &Lifetime(id2)) =>
                mtwt::resolve(id1) == mtwt::resolve(id2),
            _ => *self == *other
        }
    }
}

#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash)]
/// For interpolation during macro expansion.
pub enum Nonterminal {
    NtItem(P<ast::Item>),
    NtBlock(P<ast::Block>),
    NtStmt(P<ast::Stmt>),
    NtPat(P<ast::Pat>),
    NtExpr(P<ast::Expr>),
    NtTy(P<ast::Ty>),
    NtIdent(Box<ast::Ident>, IdentStyle),
    /// Stuff inside brackets for attributes
    NtMeta(P<ast::MetaItem>),
    NtPath(Box<ast::Path>),
    NtTT(P<ast::TokenTree>), // needs P'ed to break a circularity
}

impl fmt::Debug for Nonterminal {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            NtItem(..) => f.pad("NtItem(..)"),
            NtBlock(..) => f.pad("NtBlock(..)"),
            NtStmt(..) => f.pad("NtStmt(..)"),
            NtPat(..) => f.pad("NtPat(..)"),
            NtExpr(..) => f.pad("NtExpr(..)"),
            NtTy(..) => f.pad("NtTy(..)"),
            NtIdent(..) => f.pad("NtIdent(..)"),
            NtMeta(..) => f.pad("NtMeta(..)"),
            NtPath(..) => f.pad("NtPath(..)"),
            NtTT(..) => f.pad("NtTT(..)"),
        }
    }
}

// Get the first "argument"
macro_rules! first {
    ( $first:expr, $( $remainder:expr, )* ) => ( $first )
}

// Get the last "argument" (has to be done recursively to avoid phoney local ambiguity error)
macro_rules! last {
    ( $first:expr, $( $remainder:expr, )+ ) => ( last!( $( $remainder, )+ ) );
    ( $first:expr, ) => ( $first )
}

// In this macro, there is the requirement that the name (the number) must be monotonically
// increasing by one in the special identifiers, starting at 0; the same holds for the keywords,
// except starting from the next number instead of zero, and with the additional exception that
// special identifiers are *also* allowed (they are deduplicated in the important place, the
// interner), an exception which is demonstrated by "static" and "self".
macro_rules! declare_special_idents_and_keywords {(
    // So now, in these rules, why is each definition parenthesised?
    // Answer: otherwise we get a spurious local ambiguity bug on the "}"
    pub mod special_idents {
        $( ($si_name:expr, $si_static:ident, $si_str:expr); )*
    }

    pub mod keywords {
        'strict:
        $( ($sk_name:expr, $sk_variant:ident, $sk_str:expr); )*
        'reserved:
        $( ($rk_name:expr, $rk_variant:ident, $rk_str:expr); )*
    }
) => {
    const STRICT_KEYWORD_START: ast::Name = first!($( ast::Name($sk_name), )*);
    const STRICT_KEYWORD_FINAL: ast::Name = last!($( ast::Name($sk_name), )*);
    const RESERVED_KEYWORD_START: ast::Name = first!($( ast::Name($rk_name), )*);
    const RESERVED_KEYWORD_FINAL: ast::Name = last!($( ast::Name($rk_name), )*);

    pub mod special_idents {
        use ast;
        $(
            #[allow(non_upper_case_globals)]
            pub const $si_static: ast::Ident = ast::Ident {
                name: ast::Name($si_name),
                ctxt: 0,
            };
         )*
    }

    pub mod special_names {
        use ast;
        $(
            #[allow(non_upper_case_globals)]
            pub const $si_static: ast::Name =  ast::Name($si_name);
        )*
    }

    /// All the valid words that have meaning in the Rust language.
    ///
    /// Rust keywords are either 'strict' or 'reserved'.  Strict keywords may not
    /// appear as identifiers at all. Reserved keywords are not used anywhere in
    /// the language and may not appear as identifiers.
    pub mod keywords {
        pub use self::Keyword::*;
        use ast;

        #[derive(Copy, Clone, PartialEq, Eq)]
        pub enum Keyword {
            $( $sk_variant, )*
            $( $rk_variant, )*
        }

        impl Keyword {
            pub fn to_name(&self) -> ast::Name {
                match *self {
                    $( $sk_variant => ast::Name($sk_name), )*
                    $( $rk_variant => ast::Name($rk_name), )*
                }
            }
        }
    }

    fn mk_fresh_ident_interner() -> IdentInterner {
        // The indices here must correspond to the numbers in
        // special_idents, in Keyword to_name(), and in static
        // constants below.
        let mut init_vec = Vec::new();
        $(init_vec.push($si_str);)*
        $(init_vec.push($sk_str);)*
        $(init_vec.push($rk_str);)*
        interner::StrInterner::prefill(&init_vec[..])
    }
}}

// If the special idents get renumbered, remember to modify these two as appropriate
pub const SELF_KEYWORD_NAME: ast::Name = ast::Name(SELF_KEYWORD_NAME_NUM);
const STATIC_KEYWORD_NAME: ast::Name = ast::Name(STATIC_KEYWORD_NAME_NUM);
const SUPER_KEYWORD_NAME: ast::Name = ast::Name(SUPER_KEYWORD_NAME_NUM);
const SELF_TYPE_KEYWORD_NAME: ast::Name = ast::Name(SELF_TYPE_KEYWORD_NAME_NUM);

pub const SELF_KEYWORD_NAME_NUM: u32 = 1;
const STATIC_KEYWORD_NAME_NUM: u32 = 2;
const SUPER_KEYWORD_NAME_NUM: u32 = 3;
const SELF_TYPE_KEYWORD_NAME_NUM: u32 = 10;

// NB: leaving holes in the ident table is bad! a different ident will get
// interned with the id from the hole, but it will be between the min and max
// of the reserved words, and thus tagged as "reserved".

declare_special_idents_and_keywords! {
    pub mod special_idents {
        // These ones are statics
        (0,                          invalid,                "");
        (super::SELF_KEYWORD_NAME_NUM,   self_,              "self");
        (super::STATIC_KEYWORD_NAME_NUM, statik,             "static");
        (super::SUPER_KEYWORD_NAME_NUM, super_,              "super");
        (4,                          static_lifetime,        "'static");

        // for matcher NTs
        (5,                          tt,                     "tt");
        (6,                          matchers,               "matchers");

        // outside of libsyntax
        (7,                          clownshoe_abi,          "__rust_abi");
        (8,                          opaque,                 "<opaque>");
        (9,                          unnamed_field,          "<unnamed_field>");
        (super::SELF_TYPE_KEYWORD_NAME_NUM, type_self,       "Self");
        (11,                         prelude_import,         "prelude_import");
    }

    pub mod keywords {
        // These ones are variants of the Keyword enum

        'strict:
        (12,                         As,         "as");
        (13,                         Break,      "break");
        (14,                         Crate,      "crate");
        (15,                         Else,       "else");
        (16,                         Enum,       "enum");
        (17,                         Extern,     "extern");
        (18,                         False,      "false");
        (19,                         Fn,         "fn");
        (20,                         For,        "for");
        (21,                         If,         "if");
        (22,                         Impl,       "impl");
        (23,                         In,         "in");
        (24,                         Let,        "let");
        (25,                         Loop,       "loop");
        (26,                         Match,      "match");
        (27,                         Mod,        "mod");
        (28,                         Move,       "move");
        (29,                         Mut,        "mut");
        (30,                         Pub,        "pub");
        (31,                         Ref,        "ref");
        (32,                         Return,     "return");
        // Static and Self are also special idents (prefill de-dupes)
        (super::STATIC_KEYWORD_NAME_NUM, Static, "static");
        (super::SELF_KEYWORD_NAME_NUM, SelfValue, "self");
        (super::SELF_TYPE_KEYWORD_NAME_NUM, SelfType, "Self");
        (33,                         Struct,     "struct");
        (super::SUPER_KEYWORD_NAME_NUM, Super,   "super");
        (34,                         True,       "true");
        (35,                         Trait,      "trait");
        (36,                         Type,       "type");
        (37,                         Unsafe,     "unsafe");
        (38,                         Use,        "use");
        (39,                         Virtual,    "virtual");
        (40,                         While,      "while");
        (41,                         Continue,   "continue");
        (42,                         Proc,       "proc");
        (43,                         Box,        "box");
        (44,                         Const,      "const");
        (45,                         Where,      "where");
        'reserved:
        (46,                         Alignof,    "alignof");
        (47,                         Become,     "become");
        (48,                         Offsetof,   "offsetof");
        (49,                         Priv,       "priv");
        (50,                         Pure,       "pure");
        (51,                         Sizeof,     "sizeof");
        (52,                         Typeof,     "typeof");
        (53,                         Unsized,    "unsized");
        (54,                         Yield,      "yield");
        (55,                         Do,         "do");
        (56,                         Abstract,   "abstract");
        (57,                         Final,      "final");
        (58,                         Override,   "override");
        (59,                         Macro,      "macro");
    }
}

// looks like we can get rid of this completely...
pub type IdentInterner = StrInterner;

// if an interner exists in TLS, return it. Otherwise, prepare a
// fresh one.
// FIXME(eddyb) #8726 This should probably use a task-local reference.
pub fn get_ident_interner() -> Rc<IdentInterner> {
    thread_local!(static KEY: Rc<::parse::token::IdentInterner> = {
        Rc::new(mk_fresh_ident_interner())
    });
    KEY.with(|k| k.clone())
}

/// Reset the ident interner to its initial state.
pub fn reset_ident_interner() {
    let interner = get_ident_interner();
    interner.reset(mk_fresh_ident_interner());
}

/// Represents a string stored in the task-local interner. Because the
/// interner lives for the life of the task, this can be safely treated as an
/// immortal string, as long as it never crosses between tasks.
///
/// FIXME(pcwalton): You must be careful about what you do in the destructors
/// of objects stored in TLS, because they may run after the interner is
/// destroyed. In particular, they must not access string contents. This can
/// be fixed in the future by just leaking all strings until task death
/// somehow.
#[derive(Clone, PartialEq, Hash, PartialOrd, Eq, Ord)]
pub struct InternedString {
    string: RcStr,
}

impl InternedString {
    #[inline]
    pub fn new(string: &'static str) -> InternedString {
        InternedString {
            string: RcStr::new(string),
        }
    }

    #[inline]
    fn new_from_rc_str(string: RcStr) -> InternedString {
        InternedString {
            string: string,
        }
    }
}

impl Deref for InternedString {
    type Target = str;

    fn deref(&self) -> &str { &*self.string }
}

impl BytesContainer for InternedString {
    fn container_as_bytes<'a>(&'a self) -> &'a [u8] {
        // FIXME #12938: This is a workaround for the incorrect signature
        // of `BytesContainer`, which is itself a workaround for the lack of
        // DST.
        unsafe {
            let this = &self[..];
            mem::transmute::<&[u8],&[u8]>(this.container_as_bytes())
        }
    }
}

impl fmt::Debug for InternedString {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&self.string, f)
    }
}

impl fmt::Display for InternedString {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.string, f)
    }
}

impl<'a> PartialEq<&'a str> for InternedString {
    #[inline(always)]
    fn eq(&self, other: & &'a str) -> bool {
        PartialEq::eq(&self.string[..], *other)
    }
    #[inline(always)]
    fn ne(&self, other: & &'a str) -> bool {
        PartialEq::ne(&self.string[..], *other)
    }
}

impl<'a> PartialEq<InternedString > for &'a str {
    #[inline(always)]
    fn eq(&self, other: &InternedString) -> bool {
        PartialEq::eq(*self, &other.string[..])
    }
    #[inline(always)]
    fn ne(&self, other: &InternedString) -> bool {
        PartialEq::ne(*self, &other.string[..])
    }
}

impl Decodable for InternedString {
    fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> {
        Ok(get_name(get_ident_interner().intern(&try!(d.read_str())[..])))
    }
}

impl Encodable for InternedString {
    fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
        s.emit_str(&self.string)
    }
}

/// Returns the string contents of a name, using the task-local interner.
#[inline]
pub fn get_name(name: ast::Name) -> InternedString {
    let interner = get_ident_interner();
    InternedString::new_from_rc_str(interner.get(name))
}

/// Returns the string contents of an identifier, using the task-local
/// interner.
#[inline]
pub fn get_ident(ident: ast::Ident) -> InternedString {
    get_name(ident.name)
}

/// Interns and returns the string contents of an identifier, using the
/// task-local interner.
#[inline]
pub fn intern_and_get_ident(s: &str) -> InternedString {
    get_name(intern(s))
}

/// Maps a string to its interned representation.
#[inline]
pub fn intern(s: &str) -> ast::Name {
    get_ident_interner().intern(s)
}

/// gensym's a new usize, using the current interner.
#[inline]
pub fn gensym(s: &str) -> ast::Name {
    get_ident_interner().gensym(s)
}

/// Maps a string to an identifier with an empty syntax context.
#[inline]
pub fn str_to_ident(s: &str) -> ast::Ident {
    ast::Ident::new(intern(s))
}

/// Maps a string to a gensym'ed identifier.
#[inline]
pub fn gensym_ident(s: &str) -> ast::Ident {
    ast::Ident::new(gensym(s))
}

// create a fresh name that maps to the same string as the old one.
// note that this guarantees that str_ptr_eq(ident_to_string(src),interner_get(fresh_name(src)));
// that is, that the new name and the old one are connected to ptr_eq strings.
pub fn fresh_name(src: &ast::Ident) -> ast::Name {
    let interner = get_ident_interner();
    interner.gensym_copy(src.name)
    // following: debug version. Could work in final except that it's incompatible with
    // good error messages and uses of struct names in ambiguous could-be-binding
    // locations. Also definitely destroys the guarantee given above about ptr_eq.
    /*let num = rand::thread_rng().gen_uint_range(0,0xffff);
    gensym(format!("{}_{}",ident_to_string(src),num))*/
}

// create a fresh mark.
pub fn fresh_mark() -> ast::Mrk {
    gensym("mark").usize() as u32
}

#[cfg(test)]
mod test {
    use super::*;
    use ast;
    use ext::mtwt;

    fn mark_ident(id : ast::Ident, m : ast::Mrk) -> ast::Ident {
        ast::Ident { name: id.name, ctxt:mtwt::apply_mark(m, id.ctxt) }
    }

    #[test] fn mtwt_token_eq_test() {
        assert!(Gt.mtwt_eq(&Gt));
        let a = str_to_ident("bac");
        let a1 = mark_ident(a,92);
        assert!(Ident(a, ModName).mtwt_eq(&Ident(a1, Plain)));
    }
}

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
namespace arrow {
namespace internal {

static void sleep_for(double seconds) {
  std::this_thread::sleep_for(
      std::chrono::nanoseconds(static_cast<int64_t>(seconds * 1e9)));
}

// Generate random sleep durations
static std::vector<double> RandomSleepDurations(int nsleeps, double min_seconds,
                                                double max_seconds) {
  std::vector<double> sleeps;
  std::default_random_engine engine;
  std::uniform_real_distribution<> sleep_dist(min_seconds, max_seconds);
  for (int i = 0; i < nsleeps; ++i) {
    sleeps.push_back(sleep_dist(engine));
  }
  return sleeps;
}

// Check TaskGroup behaviour with a bunch of all-successful tasks
void TestTaskGroupSuccess(std::shared_ptr<TaskGroup> task_group) {
  const int NTASKS = 10;
  auto sleeps = RandomSleepDurations(NTASKS, 1e-3, 4e-3);

  // Add NTASKS sleeps
  std::atomic<int> count(0);
  for (int i = 0; i < NTASKS; ++i) {
    task_group->Append([&, i]() {
      sleep_for(sleeps[i]);
      count += i;
      return Status::OK();
    });
  }
  ASSERT_TRUE(task_group->ok());

  ASSERT_OK(task_group->Finish());
  ASSERT_TRUE(task_group->ok());
  ASSERT_EQ(count.load(), NTASKS * (NTASKS - 1) / 2);
  // Finish() is idempotent
  ASSERT_OK(task_group->Finish());
}

// Check TaskGroup behaviour with some successful and some failing tasks
void TestTaskGroupErrors(std::shared_ptr<TaskGroup> task_group) {
  const int NSUCCESSES = 2;
  const int NERRORS = 20;

  std::atomic<int> count(0);

  for (int i = 0; i < NSUCCESSES; ++i) {
    task_group->Append([&]() {
      count++;
      return Status::OK();
    });
  }
  ASSERT_TRUE(task_group->ok());
  for (int i = 0; i < NERRORS; ++i) {
    task_group->Append([&]() {
      sleep_for(1e-2);
      count++;
      return Status::Invalid("some message");
    });
  }

  // Task error is propagated
  ASSERT_RAISES(Invalid, task_group->Finish());
  ASSERT_FALSE(task_group->ok());
  if (task_group->parallelism() == 1) {
    // Serial: exactly two successes and an error
    ASSERT_EQ(count.load(), 3);
  } else {
    // Parallel: at least two successes and an error
    ASSERT_GE(count.load(), 3);
    ASSERT_LE(count.load(), 2 * task_group->parallelism());
  }
  // Finish() is idempotent
  ASSERT_RAISES(Invalid, task_group->Finish());
}

// Check TaskGroup behaviour with a bunch of all-successful tasks and task groups
void TestTaskSubGroupsSuccess(std::shared_ptr<TaskGroup> task_group) {
  const int NTASKS = 50;
  const int NGROUPS = 7;

  auto sleeps = RandomSleepDurations(NTASKS, 1e-4, 1e-3);
  std::vector<std::shared_ptr<TaskGroup>> groups = {task_group};

  // Create some subgroups
  for (int i = 0; i < NGROUPS - 1; ++i) {
    groups.push_back(task_group->MakeSubGroup());
  }

  // Add NTASKS sleeps amonst all groups
  std::atomic<int> count(0);
  for (int i = 0; i < NTASKS; ++i) {
    groups[i % NGROUPS]->Append([&, i]() {
      sleep_for(sleeps[i]);
      count += i;
      return Status::OK();
    });
  }
  ASSERT_TRUE(task_group->ok());

  // Finish all subgroups first, then main group
  for (int i = NGROUPS - 1; i >= 0; --i) {
    ASSERT_OK(groups[i]->Finish());
  }
  ASSERT_TRUE(task_group->ok());
  ASSERT_EQ(count.load(), NTASKS * (NTASKS - 1) / 2);
  // Finish() is idempotent
  ASSERT_OK(task_group->Finish());
}

// Check TaskGroup behaviour with both successful and failing tasks and task groups
void TestTaskSubGroupsErrors(std::shared_ptr<TaskGroup> task_group) {
  const int NTASKS = 50;
  const int NGROUPS = 7;
  const int FAIL_EVERY = 17;
  std::vector<std::shared_ptr<TaskGroup>> groups = {task_group};

  // Create some subgroups
  for (int i = 0; i < NGROUPS - 1; ++i) {
    groups.push_back(task_group->MakeSubGroup());
  }

  // Add NTASKS sleeps amonst all groups
  for (int i = 0; i < NTASKS; ++i) {
    groups[i % NGROUPS]->Append([&, i]() {
      sleep_for(1e-3);
      // As NGROUPS > NTASKS / FAIL_EVERY, some subgroups are successful
      if (i % FAIL_EVERY == 0) {
        return Status::Invalid("some message");
      } else {
        return Status::OK();
      }
    });
  }

  // Finish all subgroups first, then main group
  int nsuccessful = 0;
  for (int i = NGROUPS - 1; i > 0; --i) {
    Status st = groups[i]->Finish();
    if (st.ok()) {
      ++nsuccessful;
    } else {
      ASSERT_RAISES(Invalid, st);
    }
  }
  ASSERT_RAISES(Invalid, task_group->Finish());
  ASSERT_FALSE(task_group->ok());
  // Finish() is idempotent
  ASSERT_RAISES(Invalid, task_group->Finish());
}

// Check TaskGroup behaviour with tasks spawning other tasks
void TestTasksSpawnTasks(std::shared_ptr<TaskGroup> task_group) {
  const int N = 6;

  std::atomic<int> count(0);
  // Make a task that recursively spawns itself
  std::function<std::function<Status()>(int)> make_task = [&](int i) {
    return [&, i]() {
      count++;
      if (i > 0) {
        // Exercise parallelism by spawning two tasks at once and then sleeping
        task_group->Append(make_task(i - 1));
        task_group->Append(make_task(i - 1));
        sleep_for(1e-3);
      }
      return Status::OK();
    };
  };

  task_group->Append(make_task(N));

  ASSERT_OK(task_group->Finish());
  ASSERT_TRUE(task_group->ok());
  ASSERT_EQ(count.load(), (1 << (N + 1)) - 1);
}

// A task that keeps recursing until a barrier is set.
// Using a lambda for this doesn't play well with Thread Sanitizer.
struct BarrierTask {
  std::atomic<bool>* barrier_;
  std::weak_ptr<TaskGroup> weak_group_ptr_;
  Status final_status_;

  Status operator()() {
    if (!barrier_->load()) {
      sleep_for(1e-5);
      // Note the TaskGroup should be kept alive by the fact this task
      // is still running...
      weak_group_ptr_.lock()->Append(*this);
    }
    return final_status_;
  }
};

// Try to replicate subtle lifetime issues when destroying a TaskGroup
// where all tasks may not have finished running.
void StressTaskGroupLifetime(std::function<std::shared_ptr<TaskGroup>()> factory) {
  const int NTASKS = 100;
  auto task_group = factory();
  auto weak_group_ptr = std::weak_ptr<TaskGroup>(task_group);

  std::atomic<bool> barrier(false);

  BarrierTask task{&barrier, weak_group_ptr, Status::OK()};

  for (int i = 0; i < NTASKS; ++i) {
    task_group->Append(task);
  }

  // Lose strong reference
  barrier.store(true);
  task_group.reset();

  // Wait for finish
  while (!weak_group_ptr.expired()) {
    sleep_for(1e-5);
  }
}

// Same, but with also a failing task
void StressFailingTaskGroupLifetime(std::function<std::shared_ptr<TaskGroup>()> factory) {
  const int NTASKS = 100;
  auto task_group = factory();
  auto weak_group_ptr = std::weak_ptr<TaskGroup>(task_group);

  std::atomic<bool> barrier(false);

  BarrierTask task{&barrier, weak_group_ptr, Status::OK()};
  BarrierTask failing_task{&barrier, weak_group_ptr, Status::Invalid("XXX")};

  for (int i = 0; i < NTASKS; ++i) {
    task_group->Append(task);
  }
  task_group->Append(failing_task);

  // Lose strong reference
  barrier.store(true);
  task_group.reset();

  // Wait for finish
  while (!weak_group_ptr.expired()) {
    sleep_for(1e-5);
  }
}

TEST(SerialTaskGroup, Success) { TestTaskGroupSuccess(TaskGroup::MakeSerial()); }

TEST(SerialTaskGroup, Errors) { TestTaskGroupErrors(TaskGroup::MakeSerial()); }

TEST(SerialTaskGroup, TasksSpawnTasks) { TestTasksSpawnTasks(TaskGroup::MakeSerial()); }

TEST(SerialTaskGroup, SubGroupsSuccess) {
  TestTaskSubGroupsSuccess(TaskGroup::MakeSerial());
}

TEST(SerialTaskGroup, SubGroupsErrors) {
  TestTaskSubGroupsErrors(TaskGroup::MakeSerial());
}

TEST(ThreadedTaskGroup, Success) {
  auto task_group = TaskGroup::MakeThreaded(GetCpuThreadPool());
  TestTaskGroupSuccess(task_group);
}

TEST(ThreadedTaskGroup, Errors) {
  // Limit parallelism to ensure some tasks don't get started
  // after the first failing ones
  std::shared_ptr<ThreadPool> thread_pool;
  ASSERT_OK(ThreadPool::Make(4, &thread_pool));

  TestTaskGroupErrors(TaskGroup::MakeThreaded(thread_pool.get()));
}

TEST(ThreadedTaskGroup, TasksSpawnTasks) {
  auto task_group = TaskGroup::MakeThreaded(GetCpuThreadPool());
  TestTasksSpawnTasks(task_group);
}

TEST(ThreadedTaskGroup, SubGroupsSuccess) {
  std::shared_ptr<ThreadPool> thread_pool;
  ASSERT_OK(ThreadPool::Make(4, &thread_pool));

  TestTaskSubGroupsSuccess(TaskGroup::MakeThreaded(thread_pool.get()));
}

TEST(ThreadedTaskGroup, SubGroupsErrors) {
  std::shared_ptr<ThreadPool> thread_pool;
  ASSERT_OK(ThreadPool::Make(4, &thread_pool));

  TestTaskSubGroupsErrors(TaskGroup::MakeThreaded(thread_pool.get()));
}

TEST(ThreadedTaskGroup, StressTaskGroupLifetime) {
  std::shared_ptr<ThreadPool> thread_pool;
  ASSERT_OK(ThreadPool::Make(16, &thread_pool));

  StressTaskGroupLifetime([&] { return TaskGroup::MakeThreaded(thread_pool.get()); });
}

TEST(ThreadedTaskGroup, StressFailingTaskGroupLifetime) {
  std::shared_ptr<ThreadPool> thread_pool;
  ASSERT_OK(ThreadPool::Make(16, &thread_pool));

  StressFailingTaskGroupLifetime(
      [&] { return TaskGroup::MakeThreaded(thread_pool.get()); });
}

}  // namespace internal
}  // namespace arrow


text:
package com.hp.autonomy.aci.content.identifier.stateid;

/**
 * An abstract base-class that partially implements the {@link StateRange} interface using sensible defaults.
 */
public abstract class AbstractStateRange implements StateRange {
    @Override
    public boolean equals(final Object object) {
        return object == this || object instanceof StateRange && toString().equals(object.toString());
    }

    @Override
    public int hashCode() {
        return toString().hashCode();
    }

    @Override
    public abstract String toString();

    /**
     * Simple implementation that tests for emptiness using {@code size() == 0}. In most cases this should be
     * overridden with a better implementation.
     *
     * @return {@code true} if and only if size is 0.
     */
    @Override
    public boolean isEmpty() {
        return size() == 0;
    }
}


text:
package org.kuali.kfs.module.endow.dataaccess;

import java.sql.Date;
import java.util.List;

import org.kuali.kfs.module.endow.businessobject.Tickler;

public interface TicklerDao {

    /**
     * Gets Tickler whose next income pay date is equal to the current date and whose frequency code is valid
     *
     * @param currentDate the current date
     * @return List<Tickler>
     */
    public List<Tickler> getTicklerWithNextPayDateEqualToCurrentDate(Date currentDate);
}


text:
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved.                             */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

package org.usfirst.frc0;

import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import org.usfirst.frc0.commands.CommandBase;
import org.usfirst.frc0.commands.ExampleCommand;
import edu.wpi.first.wpilibj.Timer;

/**
 * The VM is configured to automatically run this class, and to call the
 * functions corresponding to each mode, as described in the IterativeRobot
 * documentation. If you change the name of this class or the package after
 * creating this project, you must also update the manifest file in the resource
 * directory.
 */
public class CommandBasedRobot extends IterativeRobot {

    Command autonomousCommand;
    Timer time;

    /**
     * This function is run when the robot is first started up and should be
     * used for any initialization code.
     */
    public void robotInit() {
        // instantiate the command used for the autonomous period
        autonomousCommand = new ExampleCommand();

        // Initialize all subsystems

        time = new Timer();
        time.start();
        CommandBase.init();

    }

    public void autonomousInit() {
        // schedule the autonomous command (example)
        autonomousCommand.start();
    }

    /**
     * This function is called periodically during autonomous
     */
    public void autonomousPeriodic() {
        Scheduler.getInstance().run();
    }

    public void teleopInit() {
		// This makes sure that the autonomous stops running when
		// teleop starts running. If you want the autonomous to
		// continue until interrupted by another command, remove
		// this line or comment it out.
		autonomousCommand.cancel();

		Timer autonomousTime = new Timer();
		autonomousTime.start();
    }

    /**
     * This function is called periodically during operator control
     */
    public void teleopPeriodic() {
        Scheduler.getInstance().run();
    }
}


text:
function menu_handle=wseismic_scrollbar_menu(figure_handle,options_menu_handle,seismic,plotdir)
% Function creates a menu button on the figure with handle "figure_handle" (or
% the current figure) that allows one to add scroll bars to a wiggle seismic plot
%
% Written by: E. Rietsch, August 22, 2005
% Last updated: November 5, 2005: Save axis limits before user querry
%
%            menu_handle=wseismic_scrollbar_menu(figure_handle,seismic,plotdir)
% INPUT
% figure_handle  handle of the figure to which to attach the menu button
% seismic    seismic dataset to be displayed; needed to provide limits for the scrollbar boxes
% plotdir    plot direction
% OUTPUT
% menu_handle  handle of the menu button created by this function

ntr=size(seismic.traces,2);
tmax=seismic.last-seismic.first;
tmin=min(3*seismic.step,tmax);
if tmin > tmax
   tmin=tmax;
end

%	Create menu button
menu_handle=uimenu(options_menu_handle,'Label','Add scrollbars','ForegroundColor','b');

set(menu_handle,'Callback',{@seismic_scrollbar,gca,menu_handle,ntr,tmin,tmax,plotdir});

if nargout == 0
   clear menu_handle
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function seismic_scrollbar(hObject,evdata,axis_handle,menu_handle,ntr,tmin,tmax,plotdir) %#ok

label=get(menu_handle,'Label');

if strcmp(label,'Add scrollbars')
   set(menu_handle,'Label','Remove scrollbars');
else
   reset_scroll_button(axis_handle,menu_handle)
   return
end

zoom out

%       Prompt user for time and trace range
prompt={'Enter the number of traces to display:','Enter the time range to display:'};
name='Scroll parameters';
numlines=1;

defaultanswer=mat2cellstrings([min(50,ntr),min(500,tmax)]);

ier1=true;
ier2=true;

%	Save present axis limits
v=axis;
setappdata(menu_handle,'axislimits',v)

while any(ier1)  ||  any(ier2)
    answer=inputdlg(prompt,name,numlines,defaultanswer);

    if isempty(answer)
       reset_scroll_button(axis_handle,menu_handle)
       return
    end

    [ntraces,ier1]=check_numeric(answer{1},'Number of traces',{'minmax',[1,1]}, ...
          {'bounds',1,ntr});
%          keyboard
    [timerange,ier2]=check_numeric(answer{2},'Time range',{'minmax',[1,1]}, ...
          {'bounds',tmin,tmax});
end

%       This reduces flickering when the axis is updated
set(gcf,'doublebuffer','on');

%       Set appropriate axis limits and settings
% set(axis_handle,'xlim',[v(1),v(1)+ntraces],'ylim',[v(3),v(3)+timerange]);

%       Generate constants for use in uicontrol initialization
pos=get(axis_handle,'position');

%xmin=round(v(1));
%xmax=round(v(2));
xmin=v(1);
xmax=v(2);

ymin=round(v(3));
ymax=round(v(4));

if ntr > 1
   xtraces=ntraces*(xmax-xmin)/(ntr-1);
else
   xtraces=ntraces;
end

if ntraces < ntr
   ntraces=ntraces+1;
%       Create a slider below the x-axis
   xsliderpos=[pos(1), pos(2)-0.030, pos(3), 0.029];
   sstep1=max(1/(ntr-ntraces+1),0.01);
   if strcmp(plotdir,'l2r')
       hxslider=uicontrol('style','slider',...
          'units','normalized','Position',xsliderpos,...
          'min',xmin,'max',xmax-xtraces,'value',xmin, ...
          'SliderStep',[sstep1,min(1,10*sstep1)]);
   else
       hxslider=uicontrol('style','slider',...
          'units','normalized','Position',xsliderpos,...
          'min',xmin,'max',xmax-xtraces,'value',xmax-xtraces, ...
          'SliderStep',[sstep1,min(1,10*sstep1)]);
   end
   set(hxslider,'Callback',{@scrollx,axis_handle,xtraces,xmin,xmax,plotdir})
   set(gca,'XLim',[xmin,xmin+xtraces])
   no_xscrollbar=false;
else
   hxslider=1.1;
   no_xscrollbar=true;
end

if timerange < tmax
   ysliderpos=[pos(1)+pos(3)+0.003, pos(2),      0.018,   pos(4)];
   sstep2=min(1,timerange/(ymax-ymin));
   hyslider=uicontrol('style','slider',...
       'units','normalized','Position',ysliderpos,...
       'min',ymin,'max',ymax-timerange,'value',ymax-timerange, ...
       'SliderStep',[max(sstep2/10,8/(ymax-ymin)),sstep2]);
   set(hyslider,'Callback',{@scrolly,axis_handle,timerange,ymin,ymax})

   set(gca,'YLim',[ymin, ymin+timerange])
   no_yscrollbar=false;
else
   hyslider=1.1;
   no_yscrollbar=true;
end
setappdata(menu_handle,'sliders',[hxslider,hyslider])

if no_xscrollbar && no_yscrollbar
   set(menu_handle,'Label','Add scrollbars');
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function scrollx(hObject,evdata,axis_handle,ntraces,xmin,xmax,plotdir) %#ok

if strcmp(plotdir,'l2r')
   xlimits=get(gcbo,'value')+[0,ntraces];
else
   xlimits=xmax-get(gcbo,'value')+[-ntraces,0]+xmin;
end

set(axis_handle,'XLim',xlimits)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function scrolly(hObject,evdata,axis_handle,timerange,ymin,ymax) %#ok
ylimits=ymax-get(gcbo,'value')+[-timerange,0]+ymin;
%ylimits=ylimits;

set(axis_handle,'YLim',ylimits)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function reset_scroll_button(axis_handle,menu_handle) %#ok

set(menu_handle,'Label','Add scrollbars');
sliders=getappdata(menu_handle,'sliders');
try
   delete(sliders(1))
catch
end
try
   delete(sliders(2))
catch
end
axislimits=getappdata(menu_handle,'axislimits');
axis(axis_handle,axislimits)


text:
import sqlite3
# import abc

from .helpers import find_join_index, invert_graph

class Table:

    def __init__(self, parent, name):
        self.parent = parent
        self.name = name

    @property
    def columns(self):
        return self.parent.table_columns(self.name)

    @property
    def primary_keys(self):
        return self.parent.table_primary_keys(self.name)

    @property
    def row_count(self):
        return self.parent.table_row_count(self.name)

    @property
    def index_candidates(self):
        return self.parent.table_index_candidates(self.name)

    def column_unique_count(self, column):
        return self.parent.column_unique_count(".".join((self.name, column)))

# TODO: consider ABC

class SqliteDatabase:

    def __init__(self, path):
        connection = sqlite3.connect(path)
        try:
            connection.execute("PRAGMA schema_version")
            self._connection = connection
        except sqlite3.DatabaseError:
            raise ValueError(
                "{} is not a valid SQLite database".format(path))

    @property
    def tables(self):
        crs = self._connection.cursor()
        crs.execute("SELECT name FROM SQLITE_MASTER WHERE type=\"table\"")
        return [table_name for (table_name,) in crs.fetchall()]

    @property
    def columns(self):
        return [c for cs in [[(".".join((table, column[0])), column[1])
                              for column in self.table_columns(table)]
                             for table in self.tables] for c in cs]

    @property
    def graph(self):
        return self.directed_graph()

    def __getitem__(self, item):
        if item in self.tables:
            return Table(self, item)
        else:
            raise KeyError("No table named {}".format(item))

    def table_columns(self, table):
        """List all columns in a table.

        Parameters
        ----------
        table : str

        Returns
        -------
        [str]
            List of column names
        """
        if table in self.tables:
            crs = self._connection.cursor()
            crs.execute("PRAGMA table_info({})".format(table))
            return [(col, sql_type.split(" ", 1)[0].upper())
                    for (_, col, sql_type, _, _, _) in crs.fetchall()]
        else:
            raise ValueError("No table named {}".format(table))

    def table_primary_keys(self, table):
        """List the primary key columns of a table.

        Parameters
        ----------
        table : str

        Returns
        -------
        [str]
            List of primary key column names
        """

        if table in self.tables:
            crs = self._connection.cursor()
            crs.execute("PRAGMA table_info({})".format(table))
            return [(col, sql_type.split(" ", 1)[0].upper())
                    for (_, col, sql_type, _, _, k) in crs.fetchall()
                    if any(s in sql_type.split(" ", 1)[-1].lower()
                           for s in ("primary_key", "primary key"))
                    or k > 0]

    def table_row_count(self, table):
        """Compute the number of rows in a table.

        Parameters
        ----------
        table : str
            Table name

        Returns
        -------
        int
            The number of rows
        """

        if table not in self.tables:
            raise ValueError("No table named {}".format(table))

        crs = self._connection.cursor()
        query = "SELECT COUNT(*) FROM {table_name}"
        crs.execute(query.format(table_name=table))
        n_rows = crs.fetchone()[0]

        return n_rows

    def column_unique_count(self, *args):
        """Compute the number of unique values in a given column or group of
        columns.

        Parameters
        ----------
        *args
            Qualified column names (e.g. MyTable.MyColumn), all sharing the
            same table name

        Returns
        -------
        int
            The number of unique values
        """

        if len(args) < 1:
            raise TypeError("Specify at least one column")

        for column in args:
            self._validate_column(column)

        tables, columns = zip(*map(lambda s: s.split("."), args))

        if any(not table == tables[0] for table in tables):
            raise ValueError("All columns must belong to the same table")

        crs = self._connection.cursor()
        if len(args) > 1:
            query = "SELECT COUNT(*) FROM " \
                    "(SELECT DISTINCT {columns} FROM {table})"
        else:
            query = "SELECT COUNT(DISTINCT {columns}) FROM {table}"

        crs.execute(query.format(columns=", ".join(columns),
                                 table=tables[0]))
        n_unique = crs.fetchone()[0]

        return n_unique

    def column_intersection_unique_count(self, column_1, column_2):
        """Compute the number of unique values in the intersection of two
        columns.

        Parameters
        ----------
        column_1 : str
            Qualified column name (e.g. MyTable.MyColumn)
        column_2 : str
            Qualified column name

        Returns
        -------
        int
            The number of unique values
        """

        table_name_1, column_name_1 = self._validate_column(column_1)
        table_name_2, column_name_2 = self._validate_column(column_2)

        crs = self._connection.cursor()
        query = "SELECT COUNT(DISTINCT {column_name_1}) FROM {table_name_1} " \
                "WHERE {column_name_1} IN " \
                "(SELECT {column_name_2} FROM {table_name_2})"
        crs.execute(query.format(column_name_1=column_name_1,
                                 column_name_2=column_name_2,
                                 table_name_1=table_name_1,
                                 table_name_2=table_name_2))
        n_unique = crs.fetchone()[0]

        return n_unique

    def all_unique(self, *args):
        """Check if all values in a column are unique.

        Parameters
        ----------
        *args
            Qualified column names (e.g. MyTable.MyColumn), all sharing the
            same table name

        Returns
        -------
        bool
            True if all values are unique, False otherwise
        """

        return self.table_row_count(args[0].split(".")[0]) == \
            self.column_unique_count(*args)

    def table_index_candidates(self, table):
        """List all index candidates for a given table in order of likelihood.

        The most likely candidate is usually the primary key or keys. If the
        first column or columns excluding a single INT primary key column are
        all INT or VARCHAR and form a candidate (i.e. all unique values or
        combinations), they should be considered as more likely as the primary
        key is expected to be merely a convenience key.

        A column is only considered as a candidate if it has all unique values
        or if some combination of other columns, each with fewer unique values,
        results in all unique combinations. INT columns are the most likely
        indices and multiplexers, followed by VARCHAR and then all other types.
        Finally, candidates with equally likely types are ordered in decreasing
        order of unique values summed over all multiplexers.

        Parameters
        ----------
        table : str
            Table name

        Returns
        -------
        [[str]]
            A list of lists of index candidates where the first item in an
            inner list is the master index and any subsequent items are
            multiplexers
        """

        columns = list(map(lambda x: (*x, self.column_unique_count(x[0])),
                           map(lambda x: (".".join((table, x[0])), x[1]),
                               self.table_columns(table))))

        primary_keys = [".".join((table, column[0]))
                        for column in self.table_primary_keys(table)]

        # Compute a graph {master: [(possible multiplexer, n_unique)]}
        graph = {outer: sorted([(inner, x_inner)
                                for (inner, _, x_inner) in columns
                                if x_inner < x_outer],
                               key=lambda x: x[1],
                               reverse=True)
                 for (outer, _, x_outer) in columns}

        # For each column, conduct a depth-first search to find candidate sets
        scored_candidates = []
        for column in graph.keys():
            this_candidate = []
            queue = [column]
            while queue:
                this_candidate.append(queue.pop())
                connections = graph[this_candidate[-1]]
                if self.all_unique(*this_candidate):
                    n_nonint = sum(not self._column_has_type(column, "INT")
                                   for column in this_candidate)
                    n_nonstring = sum(not self._column_has_type(column,
                                                                "VARCHAR")
                                      for column in this_candidate)
                    n_unique = sum(self.column_unique_count(column)
                                   for column in this_candidate)
                    score = (n_nonint, n_nonstring, n_unique)
                    scored_candidates.append((this_candidate.copy(), score))
                    this_candidate.pop()
                    continue
                elif connections:
                    queue.extend([c for c, _ in connections])
                else:
                    this_candidate.pop()

        scored_candidates.sort(key=lambda x: x[1])

        # Place primary key candidates first
        primary_key_candidates = []
        for k, candidate in enumerate(scored_candidates):
            if any(column in primary_keys for column in candidate[0]):
                primary_key_candidates.append(
                    scored_candidates.pop(k - len(primary_key_candidates)))

        # Leap-frog convenience index
        sorted_candidates = []
        if len(primary_keys) == 1 and self._column_has_type(primary_keys[0],
                                                            "INT"):
            if columns[0][0] == primary_keys[0]:
                first_non_key = columns[1]
            else:
                first_non_key = columns[0]

            if first_non_key[1].startswith("INT"):
                for k, candidate in enumerate(scored_candidates):
                    cond_1 = len(candidate[0]) > 1
                    if cond_1 and first_non_key[0] in candidate[0] and all(
                            self._column_has_type(column, "INT", "VARCHAR")
                            for column in candidate[0]):
                        sorted_candidates.append(
                            scored_candidates.pop(k - len(sorted_candidates)))

        sorted_candidates.extend(primary_key_candidates)
        sorted_candidates.extend(scored_candidates)

        return [[column.split(".")[1] for column in candidate]
                for candidate, _ in sorted_candidates]

    def graph_matching(self, *args):
        """Make an undirected graph connecting all columns in different tables
        whose sets of values fully match.

        Parameter
        ---------
        *args : str
            Qualified column names (e.g. MyTable.MyColumn) to be considered
            for the graph, if none are given all columns will be used

        Returns
        -------
        dict
            An undirected graph on the form {node: [connected_nodes]}

        Raises
        ------
        ValueError
            If a specified column does not exists
        """

        if len(args) > 0:
            columns = [c for c in self.columns if c[0] in args]
            if len(columns) < len(args):
                columns_ = [c[0] for c in columns]
                invalid_columns = [c for c in args if c not in columns_]
                raise ValueError("Invalid column name(s): {}".format(
                    ", ".join(invalid_columns)))
        else:
            columns = self.columns

        graph = {}
        for this_column in columns:
            this_table_name, _ = this_column[0].split(".")
            graph[this_column[0]] = []
            for other_column in columns:
                other_table_name, _ = other_column[0].split(".")
                if not other_table_name == this_table_name:
                    if self._score_columns(this_column, other_column) == 1:
                        graph[this_column[0]].append(other_column[0])
        return graph

    def masters_dict(self, *args):
        """Generate a dict linking each column to a master column selected for
        each group of columns with identical sets of unique values.

        Parameter
        ---------
        *args : str
            Qualified column names (e.g. MyTable.MyColumn) to be considered
            for the graph, if none are given all columns will be used

        Returns
        -------
        dict
            A dict on the form {column: master_column}

        Raises
        ------
        ValueError
            If a specified column does not exists
        """
        graph_ = self.graph_matching(*args)

        groups = list({tuple(sorted([c, *cs])) for c, cs in graph_.items()})

        graph = {}
        for group in groups:
            if len(group) == 1:
                graph[group[0]] = group[0]
                continue

            master = self._master(group)
            for column in group:
                graph[column] = master

        return graph

    def directed_graph(self, *args):
        """Make a directed graph with all full and partial column matches to
        other tables.

        Parameter
        ---------
        *args : str
            Qualified column names (e.g. MyTable.MyColumn) to be considered
            for the graph, if none are given all columns will be used

        Returns
        -------
        dict
            A graph on the form {node: [(connected_node, match_score)]}

        Raises
        ------
        ValueError
            If a specified column does not exists
        """

        if len(args) > 0:
            columns = [c for c in self.columns if c[0] in args]
            if len(columns) < len(args):
                columns_ = [c[0] for c in columns]
                invalid_columns = [c for c in args if c not in columns_]
                raise ValueError("Invalid column name(s): {}".format(
                    ", ".join(invalid_columns)))
        else:
            columns = self.columns

        graph = {}
        for this_column in columns:
            this_table_name, _ = this_column[0].split(".")
            graph[this_column[0]] = []
            for other_column in columns:
                other_table_name, _ = other_column[0].split(".")
                if not other_table_name == this_table_name:
                    score = self._score_columns(this_column, other_column)
                    if score >= 0:
                        graph[this_column[0]].append((other_column[0], score))
        return graph

    def reduced_graph_indices(self):
        """Make a directed graph of relations between index columns in the
        database.

        Within a group, all members point exclusively to the master.

        Returns
        -------
        dict
            A graph on the form {node: group_master or [other_master]}
        """

        # Consider only the most likely index candidates for each table
        columns = [".".join((table, column))
                   for table in self.tables
                   for column in self.table_index_candidates(table)[0]]

        masters = self.masters_dict(*columns)
        scored_graph = invert_graph(self.directed_graph(*columns), 0)

        graph = {}
        for column in columns:
            master = masters[column]
            if masters[column] == column:
                graph[column] = list(set(
                    masters[c] for c, m in scored_graph[column] if m < 1))
            else:
                graph[column] = master

        return graph

    def frame_candidates(self):
        """List column and index candidates for the entire database.

        Returns
        -------
        [kwargs]
            A list of keyword argument dicts to data frame constructors
        """

        graph = self.reduced_graph_indices()
        masters = [key for key, val in graph.items() if isinstance(val, list)]
        tables = self.tables

        candidates = []
        for master in masters:
            master_table, master_column = master.split(".")
            columns = {master: (master_table, master_column, master_column)}

            for table in tables:
                if table == master_table:
                    join_index = master_column
                else:
                    join_index = find_join_index(table, master, graph)

                if join_index is not None:
                    index_columns = self.table_index_candidates(table)[0]
                    # multiplexers = [c for c in index_columns
                    #                 if not c == join_index]
                    table_columns = [c[0] for c in self.table_columns(table)
                                     if c[0] not in index_columns]
                    for column in table_columns:
                        full_name = ".".join((table, column))
                        columns[full_name] = (table, column, join_index)

            candidates.append({"columns": columns, "index_col": master})

        return candidates

    def has_alias(self, column):
        """Checks if a column has an alias (i e another column in the same
        table with unique values for each unique value in this column.

        Parameters
        ----------
        column : str
            Qualified column name (e.g. MyTable.MyColumn)

        Returns
        -------
        bool
            True if column has an alias
        """

        table_name, column_name = self._validate_column(column)
        n_unique = self.column_unique_count(column)

        for column_name_, _ in self.table_columns(table_name):
            column_ = ".".join((table_name, column_name_))
            if not column_ == column:
                other_unique = self.column_unique_count(column_)
                intersect_unique = self.column_unique_count(column, column_)
                if other_unique == n_unique and intersect_unique == n_unique:
                    return True

        return False

    def _validate_column(self, column):
        try:
            table_name, column_name = column.split(".")
        except ValueError:
            raise ValueError(
                "{} is not a qualified column name".format(column))

        if table_name not in self.tables:
            raise ValueError("No table named {}".format(table_name))

        if column_name not in (c for (c, _) in self.table_columns(table_name)):
            raise ValueError(
                "No column named {column_name} in table {table_name}".format(
                    column_name=column_name, table_name=table_name))

        return table_name, column_name

    def _column_has_type(self, column, *args):
        table, column_ = column.split(".")
        column_types = {c: t for c, t in self.table_columns(table)}
        return column_types[column_].startswith(args)

    def _score_columns(self, this, other):
        name_1, type_1 = this
        name_2, type_2 = other

        if type_1 == type_2:
            u_this = self.column_unique_count(name_1)
            u_other = self.column_unique_count(name_2)
            u_intersection = self.column_intersection_unique_count(name_1,
                                                                   name_2)

            if u_intersection == u_this and u_this <= u_other:
                return u_this/u_other
            else:
                return -1

        else:
            return -1

    def _master(self, group):
        """Find the most suitable master column in a group.

        Parameters
        ----------
        group : tuple(str)
            Qualified names of columns that belong to the group

        Returns
        -------
        str
            Master column name
        """

        suitability = [(not self.has_alias(column),
                        self.column_unique_count(column),
                        len(self.table_columns(column.split(".")[0])),
                        column) for column in group]

        return sorted(suitability)[0][3]


text:
import {Injectable} from '@angular/core';
import {Options} from '@popperjs/core';
import {PlacementArray} from '../util/positioning';

/**
 * A configuration service for the [`NgbDropdown`](#/components/dropdown/api#NgbDropdown) component.
 *
 * You can inject this service, typically in your root component, and customize the values of its properties in
 * order to provide default values for all the dropdowns used in the application.
 */
@Injectable({providedIn: 'root'})
export class NgbDropdownConfig {
  autoClose: boolean | 'outside' | 'inside' = true;
  placement: PlacementArray = ['bottom-start', 'bottom-end', 'top-start', 'top-end'];
  popperOptions = (options: Partial<Options>) => options;
  container: null | 'body';
}


text:
"""Django model to DOT (Graphviz) converter
by Antonio Cavedoni <antonio@cavedoni.org>

Lightly modified by Chris Moffitt
Included in Satchmo with permission

"""

__version__ = "0.6"
__svnid__ = "$Id$"
__license__ = "Python"
__author__ = "Antonio Cavedoni <http://cavedoni.com/>"
__contributors__ = [
   "Stefano J. Attardi <http://attardi.org/>",
   "limodou <http://www.donews.net/limodou/>",
   "Carlo C8E Miron"
   ]

from django.db import models
from django.db.models import get_models
from django.db.models.fields.related import \
    ForeignKey, OneToOneField, ManyToManyField
from django.contrib.contenttypes.generic import GenericRelation
from django.template import Template, Context
import os
from textwrap import wrap
from string import join, split
os.environ["DJANGO_SETTINGS_MODULE"]="satchmo.settings"

dot_template = """
digraph {{ name }}
    {% autoescape off %}
   {
  graph [
        labelloc = t
        label= <

          Satchmo {{ title }} model

{{ doc }}

          >
        ]
  fontname = "Helvetica"
  fontsize = 8
  node [
    fontname = "Helvetica"
    fontsize = 8
    shape = "plaintext"
  ]
   edge [
    fontname = "Helvetica"
    fontsize = 8
  ]

  {% for model in models %}
  {{ model.name }} [label=<

{{ model.name }}

{{model.doc}}

     {% for field in model.fields %}

{{ field.name }}
     {{ field.type }}

     {% endfor %}

    >]

  {% for relation in model.relations %}
  {{ model.name }} -> {{ relation.target }}
    [label="{{ relation.type }}"] {{ relation.arrows }};
  {% endfor %}
  {% endfor %}
}
{% endautoescape %}
"""

def wrap_doc(docString, wraplimit=45):
    if docString:
        tmp = wrap(docString, 45)
        return join(tmp,"
")
    else:
        return ("")

def generate_dot(app_label):
   app = models.get_app(app_label)
   doc = wrap_doc(app.__doc__, 65)
   title = split(app.__name__,".")[1]
   graph = Context({
      'name': '"%s"' % app.__name__,
      'models': [],
      'doc': doc,
      'title': title,
      })

   for appmodel in get_models(app):
      tmpDoc = wrap_doc(appmodel.__doc__)
      model = {
         'name': app.__name__,
         'fields': [],
         'relations': [],
         'doc': tmpDoc
         }

      # model attributes
      def add_attributes():
         model['fields'].append({
               'name': field.name,
               'type': type(field).__name__
               })

      for field in appmodel._meta.fields:
         add_attributes()

      if appmodel._meta.many_to_many:
         for field in appmodel._meta.many_to_many:
            add_attributes()

      # relations
      def add_relation(extras=""):
         _rel = {
            'target': field.rel.to.__name__,
            'type': type(field).__name__,
            'arrows': extras
            }
         if _rel not in model['relations']:
            model['relations'].append(_rel)

      for field in appmodel._meta.fields:
         if isinstance(field, ForeignKey):
            add_relation()
         elif isinstance(field, OneToOneField):
            add_relation("[arrowhead=none arrowtail=none]")

      if appmodel._meta.many_to_many:
         for field in appmodel._meta.many_to_many:
            if isinstance(field, ManyToManyField):
               add_relation("[arrowhead=normal arrowtail=normal]")
            elif isinstance(field, GenericRelation):
               add_relation(
                  '[style="dotted"] [arrowhead=normal arrowtail=normal]')
      graph['models'].append(model)

   t = Template(dot_template)
   return t.render(graph)

if __name__ == "__main__":
   import sys
   try:
      app_label = sys.argv[1]
      print generate_dot(app_label)
   except IndexError:
      print __doc__


text:
package hypervisors

import (
	"strconv"

	"github.com/gophercloud/gophercloud"
	"github.com/gophercloud/gophercloud/pagination"
)

// List makes a request against the API to list hypervisors.
func List(client *gophercloud.ServiceClient) pagination.Pager {
	return pagination.NewPager(client, hypervisorsListDetailURL(client), func(r pagination.PageResult) pagination.Page {
		return HypervisorPage{pagination.SinglePageBase(r)}
	})
}

// Statistics makes a request against the API to get hypervisors statistics.
func GetStatistics(client *gophercloud.ServiceClient) (r StatisticsResult) {
	_, r.Err = client.Get(hypervisorsStatisticsURL(client), &r.Body, &gophercloud.RequestOpts{
		OkCodes: []int{200},
	})
	return
}

// Get makes a request against the API to get details for specific hypervisor.
func Get(client *gophercloud.ServiceClient, hypervisorID int) (r HypervisorResult) {
	v := strconv.Itoa(hypervisorID)
	_, r.Err = client.Get(hypervisorsGetURL(client, v), &r.Body, &gophercloud.RequestOpts{
		OkCodes: []int{200},
	})
	return
}

// GetUptime makes a request against the API to get uptime for specific hypervisor.
func GetUptime(client *gophercloud.ServiceClient, hypervisorID int) (r UptimeResult) {
	v := strconv.Itoa(hypervisorID)
	_, r.Err = client.Get(hypervisorsUptimeURL(client, v), &r.Body, &gophercloud.RequestOpts{
		OkCodes: []int{200},
	})
	return
}


text: package commandrunner // import "code.cloudfoundry.org/commandrunner"