Transfers SWAG data from one backend to another
518325
def propagate(ctx):
    """"""
    data = []
    if ctx.type == 'file':
        if ctx.data_file:
            file_path = ctx.data_file
        else:
            file_path = os.path.join(ctx.data_dir, ctx.namespace + '.json')

        with open(file_path, 'r') as f:
            data = json.loads(f.read())

    swag_opts = {
        'swag.type': 'dynamodb'
    }

    swag = SWAGManager(**parse_swag_config_options(swag_opts))

    for item in data:
        time.sleep(2)
        swag.create(item, dry_run=ctx.dry_run)
887705
def copy_package(owner, repo, identifier, destination):
    """"""
    client = get_packages_api()

    with catch_raise_api_exception():
        data, _, headers = client.packages_copy_with_http_info(
            owner=owner,
            repo=repo,
            identifier=identifier,
            data={"destination": destination},
        )

    ratelimits.maybe_rate_limit(client, headers)
    return data.slug_perm, data.slug
502692
def _migrate_ledger(data_directory,
                    old_ledger_file, new_ledger_file,
                    serializer: MappingSerializer = None):
    

    # we should have ChunkedFileStorage implementation of the Ledger
    if not os.path.isdir(os.path.join(data_directory, old_ledger_file)):
        msg = 'Could not find directory {} for migration.'.format(
            old_ledger_file)
        logger.error(msg)
        raise Exception(msg)

    # open the old ledger using the specified serializer
    old_ledger_file_backup = old_ledger_file + "_new"
    old_txn_log_store = ChunkedFileStore(data_directory,
                                         old_ledger_file_backup,
                                         isLineNoKey=True,
                                         storeContentHash=False)
    old_ledger = Ledger(CompactMerkleTree(),
                        dataDir=data_directory,
                        txn_serializer=serializer,
                        hash_serializer=serializer,
                        fileName=old_ledger_file_backup,
                        transactionLogStore=old_txn_log_store)

    # open the new ledger with new serialization
    new_ledger = Ledger(CompactMerkleTree(),
                        dataDir=data_directory,
                        fileName=new_ledger_file)
    logger.info("new size for {}: {}".format(
        old_ledger_file_backup, str(new_ledger.size)))

    # add all txns into the old ledger
    for _, txn in new_ledger.getAllTxn():
        old_ledger.add(txn)
    logger.info("old size for {}: {}".format(
        new_ledger_file, str(old_ledger.size)))

    old_ledger.stop()
    new_ledger.stop()

    # now that everything succeeded, remove the new files and move the old
    # files into place
    shutil.rmtree(
        os.path.join(data_directory, new_ledger_file))
    os.rename(
        os.path.join(data_directory, old_ledger_file_backup),
        os.path.join(data_directory, old_ledger_file))
654095
def export_datasource_schema(back_references):
    """"""
    data = dict_import_export.export_schema_to_dict(
        back_references=back_references)
    yaml.safe_dump(data, stdout, default_flow_style=False)
732216
def move_vobject(self, uuid, from_project, to_project):
        """"""
        if to_project not in self.get_filesnames():
            return

        uuid = uuid.split('@')[0]
        with self._lock:
            run(['task', 'rc.verbose=nothing', 'rc.data.location={self._data_location}'.format(**locals()), 'rc.confirmation=no', uuid, 'modify', 'project:{}'.format(basename(to_project))])
1006513
function sendResponse (req, res, next, dataStore) {
  return function (err, resources) {
    if (!err) {
      util.debug("%s successfully updated", res.swagger.location);

      if (resources.length > 0) {
        // Determine the max "modifiedOn" date of the resources
        res.swagger.lastModified = _.max(resources, "modifiedOn").modifiedOn;
      }
      else {
        // There is no data, so use the current date/time as the "last-modified" header
        res.swagger.lastModified = new Date();
      }

      // Extract the "data" of each Resource
      resources = _.map(resources, "data");
    }

    // Set the response body (unless it's already been set by other middleware)
    if (err || res.body) {
      next(err);
    }
    else if (!res.swagger.isCollection) {
      // Response body is a single value, so only return the first item that was edited
      res.body = _.first(resources);
      next();
    }
    else {
      // Response body is the entire collection (new, edited, and old)
      dataStore.getCollection(req.path, (err, collection) => {
        res.body = _.map(collection, "data");
        next(err);
      });
    }
  };
}
904566
def push(package, is_public=False, is_team=False, reupload=False, hash=None):
    
    team, owner, pkg, subpath = parse_package(package, allow_subpath=True)
    _check_team_id(team)
    session = _get_session(team)

    store, pkgroot = PackageStore.find_package(team, owner, pkg, pkghash=hash)
    if pkgroot is None:
        raise CommandException("Package {package} not found.".format(package=package))

    pkghash = hash_contents(pkgroot)
    if hash is not None:
        assert pkghash == hash
    contents = pkgroot

    for component in subpath:
        try:
            contents = contents.children[component]
        except (AttributeError, KeyError):
            raise CommandException("Invalid subpath: %r" % component)

    def _push_package(dry_run=False, sizes=dict()):
        data = json.dumps(dict(
            dry_run=dry_run,
            is_public=is_public,
            is_team=is_team,
            contents=contents,
            description="",  # TODO
            sizes=sizes
        ), default=encode_node)

        compressed_data = gzip_compress(data.encode('utf-8'))

        if subpath:
            return session.post(
                "{url}/api/package_update/{owner}/{pkg}/{subpath}".format(
                    url=get_registry_url(team),
                    owner=owner,
                    pkg=pkg,
                    subpath='/'.join(subpath)
                ),
                data=compressed_data,
                headers={
                    'Content-Encoding': 'gzip'
                }
            )
        else:
            return session.put(
                "{url}/api/package/{owner}/{pkg}/{hash}".format(
                    url=get_registry_url(team),
                    owner=owner,
                    pkg=pkg,
                    hash=pkghash
                ),
                data=compressed_data,
                headers={
                    'Content-Encoding': 'gzip'
                }
            )

    print("Fetching upload URLs from the registry...")
    resp = _push_package(dry_run=True)
    obj_urls = resp.json()['upload_urls']

    assert set(obj_urls) == set(find_object_hashes(contents))

    obj_sizes = {
        obj_hash: os.path.getsize(store.object_path(obj_hash)) for obj_hash in obj_urls
    }

    success = upload_fragments(store, obj_urls, obj_sizes, reupload=reupload)
    if not success:
        raise CommandException("Failed to upload fragments")

    print("Uploading package metadata...")
    resp = _push_package(sizes=obj_sizes)
    package_url = resp.json()['package_url']

    if not subpath:
        # Update the latest tag.
        print("Updating the 'latest' tag...")
        session.put(
            "{url}/api/tag/{owner}/{pkg}/{tag}".format(
                url=get_registry_url(team),
                owner=owner,
                pkg=pkg,
                tag=LATEST_TAG
            ),
            data=json.dumps(dict(
                hash=pkghash
            ))
        )

    print("Push complete. %s is live:\n%s" % (package, package_url))
266567
def get_card_transfer(provider: Provider, deck: Deck,
                      txid: str,
                      debug: bool=False) -> Iterator:
    ''''''

    rawtx = provider.getrawtransaction(txid, 1)

    bundle = card_bundler(provider, deck, rawtx)

    return card_bundle_parser(bundle, debug)
1198241
def client_data(typ, challenge)
      JSON.dump(
        challenge: challenge,
        origin: app_id,
        typ: typ
      )
    end
574566
function transfer( targetObj, ...sourceObjList ) {
    sourceObjList.forEach(sourceObj => {
        Object.keys(sourceObj).forEach(sourceObjKey => {
            targetObj[sourceObjKey] = sourceObj[sourceObjKey];
        })
    });
    return targetObj;
}
680557
def fetch(self, transfer_id, data={}, **kwargs):
        "
        return super(Transfer, self).fetch(transfer_id, data, **kwargs)
315406
def transfer(cls, field_mappings, source, destination_factory):
    """"""
    data = dict()
    for index, field_mapping in enumerate(field_mappings):
      try:
        data[field_mapping.destination_name] = field_mapping.get_value(source)
      except Exception as ex:
        raise Exception(
          "Error with mapping #{0} '{1}'->'{2}': {3}".format(
            index,
            field_mapping.source_name,
            field_mapping.destination_name, ex)) from ex
    return destination_factory(data)
424801
def _restore_transfers(self, response):
        

        transfers = []
        for transfer_data in response.json()['transfers']:
            transfer = Transfer(self, _restore=True)
            transfer.transfer_info.update(transfer_data)
            transfer.get_files()
            transfers.append(transfer)

        return transfers
410428
private void transferLinks(LinkedHashMapEntry<K,V> src,
                               LinkedHashMapEntry<K,V> dst) {
        LinkedHashMapEntry<K,V> b = dst.before = src.before;
        LinkedHashMapEntry<K,V> a = dst.after = src.after;
        if (b == null)
            head = dst;
        else
            b.after = dst;
        if (a == null)
            tail = dst;
        else
            a.before = dst;
    }
905502
def install(self, backend='money.exchange.SimpleBackend'):
        """"""
        # RADAR: Python2
        if isinstance(backend, money.six.string_types):
            path, name = backend.rsplit('.', 1)
            module = importlib.import_module(path)
            backend = getattr(module, name)()
        elif isinstance(backend, type):
            backend = backend()
        if not isinstance(backend, BackendBase):
            raise TypeError("backend '{}' is not a subclass of "
                            "money.xrates.BackendBase".format(backend))
        self._backend = backend
42479
function fetchData(token) {
    sdk.feed.startpage(token).then(function(stream) {
        return stream.messages.map(function(message) {
            return message.attachments.filter(function(attachment) {
                return attachment.type === 'IMAGE';
            });
        });
    }).then(function(imageAttachmentArrays) {
        return imageAttachmentArrays.reduce(function(prev, cur) {
            return prev.concat(cur);
        }, []);
    }).then(function(imageAttachments) {
        imageAttachments.forEach(function(attachment) {
            var file_name = attachment.url.split('/').reverse()[0];
            request('https://' + sdk.config.domain + attachment.url)
                .pipe(fs.createWriteStream(file_name))
                .on('finish', function() {
                    console.log('saved attachment ' + file_name);
                });
        });
    }).catch(function(err) {
        console.log('Error:', err);
    });
}
339040
def merge_data!(other, source: "YAML front matter")
      merge_categories!(other)
      Utils.deep_merge_hashes!(data, other)
      merge_date!(source)
      data
    end