_id stringlengths 98 184 | text stringlengths 91 10.9k |
|---|---|
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/www/security.py#L366-L438 | def create_custom_dag_permission_view(self, session=None):
"""
"""
self.log.debug('Fetching a set of all permission, view_menu from FAB meta-table')
def merge_pv(perm, view_menu):
"""Create permission view menu only if it doesn't exist"""
if view_menu an... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/blockwise.py#L151-L172 | def _validate_block_sizes(block_sizes, bijectors, validate_args):
""""""
block_sizes_shape = block_sizes.shape
if tensorshape_util.is_fully_defined(block_sizes_shape):
if (tensorshape_util.rank(block_sizes_shape) != 1 or
(tensorshape_util.num_elements(block_sizes_shape) != len(bijectors))):
rais... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/jobs.py#L609-L738 | def manage_slas(self, dag, session=None):
"""
"""
if not any([isinstance(ti.sla, timedelta) for ti in dag.tasks]):
self.log.info("Skipping SLA check for %s because no tasks in DAG have SLAs", dag)
return
TI = models.TaskInstance
sq = (
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_transfer_hook.py#L246-L262 | def get_transfer_operation(self, operation_name):
"""
"""
return (
self.get_conn()
.transferOperations()
.get(name=operation_name)
.execute(num_retries=self.num_retries)
) |
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/references/classification/utils.py#L30-L41 | def synchronize_between_processes(self):
"""
"""
if not is_dist_avail_and_initialized():
return
t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda')
dist.barrier()
dist.all_reduce(t)
t = t.tolist()
self.count ... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/assert_util.py#L76-L106 | def assert_rank_at_most(x, rank, data=None, summarize=None, message=None,
name=None):
"""
"""
with tf.compat.v2.name_scope(name or 'assert_rank_at_most'):
return tf.compat.v1.assert_less_equal(
tf.rank(x), rank, data=data, summarize=summarize, message=message) |
https://github.com/soimort/you-get/blob/b746ac01c9f39de94cac2d56f665285b0523b974/src/you_get/common.py#L319-L326 | def ungzip(data):
"""
"""
from io import BytesIO
import gzip
buffer = BytesIO(data)
f = gzip.GzipFile(fileobj=buffer)
return f.read() |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/sample_halton_sequence.py#L345-L365 | def _base_expansion_size(num, bases):
"""
"""
return tf.floor(tf.math.log(num) / tf.math.log(bases)) + 1 |
https://github.com/asciimoo/searx/blob/a84caa22cf947e973c10aa968d35fb2bdda6d048/searx/engines/duden.py#L26-L39 | def request(query, params):
'''
'''
offset = (params['pageno'] - 1)
params['url'] = search_url.format(offset=offset, query=quote(query))
return params |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/sagemaker_hook.py#L86-L117 | def secondary_training_status_message(job_description, prev_description):
"""
"""
if job_description is None or job_description.get('SecondaryStatusTransitions') is None\
or len(job_description.get('SecondaryStatusTransitions')) == 0:
return ''
prev_description_secondary_trans... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/trainable_distributions/trainable_distributions_lib.py#L42-L61 | def softplus_and_shift(x, shift=1e-5, name=None):
"""
"""
with tf.compat.v1.name_scope(name, 'softplus_and_shift', [x, shift]):
x = tf.convert_to_tensor(value=x, name='x')
y = tf.nn.softplus(x)
if shift is not None:
y += shift
return y |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/task/task_runner/__init__.py#L27-L43 | def get_task_runner(local_task_job):
"""
"""
if _TASK_RUNNER == "StandardTaskRunner":
return StandardTaskRunner(local_task_job)
elif _TASK_RUNNER == "CgroupTaskRunner":
from airflow.contrib.task_runner.cgroup_task_runner import CgroupTaskRunner
return CgroupTaskRunner(local_... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/dingding_hook.py#L65-L74 | def _get_endpoint(self):
"""
"""
conn = self.get_connection(self.http_conn_id)
token = conn.password
if not token:
raise AirflowException('Dingding token is requests but get nothing, '
'check you conn_id configuration.')
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/kubernetes/worker_configuration.py#L188-L202 | def _get_security_context(self):
""""""
security_context = {}
if self.kube_config.worker_run_as_user:
security_context['runAsUser'] = self.kube_config.worker_run_as_user
if self.kube_config.worker_fs_group:
security_context['fsGroup'] = self.kube_config.worker_f... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vae.py#L191-L225 | def make_encoder(activation, latent_size, base_depth):
"""
"""
conv = functools.partial(
tf.keras.layers.Conv2D, padding="SAME", activation=activation)
encoder_net = tf.keras.Sequential([
conv(base_depth, 5, 1),
conv(base_depth, 5, 2),
conv(2 * base_depth, 5, 1),
conv(2 * base_dep... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/mysql_to_gcs.py#L269-L288 | def _convert_types(schema, col_type_dict, row):
"""
"""
converted_row = []
for col_name, col_val in zip(schema, row):
if type(col_val) in (datetime, date):
col_val = time.mktime(col_val.timetuple())
elif isinstance(col_val, Decimal):
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/decomposition.py#L29-L37 | def _split_covariance_into_marginals(covariance, block_sizes):
""""""
start_dim = 0
marginals = []
for size in block_sizes:
end_dim = start_dim + size
marginals.append(covariance[..., start_dim:end_dim, start_dim:end_dim])
start_dim = end_dim
return marginals |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/sample.py#L34-L52 | def _make_summary_statistic(attr):
""""""
def _fn(self, **kwargs):
"""Implements summary statistic, eg, mean, stddev, mode."""
x = getattr(self.distribution, attr)(**kwargs)
shape = prefer_static.concat([
self.distribution.batch_shape_tensor(),
prefer_static.ones(prefer_static.rank_from_... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/jobs.py#L2071-L2101 | def _task_instances_for_dag_run(self, dag_run, session=None):
"""
"""
tasks_to_run = {}
if dag_run is None:
return tasks_to_run
# check if we have orphaned tasks
self.reset_state_for_orphaned_tasks(filter_by_dag_run=dag_run, session=session)
... |
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/functional.py#L453-L465 | def vflip(img):
"""
"""
if not _is_pil_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
return img.transpose(Image.FLIP_TOP_BOTTOM) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/normal_conjugate_posteriors.py#L25-L81 | def normal_conjugates_known_scale_posterior(prior, scale, s, n):
"""
"""
if not isinstance(prior, normal.Normal):
raise TypeError("Expected prior to be an instance of type Normal")
if s.dtype != prior.dtype:
raise TypeError(
"Observation sum s.dtype does not match prior dtype: %s vs. %s"
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/mongo_hook.py#L104-L112 | def aggregate(self, mongo_collection, aggregate_query, mongo_db=None, **kwargs):
"""
"""
collection = self.get_collection(mongo_collection, mongo_db=mongo_db)
return collection.aggregate(aggregate_query, **kwargs) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/decomposition.py#L40-L106 | def _decompose_from_posterior_marginals(
model, posterior_means, posterior_covs, parameter_samples):
"""
"""
try:
model.components
except AttributeError:
raise ValueError('Model decomposed into components must be an instance of'
'`tfp.sts.Sum` (passed model {})'.format(model))
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/S3_hook.py#L295-L314 | def get_wildcard_key(self, wildcard_key, bucket_name=None, delimiter=''):
"""
"""
if not bucket_name:
(bucket_name, wildcard_key) = self.parse_s3_url(wildcard_key)
prefix = re.split(r'[*]', wildcard_key, 1)[0]
klist = self.list_keys(bucket_name, prefix=prefi... |
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/functional.py#L38-L94 | def to_tensor(pic):
"""
"""
if not(_is_pil_image(pic) or _is_numpy_image(pic)):
raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(type(pic)))
if isinstance(pic, np.ndarray):
# handle numpy array
if pic.ndim == 2:
pic = pic[:, :, None]
img =... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/fun_mcmc/fun_mcmc_lib.py#L122-L137 | def call_fn(fn: TransitionOperator, args: Union[Tuple[Any], Any]) -> Any:
"""
"""
if isinstance(args, (list, tuple)) and not mcmc_util.is_namedtuple_like(args):
args = args # type: Tuple[Any]
return fn(*args)
else:
return fn(args) |
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/transforms.py#L1064-L1089 | def get_params(degrees, translate, scale_ranges, shears, img_size):
"""
"""
angle = random.uniform(degrees[0], degrees[1])
if translate is not None:
max_dx = translate[0] * img_size[0]
max_dy = translate[1] * img_size[1]
translations = (np.round(random... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/poisson_lognormal.py#L88-L152 | def quadrature_scheme_lognormal_quantiles(
loc, scale, quadrature_size,
validate_args=False, name=None):
"""
"""
with tf.name_scope(name or "quadrature_scheme_lognormal_quantiles"):
# Create a LogNormal distribution.
dist = transformed_distribution.TransformedDistribution(
distribution=nor... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/mongo_hook.py#L186-L212 | def replace_one(self, mongo_collection, doc, filter_doc=None,
mongo_db=None, **kwargs):
"""
"""
collection = self.get_collection(mongo_collection, mongo_db=mongo_db)
if not filter_doc:
filter_doc = {'_id': doc['_id']}
return collection.r... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/batch_reshape.py#L294-L377 | def _validate_sample_arg(self, x):
""""""
with tf.name_scope("validate_sample_arg"):
x_ndims = (
tf.rank(x) if tensorshape_util.rank(x.shape) is None else
tensorshape_util.rank(x.shape))
event_ndims = (
tf.size(input=self.event_shape_tensor())
if tensorshape_u... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/internal/util.py#L296-L329 | def canonicalize_observed_time_series_with_mask(
maybe_masked_observed_time_series):
"""
"""
with tf.compat.v1.name_scope('canonicalize_observed_time_series_with_mask'):
if hasattr(maybe_masked_observed_time_series, 'is_missing'):
observed_time_series = (
maybe_masked_observed_time_series... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/spark_submit_hook.py#L378-L429 | def _process_spark_submit_log(self, itr):
"""
"""
# Consume the iterator
for line in itr:
line = line.strip()
# If we run yarn cluster mode, we want to extract the application id from
# the logs so we can kill the application when we stop it u... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_natural_language_hook.py#L198-L217 | def classify_text(self, document, retry=None, timeout=None, metadata=None):
"""
"""
client = self.get_conn()
return client.classify_text(document=document, retry=retry, timeout=timeout, metadata=metadata) |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_spanner_hook.py#L184-L209 | def get_database(self, instance_id, database_id, project_id=None):
"""
"""
instance = self._get_client(project_id=project_id).instance(
instance_id=instance_id)
if not instance.exists():
raise AirflowException("The instance {} does not exist in project {... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_api_base_hook.py#L148-L159 | def _get_field(self, f, default=None):
"""
"""
long_f = 'extra__google_cloud_platform__{}'.format(f)
if hasattr(self, 'extras') and long_f in self.extras:
return self.extras[long_f]
else:
return default |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/program_transformations.py#L34-L135 | def make_value_setter(**model_kwargs):
"""
"""
def set_values(f, *args, **kwargs):
"""Sets random variable values to its aligned value."""
name = kwargs.get("name")
if name in model_kwargs:
kwargs["value"] = model_kwargs[name]
return interceptable(f)(*args, **kwargs)
return set_values |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/sqoop_hook.py#L235-L256 | def import_query(self, query, target_dir, append=False, file_type="text",
split_by=None, direct=None, driver=None, extra_import_options=None):
"""
"""
cmd = self._import_cmd(target_dir, append, file_type, split_by, direct,
driver, extr... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/quantized_distribution.py#L372-L394 | def _log_prob_with_logsf_and_logcdf(self, y):
""""""
# There are two options that would be equal if we had infinite precision:
# Log[ sf(y - 1) - sf(y) ]
# = Log[ exp{logsf(y - 1)} - exp{logsf(y)} ]
# Log[ cdf(y) - cdf(y - 1) ]
# = Log[ exp{logcdf(y)} - exp{logcdf(y - 1)} ]
logsf_y = sel... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/normal.py#L234-L237 | def _inv_z(self, z):
""""""
with tf.name_scope("reconstruct"):
return z * self.scale + self.loc |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/hager_zhang.py#L579-L650 | def _prepare_args(value_and_gradients_function,
initial_step_size,
val_initial,
val_0,
approximate_wolfe_threshold):
"""
"""
eval_count = 0
if val_initial is None:
if initial_step_size is not None:
initial_step_size = tf.convert_t... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/dirichlet.py#L331-L403 | def _kl_dirichlet_dirichlet(d1, d2, name=None):
"""
"""
with tf.name_scope(name or "kl_dirichlet_dirichlet"):
# The KL between Dirichlet distributions can be derived as follows. We have
#
# Dir(x; a) = 1 / B(a) * prod_i[x[i]^(a[i] - 1)]
#
# where B(a) is the multivariate Beta function:
#... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/wasb_hook.py#L66-L82 | def check_for_prefix(self, container_name, prefix, **kwargs):
"""
"""
matches = self.connection.list_blobs(container_name, prefix,
num_results=1, **kwargs)
return len(list(matches)) > 0 |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/migrations/env.py#L48-L65 | def run_migrations_offline():
"""
"""
context.configure(
url=settings.SQL_ALCHEMY_CONN, target_metadata=target_metadata,
literal_binds=True, compare_type=COMPARE_TYPE)
with context.begin_transaction():
context.run_migrations() |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_pubsub_hook.py#L112-L137 | def delete_topic(self, project, topic, fail_if_not_exists=False):
"""
"""
service = self.get_conn()
full_topic = _format_topic(project, topic)
try:
service.projects().topics().delete(topic=full_topic).execute(num_retries=self.num_retries)
except HttpError as e... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/langevin.py#L630-L688 | def _euler_method(random_draw_parts,
state_parts,
drift_parts,
step_size_parts,
volatility_parts,
name=None):
"""
"""
with tf.compat.v1.name_scope(name, 'mala_euler_method', [
random_draw_parts, state_parts, drift_part... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/taskinstance.py#L674-L687 | def get_dagrun(self, session):
"""
"""
from airflow.models.dagrun import DagRun # Avoid circular import
dr = session.query(DagRun).filter(
DagRun.dag_id == self.dag_id,
DagRun.execution_date == self.execution_date
).first()
return dr |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/_vendor/nvd3/NVD3Chart.py#L179-L294 | def add_serie(self, y, x, name=None, extra=None, **kwargs):
"""
"""
if not name:
name = "Serie %d" % (self.serie_no)
# For scatterChart shape & size fields are added in serie
if 'shape' in kwargs or 'size' in kwargs:
csize = kwargs.get('size', 1... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/www/security.py#L221-L234 | def get_user_roles(self, user=None):
"""
"""
if user is None:
user = g.user
if user.is_anonymous:
public_role = appbuilder.config.get('AUTH_ROLE_PUBLIC')
return [appbuilder.security_manager.find_role(public_role)] \
if public_r... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/S3_hook.py#L109-L145 | def list_prefixes(self, bucket_name, prefix='', delimiter='',
page_size=None, max_items=None):
"""
"""
config = {
'PageSize': page_size,
'MaxItems': max_items,
}
paginator = self.get_conn().get_paginator('list_objects_v2')
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_vision_hook.py#L211-L222 | def delete_product_set(
self, location, product_set_id, project_id=None, retry=None, timeout=None, metadata=None
):
"""
"""
client = self.get_conn()
name = ProductSearchClient.product_set_path(project_id, location, product_set_id)
self.log.info('Deleting Prod... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/bigquery_hook.py#L1421-L1468 | def run_table_upsert(self, dataset_id, table_resource, project_id=None):
"""
"""
# check to see if the table exists
table_id = table_resource['tableReference']['tableId']
project_id = project_id if project_id is not None else self.project_id
tables_list_resp = se... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/docs/exts/docroles.py#L27-L55 | def get_template_field(env, fullname):
"""
"""
modname, classname = fullname.rsplit(".", 1)
try:
with mock(env.config.autodoc_mock_imports):
mod = import_module(modname)
except ImportError:
raise RoleException("Error loading %s module." % (modname, ))
clazz = g... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/batch_reshape.py#L234-L262 | def _call_reshape_input_output(self, fn, x, extra_kwargs=None):
""""""
# Note: we take `extra_kwargs` as a dict rather than `**extra_kwargs`
# because it is possible the user provided extra kwargs would itself
# have `fn` and/or `x` as a key.
with tf.control_dependencies(self._runtime_assertions +
... |
https://github.com/soimort/you-get/blob/b746ac01c9f39de94cac2d56f665285b0523b974/src/you_get/util/log.py#L72-L74 | def print_log(text, *colors):
""""""
sys.stderr.write(sprint("{}: {}".format(script_name, text), *colors) + "\n") |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/api/common/experimental/get_dag_runs.py#L25-L55 | def get_dag_runs(dag_id, state=None):
"""
"""
dagbag = DagBag()
# Check DAG exists.
if dag_id not in dagbag.dags:
error_message = "Dag id {} not found".format(dag_id)
raise AirflowException(error_message)
dag_runs = list()
state = state.lower() if state else None
f... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/backend/numpy/misc.py#L60-L71 | def _sort(values, axis=-1, direction='ASCENDING', stable=False, name=None): # pylint: disable=unused-argument
""""""
if direction == 'ASCENDING':
pass
elif direction == 'DESCENDING':
values = np.negative(values)
else:
raise ValueError('Unrecognized direction: {}.'.format(direction))
result = np.s... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/math/diag_jacobian.py#L32-L248 | def diag_jacobian(xs,
ys=None,
sample_shape=None,
fn=None,
parallel_iterations=10,
name=None):
"""
"""
with tf.compat.v1.name_scope(name, 'jacobians_diag', [xs, ys]):
if sample_shape is None:
sample_shape = [1]
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/www/security.py#L236-L244 | def get_all_permissions_views(self):
"""
"""
perms_views = set()
for role in self.get_user_roles():
perms_views.update({(perm_view.permission.name, perm_view.view_menu.name)
for perm_view in role.permissions})
return perms_view... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/S3_hook.py#L459-L518 | def copy_object(self,
source_bucket_key,
dest_bucket_key,
source_bucket_name=None,
dest_bucket_name=None,
source_version_id=None):
"""
"""
if dest_bucket_name is None:
dest_b... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/util.py#L196-L216 | def default_multivariate_normal_fn(dtype, shape, name, trainable,
add_variable_fn):
"""
"""
del name, trainable, add_variable_fn # unused
dist = tfd.Normal(loc=tf.zeros(shape, dtype), scale=dtype.as_numpy_dtype(1))
batch_ndims = tf.size(input=dist.batch_shape_tensor())
r... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/azure_cosmos_hook.py#L124-L140 | def does_database_exist(self, database_name):
"""
"""
if database_name is None:
raise AirflowBadRequest("Database name cannot be None.")
existing_database = list(self.get_conn().QueryDatabases({
"query": "SELECT * FROM r WHERE r.id=@id",
"par... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/slice_sampler_kernel.py#L540-L552 | def _maybe_call_fn(fn,
fn_arg_list,
fn_result=None,
description='target_log_prob'):
""""""
fn_arg_list = (list(fn_arg_list) if mcmc_util.is_list_like(fn_arg_list)
else [fn_arg_list])
if fn_result is None:
fn_result = fn(*fn_arg_list)
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/_vendor/nvd3/NVD3Chart.py#L374-L383 | def buildhtmlheader(self):
""""""
self.htmlheader = ''
# If the JavaScript assets have already been injected, don't bother re-sourcing them.
global _js_initialized
if '_js_initialized' not in globals() or not _js_initialized:
for css in self.header_css:
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/www/utils.py#L193-L201 | def json_response(obj):
"""
"""
return Response(
response=json.dumps(
obj, indent=4, cls=AirflowJsonEncoder),
status=200,
mimetype="application/json") |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/hidden_markov_model.py#L489-L517 | def _marginal_hidden_probs(self):
""""""
initial_log_probs = tf.broadcast_to(self._log_init,
tf.concat([self.batch_shape_tensor(),
[self._num_states]],
axis=0))
# ini... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/wasb_hook.py#L120-L135 | def get_file(self, file_path, container_name, blob_name, **kwargs):
"""
"""
return self.connection.get_blob_to_path(container_name, blob_name,
file_path, **kwargs) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/structural_time_series.py#L161-L209 | def prior_sample(self,
num_timesteps,
initial_step=0,
params_sample_shape=(),
trajectories_sample_shape=(),
seed=None):
"""
"""
seed = distributions.SeedStream(
seed, salt='StructuralTimeSeries_prior_samp... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/structural_time_series.py#L80-L94 | def batch_shape(self):
"""
"""
batch_shape = tf.TensorShape([])
for param in self.parameters:
batch_shape = tf.broadcast_static_shape(
batch_shape, param.prior.batch_shape)
return batch_shape |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/math/random_ops.py#L61-L99 | def random_rayleigh(shape, scale=None, dtype=tf.float32, seed=None, name=None):
"""
"""
with tf.compat.v1.name_scope(name, 'random_rayleigh', [shape, scale, seed]):
if scale is not None:
# Its important to expand the shape to match scale's, otherwise we won't
# have independent draws.
scale ... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_pubsub_hook.py#L263-L285 | def acknowledge(self, project, subscription, ack_ids):
"""
"""
service = self.get_conn()
full_subscription = _format_subscription(project, subscription)
try:
service.projects().subscriptions().acknowledge(
subscription=full_subscription, body={'ackIds'... |
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/functional.py#L212-L246 | def resize(img, size, interpolation=Image.BILINEAR):
"""
if not _is_pil_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
if not (isinstance(size, int) or (isinstance(size, Iterable) and len(size) == 2)):
raise TypeError('Got inappropriate size arg: {}'.fo... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/hive_hooks.py#L593-L599 | def get_tables(self, db, pattern='*'):
"""
"""
with self.metastore as client:
tables = client.get_tables(db_name=db, pattern=pattern)
return client.get_table_objects_by_name(db, tables) |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/azure_container_instance_hook.py#L133-L147 | def get_logs(self, resource_group, name, tail=1000):
"""
"""
logs = self.connection.container.list_logs(resource_group, name, name, tail=tail)
return logs.content.splitlines(True) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/trainable_distributions/trainable_distributions_lib.py#L284-L387 | def normal(x,
layer_fn=tf.compat.v1.layers.dense,
loc_fn=lambda x: x,
scale_fn=1.,
name=None):
"""
"""
with tf.compat.v1.name_scope(name, 'normal', [x]):
x = tf.convert_to_tensor(value=x, name='x')
if callable(scale_fn):
y = layer_fn(x, 2)
loc = loc_... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/joint_distribution_sequential.py#L38-L46 | def _make_summary_statistic(attr):
""""""
def _fn(self):
if any(self._dist_fn_args): # pylint: disable=protected-access
raise ValueError(
'Can only compute ' + attr + ' when all distributions are '
'independent; {}'.format(self.model))
return self._unflatten(getattr(d(), attr)() f... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/forecast.py#L35-L169 | def one_step_predictive(model, observed_time_series, parameter_samples):
"""
"""
with tf.compat.v1.name_scope(
'one_step_predictive', values=[observed_time_series, parameter_samples]):
[
observed_time_series,
is_missing
] = sts_util.canonicalize_observed_time_series_with_mask(
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/executors/kubernetes_executor.py#L473-L490 | def _make_safe_pod_id(safe_dag_id, safe_task_id, safe_uuid):
"""
"""
MAX_POD_ID_LEN = 253
safe_key = safe_dag_id + safe_task_id
safe_pod_id = safe_key[:MAX_POD_ID_LEN - len(safe_uuid) - 1] + "-" + safe_uuid
return safe_pod_id |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/sample_stats.py#L646-L661 | def _make_list_or_1d_tensor(values):
""""""
values = tf.convert_to_tensor(value=values, name='values')
values_ = tf.get_static_value(values)
# Static didn't work.
if values_ is None:
# Cheap way to bring to at least 1d.
return values + tf.zeros([1], dtype=values.dtype)
# Static worked!
if values... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/math/sparse.py#L30-L61 | def dense_to_sparse(x, ignore_value=None, name=None):
"""
"""
# Copied (with modifications) from:
# tensorflow/contrib/layers/python/ops/sparse_ops.py.
with tf.compat.v1.name_scope(name, 'dense_to_sparse', [x, ignore_value]):
x = tf.convert_to_tensor(value=x, name='x')
if ignore_value is None:
i... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/initializers.py#L119-L126 | def from_config(cls, config):
""""""
return cls(**{
'initializers': [tf.compat.v2.initializers.deserialize(init)
for init in config.get('initializers', [])],
'sizes': config.get('sizes', []),
'validate_args': config.get('validate_args', False),
}) |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/log/logging_mixin.py#L166-L184 | def set_context(logger, value):
"""
"""
_logger = logger
while _logger:
for handler in _logger.handlers:
try:
handler.set_context(value)
except AttributeError:
# Not all handlers need to have context passed in so we ignore
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/affine.py#L238-L309 | def _create_scale_operator(self, identity_multiplier, diag, tril,
perturb_diag, perturb_factor, shift, validate_args,
dtype):
"""
"""
identity_multiplier = _as_tensor(identity_multiplier, "identity_multiplier",
dt... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/random_variable.py#L133-L137 | def sample_shape(self):
""""""
if isinstance(self._sample_shape, tf.Tensor):
return tf.TensorShape(tf.get_static_value(self._sample_shape))
return tf.TensorShape(self._sample_shape) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/disentangled_vae.py#L488-L515 | def call(self, inputs):
"""
"""
# TODO(dusenberrymw): Remove these reshaping commands after b/113126249 is
# fixed.
collapsed_shape = tf.concat(([-1], tf.shape(input=inputs)[-2:]), axis=0)
out = tf.reshape(inputs, collapsed_shape) # (sample*batch_size, T, hidden)
out = self.bilstm(out) # (... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/sagemaker_hook.py#L519-L572 | def describe_training_job_with_log(self, job_name, positions, stream_names,
instance_count, state, last_description,
last_describe_job_call):
"""
"""
log_group = '/aws/sagemaker/TrainingJobs'
if len(s... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/hive_hooks.py#L641-L680 | def _get_max_partition_from_part_specs(part_specs, partition_key, filter_map):
"""
"""
if not part_specs:
return None
# Assuming all specs have the same keys.
if partition_key not in part_specs[0].keys():
raise AirflowException("Provided partitio... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_text_to_speech_hook.py#L42-L51 | def get_conn(self):
"""
"""
if not self._client:
self._client = TextToSpeechClient(credentials=self._get_credentials())
return self._client |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/backend/numpy/internal/utils.py#L58-L74 | def common_dtype(args_list, preferred_dtype=None):
""""""
dtype = None
preferred_dtype = (None if preferred_dtype is None
else tf.as_dtype(preferred_dtype))
for a in tf.nest.flatten(args_list):
if hasattr(a, 'dtype'):
dt = tf.as_dtype(a.dtype)
else:
continue
if dtype... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/jobs.py#L1015-L1039 | def __get_concurrency_maps(self, states, session=None):
"""
"""
TI = models.TaskInstance
ti_concurrency_query = (
session
.query(TI.task_id, TI.dag_id, func.count('*'))
.filter(TI.state.in_(states))
.group_by(TI.task_id, TI.dag_id... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/sample_halton_sequence.py#L368-L384 | def _primes_less_than(n):
# Based on
# https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
""""""
small_primes = np.array((2, 3, 5))
if n <= 6:
return small_primes[small_primes < n]
sieve = np.ones(n // 3 + (n % 6 == 2), dtype=np.bool)
sieve[0] ... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/diagnostic.py#L146-L200 | def _effective_sample_size_single_state(states, filter_beyond_lag,
filter_threshold):
""""""
with tf.compat.v1.name_scope(
'effective_sample_size_single_state',
values=[states, filter_beyond_lag, filter_threshold]):
states = tf.convert_to_tensor(value=states... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/special_math.py#L391-L407 | def _log_ndtr_asymptotic_series(x, series_order):
""""""
npdt = dtype_util.as_numpy_dtype(x.dtype)
if series_order <= 0:
return npdt(1)
x_2 = tf.square(x)
even_sum = tf.zeros_like(x)
odd_sum = tf.zeros_like(x)
x_2n = x_2 # Start with x^{2*1} = x^{2*n} with n = 1.
for n in range(1, series_order + 1)... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/disentangled_vae.py#L1035-L1052 | def summarize_dist_params(dist, name, name_scope="dist_params"):
"""
"""
with tf.compat.v1.name_scope(name_scope):
tf.compat.v2.summary.histogram(
name="{}/{}".format(name, "mean"),
data=dist.mean(),
step=tf.compat.v1.train.get_or_create_global_step())
tf.compat.v2.summary.histogra... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/taskinstance.py#L470-L474 | def key(self):
"""
"""
return self.dag_id, self.task_id, self.execution_date, self.try_number |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/datastore_hook.py#L83-L100 | def begin_transaction(self):
"""
"""
conn = self.get_conn()
resp = (conn
.projects()
.beginTransaction(projectId=self.project_id, body={})
.execute(num_retries=self.num_retries))
return resp['transaction'] |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_transfer_hook.py#L182-L200 | def update_transfer_job(self, job_name, body):
"""
"""
body = self._inject_project_id(body, BODY, PROJECT_ID)
return (
self.get_conn()
.transferJobs()
.patch(jobName=job_name, body=body)
.execute(num_retries=self.num_retries)
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/cassandra_to_gcs.py#L269-L280 | def convert_map_type(cls, name, value):
"""
"""
converted_map = []
for k, v in zip(value.keys(), value.values()):
converted_map.append({
'key': cls.convert_value('key', k),
'value': cls.convert_value('value', v)
})
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/http_hook.py#L183-L211 | def run_with_advanced_retry(self, _retry_args, *args, **kwargs):
"""
"""
self._retry_obj = tenacity.Retrying(
**_retry_args
)
self._retry_obj(self.run, *args, **kwargs) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/random_variable.py#L270-L275 | def numpy(self):
""""""
if not isinstance(self.value, ops.EagerTensor):
raise NotImplementedError("value argument must be a EagerTensor.")
return self.value.numpy() |
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/datasets/phototour.py#L189-L196 | def read_info_file(data_dir, info_file):
"""
"""
labels = []
with open(os.path.join(data_dir, info_file), 'r') as f:
labels = [int(line.split()[0]) for line in f]
return torch.LongTensor(labels) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.