_id
stringlengths
98
184
text
stringlengths
91
10.9k
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/mssql_hook.py#L38-L49
def get_conn(self): """ """ conn = self.get_connection(self.mssql_conn_id) conn = pymssql.connect( server=conn.host, user=conn.login, password=conn.password, database=self.schema or conn.schema, port=conn.port) ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/jobs.py#L1929-L1977
def _update_counters(self, ti_status): """ """ for key, ti in list(ti_status.running.items()): ti.refresh_from_db() if ti.state == State.SUCCESS: ti_status.succeeded.add(key) self.log.debug("Task instance %s succeeded. Don't rerun....
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/azure_fileshare_hook.py#L136-L153
def get_file_to_stream(self, stream, share_name, directory_name, file_name, **kwargs): """ """ self.connection.get_file_to_stream(share_name, directory_name, file_name, stream, **kwargs)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_vision_hook.py#L128-L161
def create_product_set( self, location, product_set, project_id=None, product_set_id=None, retry=None, timeout=None, metadata=None, ): """ """ client = self.get_conn() parent = ProductSearchClient.location_path(...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/mongo_hook.py#L69-L85
def get_conn(self): """ """ if self.client is not None: return self.client # Mongo Connection Options dict that is unpacked when passed to MongoClient options = self.extras # If we are using SSL disable requiring certs from specific hostname ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/jenkins_job_trigger_operator.py#L34-L79
def jenkins_request_with_headers(jenkins_server, req): """ """ try: response = jenkins_server.jenkins_request(req) response_body = response.content response_headers = response.headers if response_body is None: raise jenkins.EmptyResponseException( ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/xcom.py#L188-L218
def get_many(cls, execution_date, key=None, task_ids=None, dag_ids=None, include_prior_dates=False, limit=100, session=None): """ """ filters = [] if key: ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/__init__.py#L27-L32
def _integrate_plugins(): """""" from airflow.plugins_manager import hooks_modules for hooks_module in hooks_modules: sys.modules[hooks_module.__name__] = hooks_module globals()[hooks_module._name] = hooks_module
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/references/classification/utils.py#L172-L184
def setup_for_distributed(is_master): """ """ import builtins as __builtin__ builtin_print = __builtin__.print def print(*args, **kwargs): force = kwargs.pop('force', False) if is_master or force: builtin_print(*args, **kwargs) __builtin__.print = print
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/mongo_hook.py#L135-L142
def insert_many(self, mongo_collection, docs, mongo_db=None, **kwargs): """ """ collection = self.get_collection(mongo_collection, mongo_db=mongo_db) return collection.insert_many(docs, **kwargs)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/sftp_hook.py#L155-L163
def create_directory(self, path, mode=777): """ """ conn = self.get_conn() conn.mkdir(path, mode)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/taskinstance.py#L295-L361
def generate_command(dag_id, task_id, execution_date, mark_success=False, ignore_all_deps=False, ignore_depends_on_past=False, ignore_task_deps=False, ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/spark_submit_hook.py#L513-L537
def _build_spark_driver_kill_command(self): """ """ # If the spark_home is passed then build the spark-submit executable path using # the spark_home; otherwise assume that spark-submit is present in the path to # the executing user if self._connection['spark_hom...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/aws_glue_catalog_hook.py#L95-L118
def check_for_partition(self, database_name, table_name, expression): """ """ partitions = self.get_partitions(database_name, table_name, expression, max_items=1) if partitions: return True else: return False
https://github.com/asciimoo/searx/blob/a84caa22cf947e973c10aa968d35fb2bdda6d048/searx/utils.py#L190-L195
def get_themes(templates_path): """""" themes = os.listdir(templates_path) if '__common__' in themes: themes.remove('__common__') return themes
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_transfer_hook.py#L235-L243
def cancel_transfer_operation(self, operation_name): """ """ self.get_conn().transferOperations().cancel(name=operation_name).execute(num_retries=self.num_retries)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/taskinstance.py#L644-L650
def ready_for_retry(self): """ """ return (self.state == State.UP_FOR_RETRY and self.next_retry_datetime() < timezone.utcnow())
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/bigquery_hook.py#L855-L921
def run_extract( # noqa self, source_project_dataset_table, destination_cloud_storage_uris, compression='NONE', export_format='CSV', field_delimiter=',', print_header=True, labels=None): """ """ ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_mlengine_hook.py#L257-L273
def get_model(self, project_id, model_name): """ """ if not model_name: raise ValueError("Model name must be provided and " "it could not be an empty string") full_model_name = 'projects/{}/models/{}'.format( project_id, model...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/databricks_hook.py#L99-L154
def _do_api_call(self, endpoint_info, json): """ """ method, endpoint = endpoint_info url = 'https://{host}/{endpoint}'.format( host=self._parse_host(self.databricks_conn.host), endpoint=endpoint) if 'token' in self.databricks_conn.extra_dejson: ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/presto_hook.py#L67-L78
def _get_pretty_exception_message(e): """ """ if (hasattr(e, 'message') and 'errorName' in e.message and 'message' in e.message): return ('{name}: {message}'.format( name=e.message['errorName'], message=e.me...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_vision_hook.py#L106-L115
def get_conn(self): """ """ if not self._client: self._client = ProductSearchClient(credentials=self._get_credentials()) return self._client
https://github.com/soimort/you-get/blob/b746ac01c9f39de94cac2d56f665285b0523b974/src/you_get/extractors/veoh.py#L19-L33
def veoh_download_by_id(item_id, output_dir = '.', merge = False, info_only = False, **kwargs): """""" webpage_url = 'http://www.veoh.com/m/watch.php?v={item_id}&quality=1'.format(item_id = item_id) #grab download URL a = get_content(webpage_url, decoded=True) url = match1(a, r'<source src="(.*?)\"...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/jobs.py#L1282-L1322
def _enqueue_task_instances_with_queued_state(self, simple_dag_bag, simple_task_instances): """ """ TI = models.TaskInstance # actually enqueue them for simple_task_instance in simple_task_instances: simple_da...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/www/api/experimental/endpoints.py#L175-L191
def dag_paused(dag_id, paused): """""" DagModel = models.DagModel with create_session() as session: orm_dag = ( session.query(DagModel) .filter(DagModel.dag_id == dag_id).first() ) if paused == 'true': orm_dag.is_paused = True else:...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/pinot_hook.py#L66-L76
def get_records(self, sql): """ """ with self.get_conn() as cur: cur.execute(sql) return cur.fetchall()
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/sensors/bash_sensor.py#L60-L91
def poke(self, context): """ """ bash_command = self.bash_command self.log.info("Tmp dir root location: \n %s", gettempdir()) with TemporaryDirectory(prefix='airflowtmp') as tmp_dir: with NamedTemporaryFile(dir=tmp_dir, prefix=self.task_id) as f: ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/www/security.py#L268-L286
def has_access(self, permission, view_name, user=None): """ """ if not user: user = g.user if user.is_anonymous: return self.is_item_public(permission, view_name) return self._has_view_access(user, permission, view_name)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/timezone.py#L82-L95
def convert_to_utc(value): """ """ if not value: return value if not is_localized(value): value = pendulum.instance(value, TIMEZONE) return value.astimezone(utc)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/oracle_hook.py#L117-L182
def insert_rows(self, table, rows, target_fields=None, commit_every=1000): """ """ if target_fields: target_fields = ', '.join(target_fields) target_fields = '({})'.format(target_fields) else: target_fields = '' conn = self.get_conn() ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/datastore_hook.py#L123-L152
def lookup(self, keys, read_consistency=None, transaction=None): """ """ conn = self.get_conn() body = {'keys': keys} if read_consistency: body['readConsistency'] = read_consistency if transaction: body['transaction'] = transaction ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/executors/base_executor.py#L160-L179
def get_event_buffer(self, dag_ids=None): """ """ cleared_events = dict() if dag_ids is None: cleared_events = self.event_buffer self.event_buffer = dict() else: for key in list(self.event_buffer.keys()): dag_id, _, _, ...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/distribution_layer.py#L834-L855
def new(params, event_shape=(), validate_args=False, name=None): """""" with tf.compat.v1.name_scope(name, 'IndependentLogistic', [params, event_shape]): params = tf.convert_to_tensor(value=params, name='params') event_shape = dist_util.expand_to_vector( tf...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_spanner_hook.py#L136-L160
def update_instance(self, instance_id, configuration_name, node_count, display_name, project_id=None): """ """ return self._apply_to_instance(project_id, instance_id, configuration_name, node_count, display_name, lambda x: x...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/email.py#L36-L50
def send_email(to, subject, html_content, files=None, dryrun=False, cc=None, bcc=None, mime_subtype='mixed', mime_charset='utf-8', **kwargs): """ """ path, attr = configuration.conf.get('email', 'EMAIL_BACKEND').rsplit('.', 1) module = importlib.import_module(path) ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/http_hook.py#L133-L147
def check_response(self, response): """ """ try: response.raise_for_status() except requests.exceptions.HTTPError: self.log.error("HTTP error: %s", response.reason) if self.method not in ['GET', 'HEAD']: self.log.error(response...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/dag_processing.py#L779-L787
def _exit_gracefully(self, signum, frame): """ """ self.log.info("Exiting gracefully upon receiving signal %s", signum) self.terminate() self.end() self.log.debug("Finished terminating DAG processors.") sys.exit(os.EX_OK)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/www/api/experimental/endpoints.py#L98-L109
def delete_dag(dag_id): """ """ try: count = delete.delete_dag(dag_id) except AirflowException as err: _log.error(err) response = jsonify(error="{}".format(err)) response.status_code = err.status_code return response return jsonify(message="Removed {} rec...
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/models/squeezenet.py#L117-L129
def squeezenet1_1(pretrained=False, **kwargs): """ model = SqueezeNet(version=1.1, **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['squeezenet1_1'])) return model
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/api/common/experimental/pool.py#L26-L35
def get_pool(name, session=None): """""" if not (name and name.strip()): raise AirflowBadRequest("Pool name shouldn't be empty") pool = session.query(Pool).filter_by(pool=name).first() if pool is None: raise PoolNotFound("Pool '%s' doesn't exist" % name) return pool
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/math/custom_gradient.py#L39-L133
def custom_gradient(fx, gx, x, fx_gx_manually_stopped=False, name=None): """ """ def maybe_stop(x): if fx_gx_manually_stopped: return x return tf.stop_gradient(x) with tf.compat.v1.name_scope(name, 'custom_gradient', [fx, gx, x]): fx = tf.convert_to_tensor(value=fx, name='fx') # We don't ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/mongo_hook.py#L263-L279
def delete_one(self, mongo_collection, filter_doc, mongo_db=None, **kwargs): """ """ collection = self.get_collection(mongo_collection, mongo_db=mongo_db) return collection.delete_one(filter_doc, **kwargs)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/mongo_hook.py#L93-L102
def get_collection(self, mongo_collection, mongo_db=None): """ """ mongo_db = mongo_db if mongo_db is not None else self.connection.schema mongo_conn = self.get_conn() return mongo_conn.get_database(mongo_db).get_collection(mongo_collection)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/pinot_hook.py#L78-L88
def get_first(self, sql): """ """ with self.get_conn() as cur: cur.execute(sql) return cur.fetchone()
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/fun_mcmc/fun_mcmc_lib.py#L299-L345
def metropolis_hastings_step(current_state: State, proposed_state: State, energy_change: FloatTensor, seed=None) -> Tuple[State, tf.Tensor, tf.Tensor]: """ """ flat_current = tf.nest.flatten(current_state) flat_proposed = nes...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/kubernetes/pod_generator.py#L67-L73
def add_volume(self, volume): """ """ self._add_volume(name=volume.name, configs=volume.configs)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/datastore_hook.py#L154-L168
def rollback(self, transaction): """ """ conn = self.get_conn() conn.projects().rollback( projectId=self.project_id, body={'transaction': transaction} ).execute(num_retries=self.num_retries)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/aws_sqs_hook.py#L50-L71
def send_message(self, queue_url, message_body, delay_seconds=0, message_attributes=None): """ """ return self.get_conn().send_message(QueueUrl=queue_url, MessageBody=message_body, DelaySeconds=delay...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/postgres_hook.py#L63-L83
def copy_expert(self, sql, filename, open=open): """ """ if not os.path.isfile(filename): with open(filename, 'w'): pass with open(filename, 'r+') as f: with closing(self.get_conn()) as conn: with closing(conn.cursor()) as...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/layers/distribution_layer.py#L1698-L1703
def params_size(num_components, event_shape=(), name=None): """""" return MixtureSameFamily.params_size( num_components, IndependentLogistic.params_size(event_shape, name=name), name=name)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/S3_hook.py#L316-L350
def load_file(self, filename, key, bucket_name=None, replace=False, encrypt=False): """ """ if not bucket_name: (bucket_name, key) = self.parse_s3_url(key) if not replace and s...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/docs/exts/docroles.py#L58-L88
def template_field_role(app, typ, rawtext, text, lineno, inliner, options={}, content=[]): """ """ text = utils.unescape(text) try: template_fields = get_template_field(app.env, text) except RoleException as e: msg = inliner.reporter.error("invalid class name %s \n%s" % (text, ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/redis_hook.py#L45-L66
def get_conn(self): """ """ conn = self.get_connection(self.redis_conn_id) self.host = conn.host self.port = conn.port self.password = None if str(conn.password).lower() in ['none', 'false', ''] else conn.password self.db = conn.extra_dejson.get('db', Non...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/bijectors/categorical_to_discrete.py#L127-L154
def _maybe_check_valid_map_values(map_values, validate_args): """""" assertions = [] message = 'Rank of map_values must be 1.' if tensorshape_util.rank(map_values.shape) is not None: if tensorshape_util.rank(map_values.shape) != 1: raise ValueError(message) elif validate_args: assertions.append...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/xcom.py#L88-L136
def set( cls, key, value, execution_date, task_id, dag_id, session=None): """ """ session.expunge_all() enable_pickling = configuration.getboolean('core', 'enable_xcom_pickling') if enab...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/settings.py#L220-L235
def prepare_classpath(): """ """ if DAGS_FOLDER not in sys.path: sys.path.append(DAGS_FOLDER) # Add ./config/ for loading custom log parsers etc, or # airflow_local_settings etc. config_path = os.path.join(AIRFLOW_HOME, 'config') if config_path not in sys.path: sys.pat...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/spark_submit_hook.py#L322-L376
def submit(self, application="", **kwargs): """ """ spark_submit_cmd = self._build_spark_submit_command(application) if hasattr(self, '_env'): env = os.environ.copy() env.update(self._env) kwargs["env"] = env self._submit_sp = subpro...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/mixture.py#L497-L502
def _cat_probs(self, log_probs): """""" which_softmax = tf.nn.log_softmax if log_probs else tf.nn.softmax cat_probs = which_softmax(self.cat.logits) cat_probs = tf.unstack(cat_probs, num=self.num_components, axis=-1) return cat_probs
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/api/common/experimental/mark_tasks.py#L188-L207
def _set_dag_run_state(dag_id, execution_date, state, session=None): """ """ DR = DagRun dr = session.query(DR).filter( DR.dag_id == dag_id, DR.execution_date == execution_date ).one() dr.state = state if state == State.RUNNING: dr.start_date = timezone.utcnow() ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/kubernetes/pod_launcher.py#L73-L92
def run_pod(self, pod, startup_timeout=120, get_logs=True): # type: (Pod, int, bool) -> Tuple[State, Optional[str]] """ """ resp = self.run_pod_async(pod) curr_time = dt.now() if resp.status.start_time is None: while self.pod_not_started(pod): ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/salesforce_hook.py#L95-L108
def describe_object(self, obj): """ """ conn = self.get_conn() return conn.__getattr__(obj).describe()
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/spark_submit_hook.py#L431-L446
def _process_spark_status_log(self, itr): """ """ # Consume the iterator for line in itr: line = line.strip() # Check if the log line is about the driver status and extract the status. if "driverState" in line: self._driver_st...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/dag_processing.py#L1230-L1262
def _find_zombies(self, session): """ """ now = timezone.utcnow() zombies = [] if (now - self._last_zombie_query_time).total_seconds() \ > self._zombie_query_interval: # to avoid circular imports from airflow.jobs import LocalTaskJ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/hooks/oracle_hook.py#L184-L231
def bulk_insert_rows(self, table, rows, target_fields=None, commit_every=5000): """ """ if not rows: raise ValueError("parameter rows could not be None or empty iterable") conn = self.get_conn() cursor = conn.cursor() values_base = target_fields if ta...
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/utils.py#L6-L87
def make_grid(tensor, nrow=8, padding=2, normalize=False, range=None, scale_each=False, pad_value=0): """ """ if not (torch.is_tensor(tensor) or (isinstance(tensor, list) and all(torch.is_tensor(t) for t in tensor))): raise TypeError('tensor or list of tensors expected, go...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/cli_action_loggers.py#L72-L86
def on_post_execution(**kwargs): """ """ logging.debug("Calling callbacks: %s", __post_exec_callbacks) for cb in __post_exec_callbacks: try: cb(**kwargs) except Exception: logging.exception('Failed on post-execution callback using %s', cb)
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/imap_hook.py#L49-L66
def has_mail_attachment(self, name, mail_folder='INBOX', check_regex=False): """ """ mail_attachments = self._retrieve_mails_attachments_by_name(name, mail_folder, ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/helpers.py#L121-L128
def chunks(items, chunk_size): """ """ if chunk_size <= 0: raise ValueError('Chunk size must be a positive integer') for i in range(0, len(items), chunk_size): yield items[i:i + chunk_size]
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/ftp_hook.py#L81-L91
def get_conn(self): """ """ if self.conn is None: params = self.get_connection(self.ftp_conn_id) pasv = params.extra_dejson.get("passive", True) self.conn = ftplib.FTP(params.host, params.login, params.password) self.conn.set_pasv(pasv) ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_api_base_hook.py#L82-L129
def _get_credentials(self): """ """ key_path = self._get_field('key_path', False) keyfile_dict = self._get_field('keyfile_dict', False) scope = self._get_field('scope', None) if scope: scopes = [s.strip() for s in scope.split(',')] else: ...
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/functional.py#L184-L209
def normalize(tensor, mean, std, inplace=False): """ """ if not _is_tensor_image(tensor): raise TypeError('tensor is not a torch image.') if not inplace: tensor = tensor.clone() mean = torch.as_tensor(mean, dtype=torch.float32, device=tensor.device) std = torch.as_tensor(std, d...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/dag.py#L64-L75
def get_last_dagrun(dag_id, session, include_externally_triggered=False): """ """ DR = DagRun query = session.query(DR).filter(DR.dag_id == dag_id) if not include_externally_triggered: query = query.filter(DR.external_trigger == False) # noqa query = query.order_by(DR.execution_dat...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/sample_stats.py#L212-L281
def cholesky_covariance(x, sample_axis=0, keepdims=False, name=None): """ """ with tf.compat.v1.name_scope( name, 'cholesky_covariance', values=[x, sample_axis]): sample_axis = tf.convert_to_tensor(value=sample_axis, dtype=tf.int32) cov = covariance( x, sample_axis=sample_axis, event_axis=-1...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/discord_webhook_hook.py#L126-L140
def execute(self): """ """ proxies = {} if self.proxy: # we only need https proxy for Discord proxies = {'https': self.proxy} discord_payload = self._build_discord_payload() self.run(endpoint=self.webhook_endpoint, data=...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/bigquery_hook.py#L124-L147
def table_exists(self, project_id, dataset_id, table_id): """ """ service = self.get_service() try: service.tables().get( projectId=project_id, datasetId=dataset_id, tableId=table_id).execute(num_retries=self.num_retries) r...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/optimizer/linesearch/hager_zhang.py#L657-L662
def _to_str(x): """""" x = tf.convert_to_tensor(value=x) if x.dtype == tf.bool: return tf.where(x, tf.fill(x.shape, 'True'), tf.fill(x.shape, 'False')) return x
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/helpers.py#L243-L289
def reap_process_group(pid, log, sig=signal.SIGTERM, timeout=DEFAULT_TIME_TO_WAIT_AFTER_SIGTERM): """ """ def on_terminate(p): log.info("Process %s (%s) terminated with exit code %s", p, p.pid, p.returncode) if pid == os.getpid(): raise RuntimeError("I refus...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/slack_webhook_hook.py#L80-L97
def _get_token(self, token, http_conn_id): """ """ if token: return token elif http_conn_id: conn = self.get_connection(http_conn_id) extra = conn.extra_dejson return extra.get('webhook_token', '') else: raise A...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/bigquery_hook.py#L1298-L1339
def cancel_query(self): """ """ jobs = self.service.jobs() if (self.running_job_id and not self.poll_job_complete(self.running_job_id)): self.log.info('Attempting to cancel job : %s, %s', self.project_id, self.running_job_id)...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/vector_diffeomixture.py#L776-L811
def maybe_check_quadrature_param(param, name, validate_args): """""" with tf.name_scope("check_" + name): assertions = [] if tensorshape_util.rank(param.shape) is not None: if tensorshape_util.rank(param.shape) == 0: raise ValueError("Mixing params must be a (batch of) vector; " ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/cassandra_hook.py#L179-L200
def record_exists(self, table, keys): """ """ keyspace = self.keyspace if '.' in table: keyspace, table = table.split('.', 1) ks = " AND ".join("{}=%({})s".format(key, key) for key in keys.keys()) cql = "SELECT * FROM {keyspace}.{table} WHERE {keys}"....
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/stats/sample_stats.py#L465-L549
def correlation(x, y=None, sample_axis=0, event_axis=-1, keepdims=False, name=None): """ """ with tf.compat.v1.name_scope( name, 'correlation', values=[x, y, event_axis, sample_axis]): # Corr[X, Y] = Cov[X, Y] / (Stddev[X] ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/log/wasb_task_handler.py#L135-L152
def wasb_read(self, remote_log_location, return_error=False): """ """ try: return self.hook.read_file(self.wasb_container, remote_log_location) except AzureHttpError: msg = 'Could not read logs from {}'.format(remote_log_location) self.log.exc...
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/functional.py#L577-L594
def adjust_saturation(img, saturation_factor): """ """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) enhancer = ImageEnhance.Color(img) img = enhancer.enhance(saturation_factor) return img
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/dag_processing.py#L637-L643
def terminate(self): """ """ self.log.info("Sending termination message to manager.") self._child_signal_conn.send(DagParsingSignal.TERMINATE_MANAGER)
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/models/googlenet.py#L18-L47
def googlenet(pretrained=False, **kwargs): """ if pretrained: if 'transform_input' not in kwargs: kwargs['transform_input'] = True if 'aux_logits' not in kwargs: kwargs['aux_logits'] = False if kwargs['aux_logits']: warnings.warn('auxiliary heads ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/operators/postgres_to_gcs_operator.py#L207-L224
def convert_types(cls, value): """ """ if type(value) in (datetime.datetime, datetime.date): return time.mktime(value.timetuple()) elif type(value) == datetime.time: formated_time = time.strptime(str(value), "%H:%M:%S") return datetime.timedel...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/mcmc/sample_halton_sequence.py#L269-L301
def _get_permutations(num_results, dims, seed=None): """ """ sample_range = tf.range(num_results) stream = distributions.SeedStream(seed, salt='MCMCSampleHaltonSequence3') def generate_one(d): seed = stream() fn = lambda _: tf.random.shuffle(tf.range(d), seed=seed) return tf.map_fn( fn, ...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/experimental/no_u_turn_sampler/logistic_regression.py#L67-L85
def covertype(): """""" import sklearn.datasets # pylint: disable=g-import-not-at-top data = sklearn.datasets.covtype.fetch_covtype() features = data.data labels = data.target # Normalize features and append a column of ones for the intercept. features -= features.mean(0) features /= features.std(0) ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcs_hook.py#L208-L221
def exists(self, bucket_name, object_name): """ """ client = self.get_conn() bucket = client.get_bucket(bucket_name=bucket_name) blob = bucket.blob(blob_name=object_name) return blob.exists()
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/log/file_processor_handler.py#L129-L149
def _init_file(self, filename): """ """ relative_path = self._render_filename(filename) full_path = os.path.join(self._get_log_directory(), relative_path) directory = os.path.dirname(full_path) if not os.path.exists(directory): try: o...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/sensors/hdfs_sensor.py#L30-L46
def poke(self, context): """ """ sb = self.hook(self.hdfs_conn_id).get_conn() self.log.info( 'Poking for %s to be a directory with files matching %s', self.filepath, self.regex.pattern ) result = [f for f in sb.ls([self.filepath], include_toplevel=Fal...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/sagemaker_hook.py#L368-L396
def create_tuning_job(self, config, wait_for_completion=True, check_interval=30, max_ingestion_time=None): """ """ self.check_tuning_config(config) response = self.get_conn().create_hyper_parameter_tuning_job(**config) if wait_for_completion: ...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/__init__.py#L32-L65
def _ensure_tf_install(): # pylint: disable=g-statement-before-imports """ """ try: import tensorflow as tf except ImportError: # Print more informative error message, then reraise. print("\n\nFailed to import TensorFlow. Please note that TensorFlow is not " "installed by default when you...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/models/dagbag.py#L305-L339
def bag_dag(self, dag, parent_dag, root_dag): """ """ dag.test_cycle() # throws if a task cycle is found dag.resolve_template_files() dag.last_loaded = timezone.utcnow() for task in dag.tasks: settings.policy(task) subdags = dag.subdags ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/contrib/hooks/gcp_compute_hook.py#L223-L245
def get_instance_group_manager(self, zone, resource_id, project_id=None): """ """ response = self.get_conn().instanceGroupManagers().get( project=project_id, zone=zone, instanceGroupManager=resource_id ).execute(num_retries=self.num_retries) ...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/dag_processing.py#L262-L272
def get_dag(self, dag_id): """ """ if dag_id not in self.dag_id_to_simple_dag: raise AirflowException("Unknown DAG ID {}".format(dag_id)) return self.dag_id_to_simple_dag[dag_id]
https://github.com/pytorch/vision/blob/3afcf3cd49661c466c75ea536b0b2a7ff57f9a05/torchvision/transforms/functional.py#L597-L641
def adjust_hue(img, hue_factor): """ """ if not(-0.5 <= hue_factor <= 0.5): raise ValueError('hue_factor is not in [-0.5, 0.5].'.format(hue_factor)) if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) input_mode = img.mode if input_mo...
https://github.com/tensorflow/probability/blob/e87fe34111d68c35db0f9eeb4935f1ece9e1a8f5/tensorflow_probability/python/distributions/vector_diffeomixture.py#L882-L896
def interpolate_scale(grid, scale): """""" if len(scale) != 2: raise NotImplementedError("Currently only bimixtures are supported; " "len(scale)={} is not 2.".format(len(scale))) deg = tf.compat.dimension_value( tensorshape_util.with_rank_at_least(grid.shape, 1)[-1]) if d...
https://github.com/apache/airflow/blob/b69c686ad8a0c89b9136bb4b31767257eb7b2597/airflow/utils/dag_processing.py#L900-L918
def _refresh_dag_dir(self): """ """ elapsed_time_since_refresh = (timezone.utcnow() - self.last_dag_dir_refresh_time).total_seconds() if elapsed_time_since_refresh > self.dag_dir_list_interval: # Build up a list of Python files t...