def _sample_cell(args, cell_body):
  """Implements the bigquery sample cell magic for ipython notebooks.

  Args:
    args: the optional arguments following '%%bigquery sample'.
    cell_body: optional contents of the cell interpreted as SQL, YAML or JSON.
  Returns:
    The results of executing the sampling query, or a profile of the sample data.
  """

  env = datalab.utils.commands.notebook_environment()
  query = None
  table = None
  view = None

  if args['query']:
    query = _get_query_argument(args, cell_body, env)
  elif args['table']:
    table = _get_table(args['table'])
  elif args['view']:
    view = datalab.utils.commands.get_notebook_item(args['view'])
    if not isinstance(view, datalab.bigquery.View):
      raise Exception('%s is not a view' % args['view'])
  else:
    query = datalab.bigquery.Query(cell_body, values=env)

  count = args['count']
  method = args['method']
  if method == 'random':
    sampling = datalab.bigquery.Sampling.random(percent=args['percent'], count=count)
  elif method == 'hashed':
    sampling = datalab.bigquery.Sampling.hashed(field_name=args['field'], percent=args['percent'],
                                                count=count)
  elif method == 'sorted':
    ascending = args['order'] == 'ascending'
    sampling = datalab.bigquery.Sampling.sorted(args['field'],
                                                ascending=ascending,
                                                count=count)
  elif method == 'limit':
    sampling = datalab.bigquery.Sampling.default(count=count)
  else:
    sampling = datalab.bigquery.Sampling.default(count=count)

  if query:
    results = query.sample(sampling=sampling, dialect=args['dialect'], billing_tier=args['billing'])
  elif view:
    results = view.sample(sampling=sampling)
  else:
    results = table.sample(sampling=sampling)
  if args['verbose']:
    print(results.sql)
  if args['profile']:
    return datalab.utils.commands.profile_df(results.to_dataframe())
  else:
    return results
Implements the bigquery sample cell magic for ipython notebooks.

  Args:
    args: the optional arguments following '%%bigquery sample'.
    cell_body: optional contents of the cell interpreted as SQL, YAML or JSON.
  Returns:
    The results of executing the sampling query, or a profile of the sample data.