Bitbucket webhooks.
18959
protected function bitbucketWebhook($payload, $project)
    {
        $results = array();
        $status = 'failed';
        foreach ($payload['push']['changes'] as $commit) {
            try {
                $email = $commit['new']['target']['author']['raw'];
                $email = substr($email, 0, strpos($email, '>'));
                $email = substr($email, strpos($email, '<') + 1);

                $results[$commit['new']['target']['hash']] = $this->createBuild(
                    $project,
                    $commit['new']['target']['hash'],
                    $commit['new']['name'],
                    $email,
                    $commit['new']['target']['message']
                );
                $status = 'ok';
            } catch (Exception $ex) {
                $results[$commit['new']['target']['hash']] = array('status' => 'failed', 'error' => $ex->getMessage());
            }
        }

        return array('status' => $status, 'commits' => $results);
    }
510333
def webhooks(self):
        
        if self._webhooks is None:
            self._webhooks = WebhookList(
                self._version,
                service_sid=self._solution['service_sid'],
                channel_sid=self._solution['sid'],
            )
        return self._webhooks
1007641
public function setHook()
    {
        Hook::subscribe(Hook::SHUTDOWN_HOOK, [$this, 'saveCacheHook'], 10);

        foreach ($this->repository as $name => $cache)
            $this->checkExpiry($name);
    }
743368
long swapRandomTagInBucket(long curIndex, long tag) {
		int randomBucketPosition = ThreadLocalRandom.current().nextInt(CuckooFilter.BUCKET_SIZE);
		return readTagAndSet(curIndex, randomBucketPosition, tag);
	}
587092
function isGitHooks () {
  return co(function * () {
    const ppid = yield getPPID()

    debug(`ppid: ${ppid}`)

    return isRunByHusky(ppid)
  }).catch(/* istanbul ignore next */ function (err) {
    debug('error: %o', err)
    return false
  })
}
24769
def sync_hooks(user_id, repositories):
    """"""
    from .api import GitHubAPI

    try:
        # Sync hooks
        gh = GitHubAPI(user_id=user_id)
        for repo_id in repositories:
            try:
                with db.session.begin_nested():
                    gh.sync_repo_hook(repo_id)
                # We commit per repository, because while the task is running
                # the user might enable/disable a hook.
                db.session.commit()
            except RepositoryAccessError as e:
                current_app.logger.warning(e.message, exc_info=True)
            except NoResultFound:
                pass  # Repository not in DB yet
    except Exception as exc:
        sync_hooks.retry(exc=exc)
198088
function updateHooks() {
    Object.keys(require.extensions).forEach(function (ext) {
      var fn = require.extensions[ext];
      if (typeof fn === 'function' && fn.name !== 'nodeDevHook') {
        require.extensions[ext] = createHook(fn);
      }
    });
  }
436510
def subscribe_to_address_webhook(callback_url, subscription_address, event='tx-confirmation', confirmations=0, confidence=0.00, coin_symbol='btc', api_key=None):
    '''
    
    '''
    assert is_valid_coin_symbol(coin_symbol)
    assert is_valid_address_for_coinsymbol(subscription_address, coin_symbol)
    assert api_key, 'api_key required'

    url = make_url(coin_symbol, 'hooks')

    params = {'token': api_key}
    data = {
        'event': event,
        'url': callback_url,
        'address': subscription_address,
    }

    if event == 'tx-confirmation' and confirmations:
        data['confirmations'] = confirmations
    elif event == 'tx-confidence' and confidence:
        data['confidence'] = confidence

    r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
    response_dict = get_valid_json(r)
    return response_dict['id']
1106126
public WebhookResources webhookResources() {
        if (webhooks.get() == null) {
            webhooks.compareAndSet(null, new WebhookResourcesImpl(this));
        }
        return webhooks.get();
    }
281715
function (filename, arg, callback) {
      console.log('*** git-hooks.js run', filename, arg);
        var hookName = path.basename(filename);
        var hooksDirname = path.resolve(path.dirname(filename), '../../.githooks', hookName);

        if (fsHelpers.exists(hooksDirname)) {
            var list = fs.readdirSync(hooksDirname);
            var hooks = list.map(function (hookName) {
                return path.resolve(hooksDirname, hookName);
            });
            excludeIgnoredPaths(hooks, function (filteredHooks) {
                runHooks(filteredHooks, [arg], callback);
            });
        } else {
            callback(0);
        }
    }
326568
def deleteWebhook(self, hook_id):
        """"""
        path = '/'.join(['notification', 'webhook', hook_id])
        return self.rachio.delete(path)
629072
function flushPins (callback) {
    let dLink, rLink, root
    series([
      // create a DAGLink to the node with direct pins
      cb => waterfall([
        cb => pinset.storeSet(directKeys(), cb),
        ({ node, cid }, cb) => DAGLink.create(types.direct, node.size, cid, cb),
        (link, cb) => { dLink = link; cb(null) }
      ], cb),

      // create a DAGLink to the node with recursive pins
      cb => waterfall([
        cb => pinset.storeSet(recursiveKeys(), cb),
        ({ node, cid }, cb) => DAGLink.create(types.recursive, node.size, cid, cb),
        (link, cb) => { rLink = link; cb(null) }
      ], cb),

      // the pin-set nodes link to a special 'empty' node, so make sure it exists
      cb => DAGNode.create(Buffer.alloc(0), (err, empty) => {
        if (err) { return cb(err) }
        dag.put(empty, {
          version: 0,
          hashAlg: 'sha2-256',
          format: 'dag-pb',
          preload: false
        }, cb)
      }),

      // create a root node with DAGLinks to the direct and recursive DAGs
      cb => DAGNode.create(Buffer.alloc(0), [dLink, rLink], (err, node) => {
        if (err) { return cb(err) }
        root = node
        dag.put(root, {
          version: 0,
          hashAlg: 'sha2-256',
          format: 'dag-pb',
          preload: false
        }, (err, cid) => {
          if (!err) {
            root.multihash = cid.buffer
          }
          cb(err)
        })
      }),

      // hack for CLI tests
      cb => repo.closed ? repo.open(cb) : cb(null, null),

      // save root to datastore under a consistent key
      cb => repo.datastore.put(pinDataStoreKey, root.multihash, cb)
    ], (err, res) => {
      if (err) { return callback(err) }
      self.log(`Flushed pins with root: ${root}`)
      return callback(null, root)
    })
  }
280155
def update!
      client.put("/webhooks/#{id}", {
        description: description,
        idModel: id_model,
        callbackURL: callback_url,
        active: active
      })
    end
902498
def webhooks(self):
        
        if self._webhooks is None:
            self._webhooks = WebhookList(self._version, session_sid=self._solution['sid'], )
        return self._webhooks
1032018
function (workingDirectory) {
        var gitPath = getClosestGitPath(workingDirectory);

        if (!gitPath) {
            throw new Error('git-hooks must be run inside a git repository');
        }

        var hooksPath = path.resolve(gitPath, HOOKS_DIRNAME);
        var pathToGitHooks = path.join(path.relative(hooksPath, __dirname), 'git-hooks');
 
        if (isWin32) {
            pathToGitHooks = pathToGitHooks.replace(/\\/g, '\\\\');
        }

        if (fsHelpers.exists(hooksOldPath)) {
            throw new Error('git-hooks already installed');
        }

        if (fsHelpers.exists(hooksPath)) {
            fs.renameSync(hooksPath, hooksOldPath);
        }

        var hookTemplate = fs.readFileSync(__dirname + '/' + HOOKS_TEMPLATE_FILE_NAME);
        var pathToGitHooks = path.relative(hooksPath, __dirname);
        // Fix non-POSIX (Windows) separators
        pathToGitHooks = pathToGitHooks.replace(new RegExp(path.sep.replace(/\\/g, '\\$&'), 'g'), '/');
        var hook = util.format(hookTemplate.toString(), pathToGitHooks);

        fsHelpers.makeDir(hooksPath);
        HOOKS.forEach(function (hookName) {
            var hookPath = path.resolve(hooksPath, hookName);
            try {
                fs.writeFileSync(hookPath, hook, {mode: '0777'});
            } catch (e) {
                // node 0.8 fallback
                fs.writeFileSync(hookPath, hook, 'utf8');
                fs.chmodSync(hookPath, '0777');
            }
        });
    }
712223
public function beforeHook() : void
    {
        $commentChar = $this->repository->getConfigOperator()->getSafely('core.commentchar', '#');
        $commitMsg   = Git\CommitMessage::createFromFile($this->arguments->get('file', ''), $commentChar);

        $this->repository->setCommitMsg($commitMsg);

        parent::beforeHook();
    }
1211696
async function initRepo({ repository, endpoint, localDir }) {
  logger.debug(`initRepo("${repository}")`);
  const opts = hostRules.find({ platform: 'bitbucket' }, { endpoint });
  // istanbul ignore next
  if (!(opts.username && opts.password)) {
    throw new Error(
      `No username/password found for Bitbucket repository ${repository}`
    );
  }
  hostRules.update({ ...opts, platform: 'bitbucket', default: true });
  api.reset();
  config = {};
  // TODO: get in touch with @rarkins about lifting up the caching into the app layer
  config.repository = repository;
  const platformConfig = {};

  // Always gitFs
  const url = GitStorage.getUrl({
    gitFs: 'https',
    auth: `${opts.username}:${opts.password}`,
    hostname: 'bitbucket.org',
    repository,
  });

  config.storage = new GitStorage();
  await config.storage.initRepo({
    ...config,
    localDir,
    url,
  });

  try {
    const info = utils.repoInfoTransformer(
      (await api.get(`/2.0/repositories/${repository}`)).body
    );
    platformConfig.privateRepo = info.privateRepo;
    platformConfig.isFork = info.isFork;
    platformConfig.repoFullName = info.repoFullName;
    config.owner = info.owner;
    logger.debug(`${repository} owner = ${config.owner}`);
    config.defaultBranch = info.mainbranch;
    config.baseBranch = config.defaultBranch;
    config.mergeMethod = info.mergeMethod;
  } catch (err) /* istanbul ignore next */ {
    if (err.statusCode === 404) {
      throw new Error('not-found');
    }
    logger.info({ err }, 'Unknown Bitbucket initRepo error');
    throw err;
  }
  delete config.prList;
  delete config.fileList;
  await Promise.all([getPrList(), getFileList()]);
  return platformConfig;
}