_id stringlengths 98 184 | text stringlengths 91 10.9k |
|---|---|
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L887-L891 | def _sort_tensor(tensor):
""""""
sorted_, _ = tf.nn.top_k(tensor, k=tf.shape(input=tensor)[-1])
sorted_.set_shape(tensor.shape)
return sorted_ |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/prefer_static.py#L100-L117 | def rank_from_shape(shape_tensor_fn, tensorshape=None):
""""""
if tensorshape is None:
shape_tensor = (shape_tensor_fn() if callable(shape_tensor_fn)
else shape_tensor_fn)
if (hasattr(shape_tensor, 'shape') and
hasattr(shape_tensor.shape, 'num_elements')):
ndims_ = tensors... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/backend/numpy/linalg.py#L97-L109 | def _matmul(a, b,
transpose_a=False, transpose_b=False,
adjoint_a=False, adjoint_b=False,
a_is_sparse=False, b_is_sparse=False,
name=None): # pylint: disable=unused-argument
""""""
if a_is_sparse or b_is_sparse:
raise NotImplementedError('Numpy backend does not s... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/latent_dirichlet_allocation_edward2.py#L194-L223 | def make_lda_variational(activation, num_topics, layer_sizes):
"""
"""
encoder_net = tf.keras.Sequential()
for num_hidden_units in layer_sizes:
encoder_net.add(
tf.keras.layers.Dense(
num_hidden_units,
activation=activation,
kernel_initializer=tf.compat.v1.glorot_... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/diagnostic.py#L388-L393 | def _axis_size(x, axis=None):
""""""
if axis is None:
return tf.cast(tf.size(input=x), x.dtype)
return tf.cast(
tf.reduce_prod(input_tensor=tf.gather(tf.shape(input=x), axis)), x.dtype) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/vector_diffeomixture.py#L936-L941 | def concat_vectors(*args):
""""""
args_ = [tf.get_static_value(x) for x in args]
if any(vec is None for vec in args_):
return tf.concat(args, axis=0)
return [val for vec in args_ for val in vec] |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/internal/slicing.py#L145-L155 | def _apply_single_step(dist, params_event_ndims, slices, params_overrides):
""""""
if len(slices) == 1 and slices[0] == Ellipsis:
# The path used by Distribution.copy: batch_slice(...args..., Ellipsis)
override_dict = {}
else:
override_dict = _slice_params_to_dict(dist, params_event_ndims, slices)
o... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/dbapi_hook.py#L81-L94 | def get_pandas_df(self, sql, parameters=None):
"""
"""
import pandas.io.sql as psql
with closing(self.get_conn()) as conn:
return psql.read_sql(sql, con=conn, params=parameters) |
https://github.com/asciimoo/searx/blob/a84caa22cf947e973c10aa968d35fb2bdda6d048/searx/autocomplete.py#L37-L110 | def searx_bang(full_query):
''''''
# check if there is a query which can be parsed
if len(full_query.getSearchQuery()) == 0:
return []
results = []
# check if current query stats with !bang
first_char = full_query.getSearchQuery()[0]
if first_char == '!' or first_char == '?':
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L1701-L1793 | def reduce_weighted_logsumexp(logx,
w=None,
axis=None,
keep_dims=False,
return_sign=False,
name=None):
"""
"""
with tf.name_scope(name or "reduce_weighted_logsumexp... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/glm/proximal_hessian.py#L235-L488 | def fit_sparse(model_matrix,
response,
model,
model_coefficients_start,
tolerance,
l1_regularizer,
l2_regularizer=None,
maximum_iterations=None,
maximum_full_sweeps_per_iteration=1,
lea... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/jobs.py#L2637-L2673 | def heartbeat_callback(self, session=None):
""""""
if self.terminating:
# ensure termination if processes are created later
self.task_runner.terminate()
return
self.task_instance.refresh_from_db()
ti = self.task_instance
fqdn = get_hostname(... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/postgres_to_gcs_operator.py#L114-L122 | def _query_postgres(self):
"""
"""
postgres = PostgresHook(postgres_conn_id=self.postgres_conn_id)
conn = postgres.get_conn()
cursor = conn.cursor()
cursor.execute(self.sql, self.parameters)
return cursor |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/linear_gaussian_ssm.py#L1275-L1394 | def build_kalman_filter_step(get_transition_matrix_for_timestep,
get_transition_noise_for_timestep,
get_observation_matrix_for_timestep,
get_observation_noise_for_timestep):
"""
"""
def kalman_filter_step(state, elems_t):
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/jobs.py#L1362-L1399 | def _change_state_for_tasks_failed_to_execute(self, session):
"""
"""
if self.executor.queued_tasks:
TI = models.TaskInstance
filter_for_ti_state_change = (
[and_(
TI.dag_id == dag_id,
TI.task_id == task_id,... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/mongo_hook.py#L281-L297 | def delete_many(self, mongo_collection, filter_doc, mongo_db=None, **kwargs):
"""
"""
collection = self.get_collection(mongo_collection, mongo_db=mongo_db)
return collection.delete_many(filter_doc, **kwargs) |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/qubole_hook.py#L192-L200 | def get_log(self, ti):
"""
"""
if self.cmd is None:
cmd_id = ti.xcom_pull(key="qbol_cmd_id", task_ids=self.task_id)
Command.get_log_id(self.cls, cmd_id) |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/mongo_to_s3.py#L71-L103 | def execute(self, context):
"""
"""
s3_conn = S3Hook(self.s3_conn_id)
# Grab collection and execute query according to whether or not it is a pipeline
if self.is_pipeline:
results = MongoHook(self.mongo_conn_id).aggregate(
mongo_collection=se... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/api/common/experimental/get_task.py#L24-L40 | def get_task(dag_id, task_id):
""""""
dagbag = DagBag()
# Check DAG exists.
if dag_id not in dagbag.dags:
error_message = "Dag id {} not found".format(dag_id)
raise DagNotFound(error_message)
# Get DAG object and check Task Exists
dag = dagbag.get_dag(dag_id)
if not dag.has... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/vi/csiszar_divergence.py#L506-L547 | def log1p_abs(logu, name=None):
"""
"""
with tf.compat.v1.name_scope(name, "log1p_abs", [logu]):
logu = tf.convert_to_tensor(value=logu, name="logu")
return tf.math.expm1(tf.abs(logu)) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/masked_autoregressive.py#L957-L966 | def _create_masks(degrees):
""""""
return [
# Create input->hidden and hidden->hidden masks.
inp[:, np.newaxis] <= out
for inp, out in zip(degrees[:-1], degrees[1:])
] + [
# Create hidden->output mask.
degrees[-1][:, np.newaxis] < degrees[0]
] |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/jobs.py#L1325-L1359 | def _execute_task_instances(self,
simple_dag_bag,
states,
session=None):
"""
"""
executable_tis = self._find_executable_task_instances(simple_dag_bag, states,
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/bfgs.py#L327-L352 | def _update_inv_hessian(prev_state, next_state):
""""""
# Only update the inverse Hessian if not already failed or converged.
should_update = ~next_state.converged & ~next_state.failed
# Compute the normalization term (y^T . s), should not update if is singular.
gradient_delta = next_state.objective_gradient... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/latent_dirichlet_allocation_distributions.py#L225-L255 | def make_prior(num_topics, initial_value):
"""
"""
def _softplus_inverse(x):
return np.log(np.expm1(x))
logit_concentration = tf.compat.v1.get_variable(
"logit_concentration",
shape=[1, num_topics],
initializer=tf.compat.v1.initializers.constant(
_softplus_inverse(initial_value)... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/bijector.py#L122-L129 | def _deep_tuple(self, x):
""""""
if isinstance(x, dict):
return self._deep_tuple(tuple(sorted(x.items())))
elif isinstance(x, (list, tuple)):
return tuple(map(self._deep_tuple, x))
return x |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/decomposition.py#L222-L325 | def decompose_forecast_by_component(model, forecast_dist, parameter_samples):
"""
"""
with tf.compat.v1.name_scope('decompose_forecast_by_component'):
try:
forecast_lgssm = forecast_dist.components_distribution
forecast_latent_mean, _ = forecast_lgssm._joint_mean() # pylint: disable=protected-a... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/positive_semidefinite_kernels/internal/util.py#L157-L171 | def maybe_get_common_dtype(arg_list):
"""
"""
# Note that `all` defaults to `True` if `arg_list` is empty.
if all(a is None for a in arg_list):
return None
return dtype_util.common_dtype(arg_list, tf.float32) |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/sftp_hook.py#L126-L143 | def describe_directory(self, path):
"""
"""
conn = self.get_conn()
flist = conn.listdir_attr(path)
files = {}
for f in flist:
modify = datetime.datetime.fromtimestamp(
f.st_mtime).strftime('%Y%m%d%H%M%S')
files[f.filename] ... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/util.py#L119-L193 | def default_mean_field_normal_fn(
is_singular=False,
loc_initializer=tf.compat.v1.initializers.random_normal(stddev=0.1),
untransformed_scale_initializer=tf.compat.v1.initializers.random_normal(
mean=-3., stddev=0.1),
loc_regularizer=None,
untransformed_scale_regularizer=None,
loc_constr... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_api_base_hook.py#L137-L146 | def _authorize(self):
"""
"""
credentials = self._get_credentials()
http = httplib2.Http()
authed_http = google_auth_httplib2.AuthorizedHttp(
credentials, http=http)
return authed_http |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/qubole_hook.py#L164-L190 | def get_results(self, ti=None, fp=None, inline=True, delim=None, fetch=True):
"""
"""
if fp is None:
iso = datetime.datetime.utcnow().isoformat()
logpath = os.path.expanduser(
configuration.conf.get('core', 'BASE_LOG_FOLDER')
)
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_video_intelligence_hook.py#L41-L49 | def get_conn(self):
"""
"""
if not self._conn:
self._conn = VideoIntelligenceServiceClient(credentials=self._get_credentials())
return self._conn |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/bfgs.py#L476-L491 | def _tensor_product(t1, t2):
"""
"""
return tf.matmul(tf.expand_dims(t1, axis=-1), tf.expand_dims(t2, axis=-2)) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L2103-L2159 | def expand_to_vector(x, tensor_name=None, op_name=None, validate_args=False):
"""
"""
with tf.name_scope(op_name or "expand_to_vector"):
x = tf.convert_to_tensor(value=x, name="x")
ndims = tensorshape_util.rank(x.shape)
if ndims is None:
# Maybe expand ndims from 0 to 1.
if validate_args:... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/no_u_turn_sampler/nuts.py#L478-L500 | def _leapfrog(value_and_gradients_fn,
current_state,
current_grads_target_log_prob,
current_momentum,
step_size):
""""""
mid_momentum = [
m + 0.5 * step * g for m, step, g in
zip(current_momentum, step_size, current_grads_target_log_prob)]
next_s... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/sqoop_operator.py#L166-L234 | def execute(self, context):
"""
"""
self.hook = SqoopHook(
conn_id=self.conn_id,
verbose=self.verbose,
num_mappers=self.num_mappers,
hcatalog_database=self.hcatalog_database,
hcatalog_table=self.hcatalog_table,
prop... |
https://github.com/asciimoo/searx/blob/a84caa22cf947e973c10aa968d35fb2bdda6d048/searx/engines/currency_convert.py#L64-L87 | def response(resp):
""""""
json_resp = resp.text[resp.text.find('\n') + 1:resp.text.rfind('\n') - 2]
results = []
try:
conversion_rate = float(json.loads(json_resp)['conversion']['converted-amount'])
except:
return results
answer = '{0} {1} = {2} {3}, 1 {1} ({5}) = {4} {3} ({6})'... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/differential_evolution.py#L712-L768 | def _get_mixing_indices(size, seed=None, name=None):
"""
"""
with tf.compat.v1.name_scope(
name, default_name='get_mixing_indices', values=[size]):
size = tf.convert_to_tensor(value=size)
dtype = size.dtype
seed_stream = distributions.SeedStream(seed, salt='get_mixing_indices')
first = tf.ra... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/api/common/experimental/mark_tasks.py#L243-L280 | def set_dag_run_state_to_failed(dag, execution_date, commit=False, session=None):
"""
"""
res = []
if not dag or not execution_date:
return res
# Mark the dag run to failed.
if commit:
_set_dag_run_state(dag.dag_id, execution_date, State.FAILED, session)
# Mark only R... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/sample.py#L81-L372 | def sample_chain(
num_results,
current_state,
previous_kernel_results=None,
kernel=None,
num_burnin_steps=0,
num_steps_between_results=0,
trace_fn=lambda current_state, kernel_results: kernel_results,
return_final_kernel_results=False,
parallel_iterations=10,
name=None,
):
"""
... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/ti_deps/deps/base_ti_dep.py#L110-L125 | def is_met(self, ti, session, dep_context=None):
"""
"""
return all(status.passed for status in
self.get_dep_statuses(ti, session, dep_context)) |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/www/api/experimental/endpoints.py#L47-L92 | def trigger_dag(dag_id):
"""
"""
data = request.get_json(force=True)
run_id = None
if 'run_id' in data:
run_id = data['run_id']
conf = None
if 'conf' in data:
conf = data['conf']
execution_date = None
if 'execution_date' in data and data['execution_date'] is n... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/edward2/interceptor.py#L199-L245 | def tape():
"""
"""
tape_data = collections.OrderedDict({})
def record(f, *args, **kwargs):
"""Records execution to a tape."""
name = kwargs.get("name")
output = interceptable(f)(*args, **kwargs)
if name:
tape_data[name] = output
return output
with interception(record):
yield ... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/independent.py#L279-L339 | def _kl_independent(a, b, name="kl_independent"):
"""
"""
p = a.distribution
q = b.distribution
# The KL between any two (non)-batched distributions is a scalar.
# Given that the KL between two factored distributions is the sum, i.e.
# KL(p1(x)p2(y) || q1(x)q2(y)) = KL(p1 || q1) + KL(q1 || q2), we comput... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L2162-L2195 | def with_dependencies(dependencies, output_tensor, name=None):
"""
"""
if tf.executing_eagerly():
return output_tensor
with tf.name_scope(name or "control_dependency") as name:
with tf.control_dependencies(d for d in dependencies if d is not None):
output_tensor = tf.convert_to_tensor(value=output... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py#L241-L288 | def _secant2_inner_update(value_and_gradients_function,
initial_args,
val_0,
val_c,
f_lim,
sufficient_decrease_param,
curvature_param):
""""""
# Fail if `val_c`... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/conv_variational.py#L1111-L1126 | def get_config(self):
"""
"""
config = {
'seed': self.seed,
}
base_config = super(_ConvFlipout, self).get_config()
return dict(list(base_config.items()) + list(config.items())) |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/redshift_hook.py#L68-L83 | def describe_cluster_snapshots(self, cluster_identifier):
"""
"""
response = self.get_conn().describe_cluster_snapshots(
ClusterIdentifier=cluster_identifier
)
if 'Snapshots' not in response:
return None
snapshots = response['Snapshots']
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/dirichlet_multinomial.py#L322-L327 | def _variance_scale_term(self):
""""""
# Expand back the last dim so the shape of _variance_scale_term matches the
# shape of self.concentration.
c0 = self.total_concentration[..., tf.newaxis]
return tf.sqrt((1. + c0 / self.total_count[..., tf.newaxis]) / (1. + c0)) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/math/root_search.py#L44-L321 | def secant_root(objective_fn,
initial_position,
next_position=None,
value_at_position=None,
position_tolerance=1e-8,
value_tolerance=1e-8,
max_iterations=50,
stopping_policy_fn=tf.reduce_all,
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/wishart.py#L425-L430 | def _multi_lgamma(self, a, p, name="multi_lgamma"):
""""""
with self._name_scope(name):
seq = self._multi_gamma_sequence(a, p)
return (0.25 * p * (p - 1.) * math.log(math.pi) +
tf.reduce_sum(input_tensor=tf.math.lgamma(seq), axis=[-1])) |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/sensors/hdfs_sensor.py#L59-L76 | def filter_for_filesize(result, size=None):
"""
"""
if size:
log = LoggingMixin().log
log.debug(
'Filtering for file size >= %s in files: %s',
size, map(lambda x: x['path'], result)
)
size *= settings.MEGABY... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/math/linalg.py#L323-L445 | def pinv(a, rcond=None, validate_args=False, name=None):
"""
"""
with tf.compat.v1.name_scope(name, 'pinv', [a, rcond]):
a = tf.convert_to_tensor(value=a, name='a')
assertions = _maybe_validate_matrix(a, validate_args)
if assertions:
with tf.control_dependencies(assertions):
a = tf.iden... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/internal/missing_values_util.py#L109-L134 | def moments_of_masked_time_series(time_series_tensor, broadcast_mask):
"""
"""
num_unmasked_entries = tf.cast(
tf.reduce_sum(input_tensor=tf.cast(~broadcast_mask, tf.int32), axis=-1),
time_series_tensor.dtype)
# Manually compute mean and variance, excluding masked entries.
mean = (tf.reduce_sum(i... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/cassandra_to_gcs.py#L147-L154 | def _query_cassandra(self):
"""
"""
self.hook = CassandraHook(cassandra_conn_id=self.cassandra_conn_id)
session = self.hook.get_conn()
cursor = session.execute(self.cql)
return cursor |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/bigquery_hook.py#L1657-L1703 | def get_datasets_list(self, project_id=None):
"""
"""
dataset_project_id = project_id if project_id else self.project_id
try:
datasets_list = self.service.datasets().list(
projectId=dataset_project_id).execute(num_retries=self.num_retries)['datasets'... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/sagemaker_hook.py#L398-L426 | def create_transform_job(self, config, wait_for_completion=True,
check_interval=30, max_ingestion_time=None):
"""
"""
self.check_s3_url(config['TransformInput']['DataSource']['S3DataSource']['S3Uri'])
response = self.get_conn().create_transform_job... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/bijector.py#L112-L120 | def _merge(self, old, new, use_equals=False):
""""""
if old is None:
return new
if new is None:
return old
if (old == new) if use_equals else (old is new):
return old
raise ValueError("Incompatible values: %s != %s" % (old, new)) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/quantiles.py#L790-L802 | def _get_best_effort_ndims(x,
expect_ndims=None,
expect_ndims_at_least=None,
expect_ndims_no_more_than=None):
""""""
ndims_static = _get_static_ndims(
x,
expect_ndims=expect_ndims,
expect_ndims_at_least=expect_ndims_a... |
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/functional.py#L410-L432 | def _get_perspective_coeffs(startpoints, endpoints):
"""
"""
matrix = []
for p1, p2 in zip(endpoints, startpoints):
matrix.append([p1[0], p1[1], 1, 0, 0, 0, -p2[0] * p1[0], -p2[0] * p1[1]])
matrix.append([0, 0, 0, p1[0], p1[1], 1, -p2[1] * p1[0], -p2[1] * p1[1]])
A = torch.tensor(m... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/opsgenie_alert_hook.py#L61-L74 | def get_conn(self, headers=None):
"""
"""
conn = self.get_connection(self.http_conn_id)
self.base_url = conn.host if conn.host else 'https://api.opsgenie.com'
session = requests.Session()
if headers:
session.headers.update(headers)
return sess... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/gamma.py#L273-L296 | def _kl_gamma_gamma(g0, g1, name=None):
"""
"""
with tf.name_scope(name or "kl_gamma_gamma"):
# Result from:
# http://www.fil.ion.ucl.ac.uk/~wpenny/publications/densities.ps
# For derivation see:
# http://stats.stackexchange.com/questions/11646/kullback-leibler-divergence-between-two-gamma-dis... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/grammar_vae.py#L166-L182 | def mask(self, symbol, on_value, off_value):
"""
"""
mask_values = [on_value if lhs == symbol else off_value
for lhs, _ in self.production_rules]
mask_values = tf.reshape(mask_values, [1, len(self.production_rules)])
return mask_values |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/seasonal.py#L628-L691 | def build_constrained_seasonal_transition_noise(
drift_scale, num_seasons, is_last_day_of_season):
""""""
# Conceptually, this method takes the noise covariance on effects L @ L'
# computed by `build_seasonal_transition_noise`, with scale factor
# L = [ 0, 0, ..., 0
# ...
# ... |
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/keras/topology.py#L150-L168 | def evaluate(self, x, y=None, batch_size=32):
"""
"""
if isinstance(x, np.ndarray) and isinstance(y, np.ndarray):
evaluation_data = to_sample_rdd(x, y)
elif isinstance(x, RDD) and not y:
evaluation_data = x
else:
raise TypeError("Unsup... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/latent_dirichlet_allocation_distributions.py#L164-L194 | def make_encoder(activation, num_topics, layer_sizes):
"""
"""
encoder_net = tf.keras.Sequential()
for num_hidden_units in layer_sizes:
encoder_net.add(
tf.keras.layers.Dense(
num_hidden_units,
activation=activation,
kernel_initializer=tf.compat.v1.glorot_normal_i... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/vae.py#L462-L476 | def build_fake_input_fns(batch_size):
""""""
random_sample = np.random.rand(batch_size, *IMAGE_SHAPE).astype("float32")
def train_input_fn():
dataset = tf.data.Dataset.from_tensor_slices(
random_sample).map(lambda row: (row, 0)).batch(batch_size).repeat()
return tf.compat.v1.data.make_one_shot_it... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/sagemaker_hook.py#L450-L477 | def create_endpoint(self, config, wait_for_completion=True,
check_interval=30, max_ingestion_time=None):
"""
"""
response = self.get_conn().create_endpoint(**config)
if wait_for_completion:
self.check_status(config['EndpointName'],
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/distribution_layer.py#L696-L720 | def new(params, event_shape=(), dtype=None, validate_args=False, name=None):
""""""
with tf.compat.v1.name_scope(name, 'IndependentBernoulli',
[params, event_shape]):
params = tf.convert_to_tensor(value=params, name='params')
event_shape = dist_util.expand_to_vector(... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/langevin.py#L691-L745 | def _get_drift(step_size_parts, volatility_parts, grads_volatility,
grads_target_log_prob,
name=None):
"""
"""
with tf.compat.v1.name_scope(name, 'mala_get_drift', [
step_size_parts, volatility_parts, grads_volatility, grads_target_log_prob
]):
drift_parts = []
for... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/jobs.py#L1042-L1214 | def _find_executable_task_instances(self, simple_dag_bag, states, session=None):
"""
"""
executable_tis = []
# Get all task instances associated with scheduled
# DagRuns which are not backfilled, in the given states,
# and the dag is not paused
TI = mode... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L1864-L1929 | def process_quadrature_grid_and_probs(quadrature_grid_and_probs,
dtype,
validate_args,
name=None):
"""
"""
with tf.name_scope(name or "process_quadrature_grid_and_probs"):
if quadrature_grid_and_p... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/timezone.py#L67-L79 | def utc_epoch():
"""
"""
# pendulum utcnow() is not used as that sets a TimezoneInfo object
# instead of a Timezone. This is not pickable and also creates issues
# when using replace()
d = dt.datetime(1970, 1, 1)
d = d.replace(tzinfo=utc)
return d |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/linear_gaussian_ssm.py#L1688-L1721 | def build_pushforward_latents_step(get_observation_matrix_for_timestep,
get_observation_noise_for_timestep):
"""
"""
def pushforward_latents_step(_, latent_t_mean_cov):
"""Loop body fn to pushforward latents to observations at a time step."""
t, latent_mean, latent_cov ... |
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/optim/optimizer.py#L848-L894 | def create(model,
training_set,
criterion,
end_trigger=None,
batch_size=32,
optim_method=None,
cores=None,
bigdl_type="float"):
"""
"""
if not end_trigger:
end_trigger = ... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L281-L351 | def shapes_from_loc_and_scale(loc, scale, name="shapes_from_loc_and_scale"):
"""
"""
if loc is not None and tensorshape_util.rank(loc.shape) == 0:
loc = None # scalar loc is irrelevant to determining batch/event shape.
with tf.name_scope(name):
# Get event shape.
event_size = scale.range_dimension_... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/taskinstance.py#L218-L247 | def command(
self,
mark_success=False,
ignore_all_deps=False,
ignore_depends_on_past=False,
ignore_task_deps=False,
ignore_ti_state=False,
local=False,
pickle_id=None,
raw=False,
job_id=None,
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/internal/correlation_matrix_volumes_lib.py#L172-L216 | def correlation_matrix_volume_rejection_samples(
det_bounds, dim, sample_shape, dtype, seed):
"""
"""
with tf.compat.v1.name_scope("rejection_sampler"):
rej_proposals = _uniform_correlation_like_matrix(
dim, sample_shape, dtype, seed=seed)
rej_proposal_volume = 2. ** (dim * (dim - 1) / 2.)
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/real_nvp.py#L228-L305 | def real_nvp_default_template(hidden_layers,
shift_only=False,
activation=tf.nn.relu,
name=None,
*args, # pylint: disable=keyword-arg-before-vararg
**kwargs):
"""
""... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/dtype_util.py#L201-L228 | def assert_same_float_dtype(tensors=None, dtype=None):
"""
"""
if tensors:
dtype = _assert_same_base_type(tensors, dtype)
if not dtype:
dtype = tf.float32
elif not is_floating(dtype):
raise ValueError('Expected floating point type, got {}.'.format(dtype))
return dtype |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/lbfgs.py#L80-L260 | def minimize(value_and_gradients_function,
initial_position,
num_correction_pairs=10,
tolerance=1e-8,
x_tolerance=0,
f_relative_tolerance=0,
initial_inverse_hessian_estimate=None,
max_iterations=50,
parallel_iteratio... |
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/models/alexnet.py#L51-L61 | def alexnet(pretrained=False, **kwargs):
"""
model = AlexNet(**kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['alexnet']))
return model |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/linear_gaussian_ssm.py#L1622-L1685 | def build_kalman_sample_step(get_transition_matrix_for_timestep,
get_transition_noise_for_timestep,
get_observation_matrix_for_timestep,
get_observation_noise_for_timestep,
full_sample_and_batch_shape,
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/internal/distribution_util.py#L1274-L1320 | def pick_vector(cond, true_vector, false_vector, name="pick_vector"):
"""
"""
with tf.name_scope(name):
cond = tf.convert_to_tensor(
value=cond, dtype_hint=tf.bool, name="cond")
if cond.dtype != tf.bool:
raise TypeError(
"{}.dtype={} which is not {}".format(cond, cond.dtype, tf.boo... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/ti_deps/deps/base_ti_dep.py#L128-L142 | def get_failure_reasons(self, ti, session, dep_context=None):
"""
"""
for dep_status in self.get_dep_statuses(ti, session, dep_context):
if not dep_status.passed:
yield dep_status.reason |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/pinot_hook.py#L36-L49 | def get_conn(self):
"""
"""
conn = self.get_connection(self.pinot_broker_conn_id)
pinot_broker_conn = connect(
host=conn.host,
port=conn.port,
path=conn.extra_dejson.get('endpoint', '/pql'),
scheme=conn.extra_dejson.get('schema', '... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/task/task_runner/base_task_runner.py#L101-L135 | def run_command(self, run_with=None, join_args=False):
"""
"""
run_with = run_with or []
cmd = [" ".join(self._command)] if join_args else self._command
full_cmd = run_with + cmd
self.log.info('Running: %s', full_cmd)
proc = subprocess.Popen(
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/joint_distribution.py#L324-L341 | def maybe_check_wont_broadcast(flat_xs, validate_args):
""""""
flat_xs = tuple(flat_xs) # So we can receive generators.
if not validate_args:
# Note: we don't try static validation because it is theoretically
# possible that a user wants to take advantage of broadcasting.
# Only when `validate_args` ... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/redshift_hook.py#L46-L66 | def delete_cluster(
self,
cluster_identifier,
skip_final_cluster_snapshot=True,
final_cluster_snapshot_identifier=''):
"""
"""
response = self.get_conn().delete_cluster(
ClusterIdentifier=cluster_identifier,
SkipFin... |
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/ti_deps/deps/base_ti_dep.py#L78-L107 | def get_dep_statuses(self, ti, session, dep_context=None):
"""
"""
# this avoids a circular dependency
from airflow.ti_deps.dep_context import DepContext
if dep_context is None:
dep_context = DepContext()
if self.IGNOREABLE and dep_context.ignore_al... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/transformed_distribution.py#L41-L49 | def _pick_scalar_condition(pred, cond_true, cond_false):
""""""
# Note: This function is only valid if all of pred, cond_true, and cond_false
# are scalars. This means its semantics are arguably more like tf.cond than
# tf.where even though we use tf.where to implement it.
pred_ = tf.get_static_value(tf.conve... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/bijector.py#L104-L110 | def remove(self, field):
""""""
return _Mapping(
x=None if field == "x" else self.x,
y=None if field == "y" else self.y,
ildj=self.ildj,
kwargs=self.kwargs) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/internal/hager_zhang_lib.py#L599-L643 | def _bisect(value_and_gradients_function, initial_args, f_lim):
""""""
def _loop_cond(curr):
# TODO(b/112524024): Also take into account max_iterations.
return ~tf.reduce_all(input_tensor=curr.stopped)
def _loop_body(curr):
"""Narrow down interval to satisfy opposite slope conditions."""
mid = va... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/sts/structural_time_series.py#L211-L272 | def joint_log_prob(self, observed_time_series):
"""
"""
with tf.compat.v1.name_scope(
'joint_log_prob', values=[observed_time_series]):
[
observed_time_series,
mask
] = sts_util.canonicalize_observed_time_series_with_mask(
observed_time_series)
num_t... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/internal/correlation_matrix_volumes_lib.py#L107-L130 | def _det_large_enough_mask(x, det_bounds):
"""
"""
# For the curious: I wonder whether it is possible and desirable to
# use a Cholesky decomposition-based algorithm for this, since the
# only matrices whose determinant this code cares about will be PSD.
# Didn't figure out how to code that in TensorFlow.
... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/math/linalg.py#L874-L895 | def _sparse_block_diag(sp_a):
"""
"""
# Construct the matrix [[M, N], [1, 0], [0, 1]] which would map the index
# (b, i, j) to (Mb + i, Nb + j). This effectively creates a block-diagonal
# matrix of dense shape [B * M, B * N].
# Note that this transformation doesn't increase the number of non-zero
# entri... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/sprites_dataset.py#L188-L191 | def create_random_seq(character, action_metadata, direction, length=8):
""""""
start = tf.random.uniform([], maxval=action_metadata[1], dtype=tf.int32)
return create_seq(character, action_metadata, direction, length, start) |
https://github.com/intel-analytics/BigDL/blob/e9c19788285986ab789a2e2998f9a85d7524779f/pyspark/bigdl/nn/layer.py#L68-L76 | def load(path, bigdl_type="float"):
"""
"""
jmodel = callBigDlFunc(bigdl_type, "loadBigDL", path)
return Layer.of(jmodel) |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/examples/sprites_dataset.py#L152-L185 | def create_seq(character, action_metadata, direction, length=8, start=0):
"""
"""
sprite_start = (action_metadata[0]+direction) * FRAME_SIZE
sprite_end = (action_metadata[0]+direction+1) * FRAME_SIZE
sprite_line = character[sprite_start:sprite_end, ...]
# Extract 64x64 patches that are side-by-side in the ... |
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/hager_zhang.py#L666-L680 | def _print(pass_through_tensor, values):
""""""
flat_values = []
for value in values:
# Checks if it is a namedtuple.
if hasattr(value, '_fields'):
for field in value._fields:
flat_values.extend([field, _to_str(getattr(value, field))])
continue
if isinstance(value, (list, tuple)):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.