Unnamed: 0
int64
0
2.93k
code
stringlengths
101
62.2k
docs
stringlengths
51
10.7k
doc_len
int64
4
1.74k
words
int64
4
4.82k
lang
stringclasses
1 value
prompt
stringlengths
320
71.2k
300
def test_type_eventpage_two_indexes(self): self.make_event_section("Other events") self.assertEqual( self.get_best_root({"page_type": "tests.EventPage"}), self.home_page )
The chooser should start at the home page, as there are two EventIndexes with EventPages.
15
9
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_type_eventpage_two_indexes(self): self.make_event_section("Other events") self.assertEqual( self.get_best_root({"page_type": "tests.EventPage"}), self.home_page ) ``` ###Assistant : The chooser should start at the home page, as there are two EventIndexes with EventPages.
301
def parse(self, filename, constraint): # type: (str, bool) -> Iterator[ParsedLine] yield from self._parse_and_recurse(filename, constraint)
Parse a given file, yielding parsed lines.
7
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def parse(self, filename, constraint): # type: (str, bool) -> Iterator[ParsedLine] yield from self._parse_and_recurse(filename, constraint) ``` ###Assistant : Parse a given file, yielding parsed lines.
302
def sparse_bincount(inputs, depth, binary_output, dtype, count_weights=None): result = tf.sparse.bincount( inputs, weights=count_weights, minlength=depth, maxlength=depth, axis=-1, binary_output=binary_output, ) result = tf.cast(result, dtype) if inputs.shape.rank == 1: output_shape = (depth,) else: batch_size = tf.shape(result)[0] output_shape = (batch_size, depth) result = tf.SparseTensor( indices=result.indices, values=result.values, dense_shape=output_shape ) return result
Apply binary or count encoding to an input and return a sparse tensor.
13
44
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def sparse_bincount(inputs, depth, binary_output, dtype, count_weights=None): result = tf.sparse.bincount( inputs, weights=count_weights, minlength=depth, maxlength=depth, axis=-1, binary_output=binary_output, ) result = tf.cast(result, dtype) if inputs.shape.rank == 1: output_shape = (depth,) else: batch_size = tf.shape(result)[0] output_shape = (batch_size, depth) result = tf.SparseTensor( indices=result.indices, values=result.values, dense_shape=output_shape ) return result ``` ###Assistant : Apply binary or count encoding to an input and return a sparse tensor.
303
def unmarshal(self, serialized_data): logger.debug("data type: %s", type(serialized_data)) try: retval = self._unmarshal(serialized_data) except Exception as err: msg = f"Error unserializing data for type {type(serialized_data)}: {str(err)}" raise FaceswapError(msg) from err logger.debug("returned data type: %s", type(retval)) return retval
Unserialize data to its original object type Parameters ---------- serialized_data: varies Data in serializer format that is to be unmarshalled to its original object Returns ------- data: varies The data in a python object format Example ------ >>> serializer = get_serializer('json') >>> json_data = <json object> >>> data = serializer.unmarshal(json_data)
50
35
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def unmarshal(self, serialized_data): logger.debug("data type: %s", type(serialized_data)) try: retval = self._unmarshal(serialized_data) except Exception as err: msg = f"Error unserializing data for type {type(serialized_data)}: {str(err)}" raise FaceswapError(msg) from err logger.debug("returned data type: %s", type(retval)) return retval ``` ###Assistant : Unserialize data to its original object type Parameters ---------- serialized_data: varies Data in serializer format that is to be unmarshalled to its original object Returns ------- data: varies The data in a python object format Example ------ >>> serializer = get_serializer('json') >>> json_data = <json object> >>> data = serializer.unmarshal(json_data)
304
def copyDataFiles(): for included_datafile in getIncludedDataFiles(): # TODO: directories should be resolved to files. if ( not isinstance(included_datafile, (IncludedDataFile)) or included_datafile.needsCopy() ): _handleDataFile( included_datafile, )
Copy the data files needed for standalone distribution. Notes: This is for data files only, not DLLs or even extension modules, those must be registered as entry points, and would not go through necessary handling if provided like this.
39
25
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def copyDataFiles(): for included_datafile in getIncludedDataFiles(): # TODO: directories should be resolved to files. if ( not isinstance(included_datafile, (IncludedDataFile)) or included_datafile.needsCopy() ): _handleDataFile( included_datafile, ) ``` ###Assistant : Copy the data files needed for standalone distribution. Notes: This is for data files only, not DLLs or even extension modules, those must be registered as entry points, and would not go through necessary handling if provided like this.
305
def toggler(self, attr): if attr not in self._options: raise KeyError("No such option: %s" % attr) o = self._options[attr] if o.typespec != bool: raise ValueError("Toggler can only be used with boolean options")
Generate a toggler for a boolean attribute. This returns a callable that takes no arguments.
15
31
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def toggler(self, attr): if attr not in self._options: raise KeyError("No such option: %s" % attr) o = self._options[attr] if o.typespec != bool: raise ValueError("Toggler can only be used with boolean options") ``` ###Assistant : Generate a toggler for a boolean attribute. This returns a callable that takes no arguments.
306
def disable_terminal_wrapping(monkeypatch): monkeypatch.setattr( "prefect.cli.profile.console", rich.console.Console(soft_wrap=True) )
Sometimes, line wrapping makes it hard to make deterministic assertions about the output of a CLI command. Wrapping can be disabled by using this fixture.
25
6
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def disable_terminal_wrapping(monkeypatch): monkeypatch.setattr( "prefect.cli.profile.console", rich.console.Console(soft_wrap=True) ) ``` ###Assistant : Sometimes, line wrapping makes it hard to make deterministic assertions about the output of a CLI command. Wrapping can be disabled by using this fixture.
307
def __add__(self, other): rank = (self.rank() + other) % self.cardinality rv = self.unrank_lex(self.size, rank) rv._rank = rank return rv
Return permutation that is other higher in rank than self. The rank is the lexicographical rank, with the identity permutation having rank of 0. Examples ======== >>> from sympy.combinatorics import Permutation >>> I = Permutation([0, 1, 2, 3]) >>> a = Permutation([2, 1, 3, 0]) >>> I + a.rank() == a True See Also ======== __sub__, inversion_vector
57
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def __add__(self, other): rank = (self.rank() + other) % self.cardinality rv = self.unrank_lex(self.size, rank) rv._rank = rank return rv ``` ###Assistant : Return permutation that is other higher in rank than self. The rank is the lexicographical rank, with the identity permutation having rank of 0. Examples ======== >>> from sympy.combinatorics import Permutation >>> I = Permutation([0, 1, 2, 3]) >>> a = Permutation([2, 1, 3, 0]) >>> I + a.rank() == a True See Also ======== __sub__, inversion_vector
308
def test_set_presence_from_syncing_not_set(self): user_id = "@test:server" status_msg = "I'm here!" self._set_presencestate_with_status_msg( user_id, PresenceState.UNAVAILABLE, status_msg ) self.get_success( self.presence_handler.user_syncing(user_id, False, PresenceState.ONLINE) ) state = self.get_success( self.presence_handler.get_state(UserID.from_string(user_id)) ) # we should still be unavailable self.assertEqual(state.state, PresenceState.UNAVAILABLE) # and status message should still be the same self.assertEqual(state.status_msg, status_msg)
Test that presence is not set by syncing if affect_presence is false
12
43
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_set_presence_from_syncing_not_set(self): user_id = "@test:server" status_msg = "I'm here!" self._set_presencestate_with_status_msg( user_id, PresenceState.UNAVAILABLE, status_msg ) self.get_success( self.presence_handler.user_syncing(user_id, False, PresenceState.ONLINE) ) state = self.get_success( self.presence_handler.get_state(UserID.from_string(user_id)) ) # we should still be unavailable self.assertEqual(state.state, PresenceState.UNAVAILABLE) # and status message should still be the same self.assertEqual(state.status_msg, status_msg) ``` ###Assistant : Test that presence is not set by syncing if affect_presence is false
309
def test_stringy_integers(self): input = { "a": "100", "b": { "foo": 99, "bar": "-98", }, "d": "0999", } output = copy_and_fixup_power_levels_contents(input) expected_output = { "a": 100, "b": { "foo": 99, "bar": -98, }, "d": 999, } self.assertEqual(output, expected_output)
String representations of decimal integers are converted to integers.
9
37
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_stringy_integers(self): input = { "a": "100", "b": { "foo": 99, "bar": "-98", }, "d": "0999", } output = copy_and_fixup_power_levels_contents(input) expected_output = { "a": 100, "b": { "foo": 99, "bar": -98, }, "d": 999, } self.assertEqual(output, expected_output) ``` ###Assistant : String representations of decimal integers are converted to integers.
310
def get_ec_matching_query(bank_account, company, amount_condition): # get matching Expense Claim query mode_of_payments = [ x["parent"] for x in frappe.db.get_all( "Mode of Payment Account", filters={"default_account": bank_account}, fields=["parent"] ) ] mode_of_payments = "('" + "', '".join(mode_of_payments) + "' )" company_currency = get_company_currency(company) return f
SELECT ( CASE WHEN employee = %(party)s THEN 1 ELSE 0 END + 1 ) AS rank, 'Expense Claim' as doctype, name, total_sanctioned_amount as paid_amount, '' as reference_no, '' as reference_date, employee as party, 'Employee' as party_type, posting_date, '{company_currency}' as currency FROM `tabExpense Claim` WHERE total_sanctioned_amount {amount_condition} %(amount)s AND docstatus = 1 AND is_paid = 1 AND ifnull(clearance_date, '') = "" AND mode_of_payment in {mode_of_payments}
65
41
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_ec_matching_query(bank_account, company, amount_condition): # get matching Expense Claim query mode_of_payments = [ x["parent"] for x in frappe.db.get_all( "Mode of Payment Account", filters={"default_account": bank_account}, fields=["parent"] ) ] mode_of_payments = "('" + "', '".join(mode_of_payments) + "' )" company_currency = get_company_currency(company) return f ``` ###Assistant : SELECT ( CASE WHEN employee = %(party)s THEN 1 ELSE 0 END + 1 ) AS rank, 'Expense Claim' as doctype, name, total_sanctioned_amount as paid_amount, '' as reference_no, '' as reference_date, employee as party, 'Employee' as party_type, posting_date, '{company_currency}' as currency FROM `tabExpense Claim` WHERE total_sanctioned_amount {amount_condition} %(amount)s AND docstatus = 1 AND is_paid = 1 AND ifnull(clearance_date, '') = "" AND mode_of_payment in {mode_of_payments}
311
def run_exec_plan(cls, plan, index_cols, dtypes, columns): omniSession = DbWorker() # First step is to make sure all partitions are in HDK. frames = plan.collect_frames() for frame in frames: if frame._partitions.size != 1: raise NotImplementedError( "HdkOnNative engine doesn't suport partitioned frames" ) for p in frame._partitions.flatten(): if p.frame_id is None: obj = p.get() if isinstance(obj, (pandas.DataFrame, pandas.Series)): p.frame_id = omniSession.import_pandas_dataframe(obj) else: assert isinstance(obj, pyarrow.Table) p.frame_id = omniSession.import_arrow_table(obj) calcite_plan = CalciteBuilder().build(plan) calcite_json = CalciteSerializer().serialize(calcite_plan) cmd_prefix = "execute relalg " if DoUseCalcite.get(): cmd_prefix = "execute calcite " at = omniSession.executeRA(cmd_prefix + calcite_json) res = np.empty((1, 1), dtype=np.dtype(object)) # workaround for https://github.com/modin-project/modin/issues/1851 if DoUseCalcite.get(): at = at.rename_columns(["F_" + str(c) for c in columns]) res[0][0] = cls._partition_class.put_arrow(at) return res
Run execution plan in HDK storage format to materialize frame. Parameters ---------- plan : DFAlgNode A root of an execution plan tree. index_cols : list of str A list of index columns. dtypes : pandas.Index Column data types. columns : list of str A frame column names. Returns ------- np.array Created frame's partitions.
53
114
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def run_exec_plan(cls, plan, index_cols, dtypes, columns): omniSession = DbWorker() # First step is to make sure all partitions are in HDK. frames = plan.collect_frames() for frame in frames: if frame._partitions.size != 1: raise NotImplementedError( "HdkOnNative engine doesn't suport partitioned frames" ) for p in frame._partitions.flatten(): if p.frame_id is None: obj = p.get() if isinstance(obj, (pandas.DataFrame, pandas.Series)): p.frame_id = omniSession.import_pandas_dataframe(obj) else: assert isinstance(obj, pyarrow.Table) p.frame_id = omniSession.import_arrow_table(obj) calcite_plan = CalciteBuilder().build(plan) calcite_json = CalciteSerializer().serialize(calcite_plan) cmd_prefix = "execute relalg " if DoUseCalcite.get(): cmd_prefix = "execute calcite " at = omniSession.executeRA(cmd_prefix + calcite_json) res = np.empty((1, 1), dtype=np.dtype(object)) # workaround for https://github.com/modin-project/modin/issues/1851 if DoUseCalcite.get(): at = at.rename_columns(["F_" + str(c) for c in columns]) res[0][0] = cls._partition_class.put_arrow(at) return res ``` ###Assistant : Run execution plan in HDK storage format to materialize frame. Parameters ---------- plan : DFAlgNode A root of an execution plan tree. index_cols : list of str A list of index columns. dtypes : pandas.Index Column data types. columns : list of str A frame column names. Returns ------- np.array Created frame's partitions.
312
def to_numeric_dtype(dtype): dtype = np.dtype(dtype) return np.dtype('int32') if dtype == np.dtype('bool') else dtype
Promotes a dtype into an numeric dtype, if it is not already one.
13
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def to_numeric_dtype(dtype): dtype = np.dtype(dtype) return np.dtype('int32') if dtype == np.dtype('bool') else dtype ``` ###Assistant : Promotes a dtype into an numeric dtype, if it is not already one.
313
def test_do_schedule_max_active_runs_task_removed(self, session, dag_maker): with dag_maker( dag_id='test_do_schedule_max_active_runs_task_removed', start_date=DEFAULT_DATE, schedule_interval='@once', max_active_runs=1, session=session, ): # Can't use EmptyOperator as that goes straight to success BashOperator(task_id='dummy1', bash_command='true') run1 = dag_maker.create_dagrun( run_type=DagRunType.SCHEDULED, execution_date=DEFAULT_DATE + timedelta(hours=1), state=State.RUNNING, ) self.scheduler_job = SchedulerJob(subdir=os.devnull) self.scheduler_job.executor = MockExecutor(do_update=False) self.scheduler_job.processor_agent = mock.MagicMock(spec=DagFileProcessorAgent) num_queued = self.scheduler_job._do_scheduling(session) assert num_queued == 1 session.flush() ti = run1.task_instances[0] ti.refresh_from_db(session=session) assert ti.state == State.QUEUED
Test that tasks in removed state don't count as actively running.
11
58
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_do_schedule_max_active_runs_task_removed(self, session, dag_maker): with dag_maker( dag_id='test_do_schedule_max_active_runs_task_removed', start_date=DEFAULT_DATE, schedule_interval='@once', max_active_runs=1, session=session, ): # Can't use EmptyOperator as that goes straight to success BashOperator(task_id='dummy1', bash_command='true') run1 = dag_maker.create_dagrun( run_type=DagRunType.SCHEDULED, execution_date=DEFAULT_DATE + timedelta(hours=1), state=State.RUNNING, ) self.scheduler_job = SchedulerJob(subdir=os.devnull) self.scheduler_job.executor = MockExecutor(do_update=False) self.scheduler_job.processor_agent = mock.MagicMock(spec=DagFileProcessorAgent) num_queued = self.scheduler_job._do_scheduling(session) assert num_queued == 1 session.flush() ti = run1.task_instances[0] ti.refresh_from_db(session=session) assert ti.state == State.QUEUED ``` ###Assistant : Test that tasks in removed state don't count as actively running.
314
def forward(self, xs, masks): if isinstance(self.embed, (Conv2dSubsampling, VGG2L)): xs, masks = self.embed(xs, masks) else: xs = self.embed(xs) xs, masks = self.encoders(xs, masks) if isinstance(xs, tuple): xs = xs[0] if self.normalize_before: xs = self.after_norm(xs) return xs, masks
Encode input sequence. :param torch.Tensor xs: input tensor :param torch.Tensor masks: input mask :return: position embedded tensor and mask :rtype Tuple[torch.Tensor, torch.Tensor]:
22
36
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def forward(self, xs, masks): if isinstance(self.embed, (Conv2dSubsampling, VGG2L)): xs, masks = self.embed(xs, masks) else: xs = self.embed(xs) xs, masks = self.encoders(xs, masks) if isinstance(xs, tuple): xs = xs[0] if self.normalize_before: xs = self.after_norm(xs) return xs, masks ``` ###Assistant : Encode input sequence. :param torch.Tensor xs: input tensor :param torch.Tensor masks: input mask :return: position embedded tensor and mask :rtype Tuple[torch.Tensor, torch.Tensor]:
315
def save_class(self): if gtff.REMEMBER_CONTEXTS: controllers[self.PATH] = self
Saves the current instance of the class to be loaded later
11
7
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def save_class(self): if gtff.REMEMBER_CONTEXTS: controllers[self.PATH] = self ``` ###Assistant : Saves the current instance of the class to be loaded later
316
def _decode_messages(self, messages): messages_len = len(messages) # if it was one message, then its old style if messages_len == 1: payload = salt.payload.loads(messages[0]) # 2 includes a header which says who should do it elif messages_len == 2: message_target = salt.utils.stringutils.to_str(messages[0]) if ( self.opts.get("__role") != "syndic" and message_target not in ("broadcast", self.hexid) ) or ( self.opts.get("__role") == "syndic" and message_target not in ("broadcast", "syndic") ): log.debug("Publish received for not this minion: %s", message_target) raise salt.ext.tornado.gen.Return(None) payload = salt.payload.loads(messages[1]) else: raise Exception( "Invalid number of messages ({}) in zeromq pubmessage from master".format( len(messages_len) ) ) # Yield control back to the caller. When the payload has been decoded, assign # the decoded payload to 'ret' and resume operation raise salt.ext.tornado.gen.Return(payload)
Take the zmq messages, decrypt/decode them into a payload :param list messages: A list of messages to be decoded
19
119
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _decode_messages(self, messages): messages_len = len(messages) # if it was one message, then its old style if messages_len == 1: payload = salt.payload.loads(messages[0]) # 2 includes a header which says who should do it elif messages_len == 2: message_target = salt.utils.stringutils.to_str(messages[0]) if ( self.opts.get("__role") != "syndic" and message_target not in ("broadcast", self.hexid) ) or ( self.opts.get("__role") == "syndic" and message_target not in ("broadcast", "syndic") ): log.debug("Publish received for not this minion: %s", message_target) raise salt.ext.tornado.gen.Return(None) payload = salt.payload.loads(messages[1]) else: raise Exception( "Invalid number of messages ({}) in zeromq pubmessage from master".format( len(messages_len) ) ) # Yield control back to the caller. When the payload has been decoded, assign # the decoded payload to 'ret' and resume operation raise salt.ext.tornado.gen.Return(payload) ``` ###Assistant : Take the zmq messages, decrypt/decode them into a payload :param list messages: A list of messages to be decoded
317
def test_get_release_wheel_url(): # This should be a commit for which wheels have already been built for # all platforms and python versions at # `s3://ray-wheels/releases/2.2.0/<commit>/`. test_commits = {"2.2.0": "b6af0887ee5f2e460202133791ad941a41f15beb"} for sys_platform in ["darwin", "linux", "win32"]: for py_version in ray_constants.RUNTIME_ENV_CONDA_PY_VERSIONS: for version, commit in test_commits.items(): if sys_platform == "win32" and py_version == (3, 6): # Windows wheels are not built for py3.6 anymore continue url = get_release_wheel_url(commit, sys_platform, version, py_version) assert requests.head(url).status_code == 200, url
Test the code that generates the filenames of the `release` branch wheels.
12
74
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_get_release_wheel_url(): # This should be a commit for which wheels have already been built for # all platforms and python versions at # `s3://ray-wheels/releases/2.2.0/<commit>/`. test_commits = {"2.2.0": "b6af0887ee5f2e460202133791ad941a41f15beb"} for sys_platform in ["darwin", "linux", "win32"]: for py_version in ray_constants.RUNTIME_ENV_CONDA_PY_VERSIONS: for version, commit in test_commits.items(): if sys_platform == "win32" and py_version == (3, 6): # Windows wheels are not built for py3.6 anymore continue url = get_release_wheel_url(commit, sys_platform, version, py_version) assert requests.head(url).status_code == 200, url ``` ###Assistant : Test the code that generates the filenames of the `release` branch wheels.
318
def test_keep_media_by_date(self) -> None: # timestamp before upload now_ms = self.clock.time_msec() server_and_media_id = self._create_media() self._access_media(server_and_media_id) channel = self.make_request( "POST", self.url + "?before_ts=" + str(now_ms), access_token=self.admin_user_tok, ) self.assertEqual(200, channel.code, msg=channel.json_body) self.assertEqual(0, channel.json_body["total"]) self._access_media(server_and_media_id) # timestamp after upload now_ms = self.clock.time_msec() channel = self.make_request( "POST", self.url + "?before_ts=" + str(now_ms), access_token=self.admin_user_tok, ) self.assertEqual(200, channel.code, msg=channel.json_body) self.assertEqual(1, channel.json_body["total"]) self.assertEqual( server_and_media_id.split("/")[1], channel.json_body["deleted_media"][0], ) self._access_media(server_and_media_id, False)
Tests that media is not deleted if it is newer than `before_ts`
12
61
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_keep_media_by_date(self) -> None: # timestamp before upload now_ms = self.clock.time_msec() server_and_media_id = self._create_media() self._access_media(server_and_media_id) channel = self.make_request( "POST", self.url + "?before_ts=" + str(now_ms), access_token=self.admin_user_tok, ) self.assertEqual(200, channel.code, msg=channel.json_body) self.assertEqual(0, channel.json_body["total"]) self._access_media(server_and_media_id) # timestamp after upload now_ms = self.clock.time_msec() channel = self.make_request( "POST", self.url + "?before_ts=" + str(now_ms), access_token=self.admin_user_tok, ) self.assertEqual(200, channel.code, msg=channel.json_body) self.assertEqual(1, channel.json_body["total"]) self.assertEqual( server_and_media_id.split("/")[1], channel.json_body["deleted_media"][0], ) self._access_media(server_and_media_id, False) ``` ###Assistant : Tests that media is not deleted if it is newer than `before_ts`
319
def test_fetch_openml_requires_pandas_in_future(monkeypatch): params = {"as_frame": False, "parser": "auto"} data_id = 1119 try: check_pandas_support("test_fetch_openml_requires_pandas") except ImportError: _monkey_patch_webbased_functions(monkeypatch, data_id, True) warn_msg = ( "From version 1.4, `parser='auto'` with `as_frame=False` will use pandas" ) with pytest.warns(FutureWarning, match=warn_msg): fetch_openml(data_id=data_id, **params) else: raise SkipTest("This test requires pandas to not be installed.") @pytest.mark.filterwarnings("ignore:Version 1 of dataset Australian is inactive") # TODO(1.4): remove this filterwarning decorator for `parser` @pytest.mark.filterwarnings("ignore:The default value of `parser` will change") @pytest.mark.parametrize( "params, err_msg", [ ( {"parser": "pandas"}, "Sparse ARFF datasets cannot be loaded with parser='pandas'", ), ( {"as_frame": True}, "Sparse ARFF datasets cannot be loaded with as_frame=True.", ), ( {"parser": "pandas", "as_frame": True}, "Sparse ARFF datasets cannot be loaded with as_frame=True.", ), ], )
Check that we raise a warning that pandas will be required in the future.
14
112
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_fetch_openml_requires_pandas_in_future(monkeypatch): params = {"as_frame": False, "parser": "auto"} data_id = 1119 try: check_pandas_support("test_fetch_openml_requires_pandas") except ImportError: _monkey_patch_webbased_functions(monkeypatch, data_id, True) warn_msg = ( "From version 1.4, `parser='auto'` with `as_frame=False` will use pandas" ) with pytest.warns(FutureWarning, match=warn_msg): fetch_openml(data_id=data_id, **params) else: raise SkipTest("This test requires pandas to not be installed.") @pytest.mark.filterwarnings("ignore:Version 1 of dataset Australian is inactive") # TODO(1.4): remove this filterwarning decorator for `parser` @pytest.mark.filterwarnings("ignore:The default value of `parser` will change") @pytest.mark.parametrize( "params, err_msg", [ ( {"parser": "pandas"}, "Sparse ARFF datasets cannot be loaded with parser='pandas'", ), ( {"as_frame": True}, "Sparse ARFF datasets cannot be loaded with as_frame=True.", ), ( {"parser": "pandas", "as_frame": True}, "Sparse ARFF datasets cannot be loaded with as_frame=True.", ), ], ) ``` ###Assistant : Check that we raise a warning that pandas will be required in the future.
320
def get_connection(self, url, proxies=None): proxy = select_proxy(url, proxies) if proxy: proxy = prepend_scheme_if_needed(proxy, "http") proxy_url = parse_url(proxy) if not proxy_url.host: raise InvalidProxyURL( "Please check proxy URL. It is malformed " "and could be missing the host." ) proxy_manager = self.proxy_manager_for(proxy) conn = proxy_manager.connection_from_url(url) else: # Only scheme should be lower case parsed = urlparse(url) url = parsed.geturl() conn = self.poolmanager.connection_from_url(url) return conn
Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of proxies used on this request. :rtype: urllib3.ConnectionPool
48
62
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_connection(self, url, proxies=None): proxy = select_proxy(url, proxies) if proxy: proxy = prepend_scheme_if_needed(proxy, "http") proxy_url = parse_url(proxy) if not proxy_url.host: raise InvalidProxyURL( "Please check proxy URL. It is malformed " "and could be missing the host." ) proxy_manager = self.proxy_manager_for(proxy) conn = proxy_manager.connection_from_url(url) else: # Only scheme should be lower case parsed = urlparse(url) url = parsed.geturl() conn = self.poolmanager.connection_from_url(url) return conn ``` ###Assistant : Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of proxies used on this request. :rtype: urllib3.ConnectionPool
321
def feature_engineering_expand_all(self, dataframe, period, **kwargs): dataframe["%-rsi-period"] = ta.RSI(dataframe, timeperiod=period) dataframe["%-mfi-period"] = ta.MFI(dataframe, timeperiod=period) dataframe["%-adx-period"] = ta.ADX(dataframe, timeperiod=period) dataframe["%-sma-period"] = ta.SMA(dataframe, timeperiod=period) dataframe["%-ema-period"] = ta.EMA(dataframe, timeperiod=period) bollinger = qtpylib.bollinger_bands( qtpylib.typical_price(dataframe), window=period, stds=2.2 ) dataframe["bb_lowerband-period"] = bollinger["lower"] dataframe["bb_middleband-period"] = bollinger["mid"] dataframe["bb_upperband-period"] = bollinger["upper"] dataframe["%-bb_width-period"] = ( dataframe["bb_upperband-period"] - dataframe["bb_lowerband-period"] ) / dataframe["bb_middleband-period"] dataframe["%-close-bb_lower-period"] = ( dataframe["close"] / dataframe["bb_lowerband-period"] ) dataframe["%-roc-period"] = ta.ROC(dataframe, timeperiod=period) dataframe["%-relative_volume-period"] = ( dataframe["volume"] / dataframe["volume"].rolling(period).mean() ) return dataframe
*Only functional with FreqAI enabled strategies* This function will automatically expand the defined features on the config defined `indicator_periods_candles`, `include_timeframes`, `include_shifted_candles`, and `include_corr_pairs`. In other words, a single feature defined in this function will automatically expand to a total of `indicator_periods_candles` * `include_timeframes` * `include_shifted_candles` * `include_corr_pairs` numbers of features added to the model. All features must be prepended with `%` to be recognized by FreqAI internals. More details on how these config defined parameters accelerate feature engineering in the documentation at: https://www.freqtrade.io/en/latest/freqai-parameter-table/#feature-parameters https://www.freqtrade.io/en/latest/freqai-feature-engineering/#defining-the-features :param df: strategy dataframe which will receive the features :param period: period of the indicator - usage example: dataframe["%-ema-period"] = ta.EMA(dataframe, timeperiod=period)
106
70
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def feature_engineering_expand_all(self, dataframe, period, **kwargs): dataframe["%-rsi-period"] = ta.RSI(dataframe, timeperiod=period) dataframe["%-mfi-period"] = ta.MFI(dataframe, timeperiod=period) dataframe["%-adx-period"] = ta.ADX(dataframe, timeperiod=period) dataframe["%-sma-period"] = ta.SMA(dataframe, timeperiod=period) dataframe["%-ema-period"] = ta.EMA(dataframe, timeperiod=period) bollinger = qtpylib.bollinger_bands( qtpylib.typical_price(dataframe), window=period, stds=2.2 ) dataframe["bb_lowerband-period"] = bollinger["lower"] dataframe["bb_middleband-period"] = bollinger["mid"] dataframe["bb_upperband-period"] = bollinger["upper"] dataframe["%-bb_width-period"] = ( dataframe["bb_upperband-period"] - dataframe["bb_lowerband-period"] ) / dataframe["bb_middleband-period"] dataframe["%-close-bb_lower-period"] = ( dataframe["close"] / dataframe["bb_lowerband-period"] ) dataframe["%-roc-period"] = ta.ROC(dataframe, timeperiod=period) dataframe["%-relative_volume-period"] = ( dataframe["volume"] / dataframe["volume"].rolling(period).mean() ) return dataframe ``` ###Assistant : *Only functional with FreqAI enabled strategies* This function will automatically expand the defined features on the config defined `indicator_periods_candles`, `include_timeframes`, `include_shifted_candles`, and `include_corr_pairs`. In other words, a single feature defined in this function will automatically expand to a total of `indicator_periods_candles` * `include_timeframes` * `include_shifted_candles` * `include_corr_pairs` numbers of features added to the model. All features must be prepended with `%` to be recognized by FreqAI internals. More details on how these config defined parameters accelerate feature engineering in the documentation at: https://www.freqtrade.io/en/latest/freqai-parameter-table/#feature-parameters https://www.freqtrade.io/en/latest/freqai-feature-engineering/#defining-the-features :param df: strategy dataframe which will receive the features :param period: period of the indicator - usage example: dataframe["%-ema-period"] = ta.EMA(dataframe, timeperiod=period)
322
def get_script_prefix(self, scope): if settings.FORCE_SCRIPT_NAME: return settings.FORCE_SCRIPT_NAME return scope.get("root_path", "") or ""
Return the script prefix to use from either the scope or a setting.
13
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_script_prefix(self, scope): if settings.FORCE_SCRIPT_NAME: return settings.FORCE_SCRIPT_NAME return scope.get("root_path", "") or "" ``` ###Assistant : Return the script prefix to use from either the scope or a setting.
323
def test_get_first_menu_and_fail(): part_one = f part_two = f command = ["storage", "create"] invoke_and_assert_in( command=command, desired_contents=(part_one, part_two), expected_code=1, user_input=f"{INVALID_OPTION}\n", )
Make sure that our utility function is returning as expected Found the following storage types: 0) Azure Blob Storage Store data in an Azure blob storage container. 1) File Storage Store data as a file on local or remote file systems. 2) Google Cloud Storage Store data in a GCS bucket. 3) Local Storage Store data in a run's local file system. Select a storage type to create: 99999999 Invalid selection {INVALID_OPTION}
72
19
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_get_first_menu_and_fail(): part_one = f part_two = f command = ["storage", "create"] invoke_and_assert_in( command=command, desired_contents=(part_one, part_two), expected_code=1, user_input=f"{INVALID_OPTION}\n", ) ``` ###Assistant : Make sure that our utility function is returning as expected Found the following storage types: 0) Azure Blob Storage Store data in an Azure blob storage container. 1) File Storage Store data as a file on local or remote file systems. 2) Google Cloud Storage Store data in a GCS bucket. 3) Local Storage Store data in a run's local file system. Select a storage type to create: 99999999 Invalid selection {INVALID_OPTION}
324
def check_planarity(G, counterexample=False): planarity_state = LRPlanarity(G) embedding = planarity_state.lr_planarity() if embedding is None: # graph is not planar if counterexample: return False, get_counterexample(G) else: return False, None else: # graph is planar return True, embedding
Check if a graph is planar and return a counterexample or an embedding. A graph is planar iff it can be drawn in a plane without any edge intersections. Parameters ---------- G : NetworkX graph counterexample : bool A Kuratowski subgraph (to proof non planarity) is only returned if set to true. Returns ------- (is_planar, certificate) : (bool, NetworkX graph) tuple is_planar is true if the graph is planar. If the graph is planar `certificate` is a PlanarEmbedding otherwise it is a Kuratowski subgraph. Examples -------- >>> G = nx.Graph([(0, 1), (0, 2)]) >>> is_planar, P = nx.check_planarity(G) >>> print(is_planar) True When `G` is planar, a `PlanarEmbedding` instance is returned: >>> P.get_data() {0: [1, 2], 1: [0], 2: [0]} Notes ----- A (combinatorial) embedding consists of cyclic orderings of the incident edges at each vertex. Given such an embedding there are multiple approaches discussed in literature to drawing the graph (subject to various constraints, e.g. integer coordinates), see e.g. [2]. The planarity check algorithm and extraction of the combinatorial embedding is based on the Left-Right Planarity Test [1]. A counterexample is only generated if the corresponding parameter is set, because the complexity of the counterexample generation is higher. References ---------- .. [1] Ulrik Brandes: The Left-Right Planarity Test 2009 http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.217.9208 .. [2] Takao Nishizeki, Md Saidur Rahman: Planar graph drawing Lecture Notes Series on Computing: Volume 12 2004
228
35
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def check_planarity(G, counterexample=False): planarity_state = LRPlanarity(G) embedding = planarity_state.lr_planarity() if embedding is None: # graph is not planar if counterexample: return False, get_counterexample(G) else: return False, None else: # graph is planar return True, embedding ``` ###Assistant : Check if a graph is planar and return a counterexample or an embedding. A graph is planar iff it can be drawn in a plane without any edge intersections. Parameters ---------- G : NetworkX graph counterexample : bool A Kuratowski subgraph (to proof non planarity) is only returned if set to true. Returns ------- (is_planar, certificate) : (bool, NetworkX graph) tuple is_planar is true if the graph is planar. If the graph is planar `certificate` is a PlanarEmbedding otherwise it is a Kuratowski subgraph. Examples -------- >>> G = nx.Graph([(0, 1), (0, 2)]) >>> is_planar, P = nx.check_planarity(G) >>> print(is_planar) True When `G` is planar, a `PlanarEmbedding` instance is returned: >>> P.get_data() {0: [1, 2], 1: [0], 2: [0]} Notes ----- A (combinatorial) embedding consists of cyclic orderings of the incident edges at each vertex. Given such an embedding there are multiple approaches discussed in literature to drawing the graph (subject to various constraints, e.g. integer coordinates), see e.g. [2]. The planarity check algorithm and extraction of the combinatorial embedding is based on the Left-Right Planarity Test [1]. A counterexample is only generated if the corresponding parameter is set, because the complexity of the counterexample generation is higher. References ---------- .. [1] Ulrik Brandes: The Left-Right Planarity Test 2009 http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.217.9208 .. [2] Takao Nishizeki, Md Saidur Rahman: Planar graph drawing Lecture Notes Series on Computing: Volume 12 2004
325
def _get_bool(val) -> Optional[bool]: if isinstance(val, bool): return val elif isinstance(val, str): if val.strip().lower() == 'true': return True elif val.strip().lower() == 'false': return False return None
Converts val to bool if can be done with certainty. If we cannot infer intention we return None.
18
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_bool(val) -> Optional[bool]: if isinstance(val, bool): return val elif isinstance(val, str): if val.strip().lower() == 'true': return True elif val.strip().lower() == 'false': return False return None ``` ###Assistant : Converts val to bool if can be done with certainty. If we cannot infer intention we return None.
326
def load_data_ptb(batch_size, max_window_size, num_noise_words): sentences = read_ptb() vocab = d2l.Vocab(sentences, min_freq=10) subsampled, counter = subsample(sentences, vocab) corpus = [vocab[line] for line in subsampled] all_centers, all_contexts = get_centers_and_contexts( corpus, max_window_size) all_negatives = get_negatives( all_contexts, vocab, counter, num_noise_words) dataset = gluon.data.ArrayDataset( all_centers, all_contexts, all_negatives) data_iter = gluon.data.DataLoader( dataset, batch_size, shuffle=True,batchify_fn=batchify, num_workers=d2l.get_dataloader_workers()) return data_iter, vocab d2l.DATA_HUB['glove.6b.50d'] = (d2l.DATA_URL + 'glove.6B.50d.zip', '0b8703943ccdb6eb788e6f091b8946e82231bc4d') d2l.DATA_HUB['glove.6b.100d'] = (d2l.DATA_URL + 'glove.6B.100d.zip', 'cd43bfb07e44e6f27cbcc7bc9ae3d80284fdaf5a') d2l.DATA_HUB['glove.42b.300d'] = (d2l.DATA_URL + 'glove.42B.300d.zip', 'b5116e234e9eb9076672cfeabf5469f3eec904fa') d2l.DATA_HUB['wiki.en'] = (d2l.DATA_URL + 'wiki.en.zip', 'c1816da3821ae9f43899be655002f6c723e91b88')
Download the PTB dataset and then load it into memory. Defined in :numref:`subsec_word2vec-minibatch-loading`
13
76
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def load_data_ptb(batch_size, max_window_size, num_noise_words): sentences = read_ptb() vocab = d2l.Vocab(sentences, min_freq=10) subsampled, counter = subsample(sentences, vocab) corpus = [vocab[line] for line in subsampled] all_centers, all_contexts = get_centers_and_contexts( corpus, max_window_size) all_negatives = get_negatives( all_contexts, vocab, counter, num_noise_words) dataset = gluon.data.ArrayDataset( all_centers, all_contexts, all_negatives) data_iter = gluon.data.DataLoader( dataset, batch_size, shuffle=True,batchify_fn=batchify, num_workers=d2l.get_dataloader_workers()) return data_iter, vocab d2l.DATA_HUB['glove.6b.50d'] = (d2l.DATA_URL + 'glove.6B.50d.zip', '0b8703943ccdb6eb788e6f091b8946e82231bc4d') d2l.DATA_HUB['glove.6b.100d'] = (d2l.DATA_URL + 'glove.6B.100d.zip', 'cd43bfb07e44e6f27cbcc7bc9ae3d80284fdaf5a') d2l.DATA_HUB['glove.42b.300d'] = (d2l.DATA_URL + 'glove.42B.300d.zip', 'b5116e234e9eb9076672cfeabf5469f3eec904fa') d2l.DATA_HUB['wiki.en'] = (d2l.DATA_URL + 'wiki.en.zip', 'c1816da3821ae9f43899be655002f6c723e91b88') ``` ###Assistant : Download the PTB dataset and then load it into memory. Defined in :numref:`subsec_word2vec-minibatch-loading`
327
async def async_config_changed(self) -> None: assert self.driver is not None await self.hass.async_add_executor_job(self.driver.config_changed)
Call config changed which writes out the new config to disk.
11
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def async_config_changed(self) -> None: assert self.driver is not None await self.hass.async_add_executor_job(self.driver.config_changed) ``` ###Assistant : Call config changed which writes out the new config to disk.
328
def setDebugActions(self, startAction, successAction, exceptionAction): self.debugActions = (startAction or _defaultStartDebugAction, successAction or _defaultSuccessDebugAction, exceptionAction or _defaultExceptionDebugAction) self.debug = True return self
Enable display of debugging messages while doing pattern matching.
9
21
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def setDebugActions(self, startAction, successAction, exceptionAction): self.debugActions = (startAction or _defaultStartDebugAction, successAction or _defaultSuccessDebugAction, exceptionAction or _defaultExceptionDebugAction) self.debug = True return self ``` ###Assistant : Enable display of debugging messages while doing pattern matching.
329
def get_qty_amount_data_for_cumulative(pr_doc, doc, items=None): if items is None: items = [] sum_qty, sum_amt = [0, 0] doctype = doc.get("parenttype") or doc.doctype date_field = ( "transaction_date" if frappe.get_meta(doctype).has_field("transaction_date") else "posting_date" ) child_doctype = "{0} Item".format(doctype) apply_on = frappe.scrub(pr_doc.get("apply_on")) values = [pr_doc.valid_from, pr_doc.valid_upto] condition = "" if pr_doc.warehouse: warehouses = get_child_warehouses(pr_doc.warehouse) condition += .format( child_doc=child_doctype, warehouses=",".join(["%s"] * len(warehouses)) ) values.extend(warehouses) if items: condition = " and `tab{child_doc}`.{apply_on} in ({items})".format( child_doc=child_doctype, apply_on=apply_on, items=",".join(["%s"] * len(items)) ) values.extend(items) data_set = frappe.db.sql( .format( parent_doc=doctype, child_doc=child_doctype, condition=condition, date_field=date_field ), tuple(values), as_dict=1, ) for data in data_set: sum_qty += data.get("stock_qty") sum_amt += data.get("amount") return [sum_qty, sum_amt]
and `tab{child_doc}`.warehouse in ({warehouses}) SELECT `tab{child_doc}`.stock_qty, `tab{child_doc}`.amount FROM `tab{child_doc}`, `tab{parent_doc}` WHERE `tab{child_doc}`.parent = `tab{parent_doc}`.name and `tab{parent_doc}`.{date_field} between %s and %s and `tab{parent_doc}`.docstatus = 1 {condition} group by `tab{child_doc}`.name
28
99
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_qty_amount_data_for_cumulative(pr_doc, doc, items=None): if items is None: items = [] sum_qty, sum_amt = [0, 0] doctype = doc.get("parenttype") or doc.doctype date_field = ( "transaction_date" if frappe.get_meta(doctype).has_field("transaction_date") else "posting_date" ) child_doctype = "{0} Item".format(doctype) apply_on = frappe.scrub(pr_doc.get("apply_on")) values = [pr_doc.valid_from, pr_doc.valid_upto] condition = "" if pr_doc.warehouse: warehouses = get_child_warehouses(pr_doc.warehouse) condition += .format( child_doc=child_doctype, warehouses=",".join(["%s"] * len(warehouses)) ) values.extend(warehouses) if items: condition = " and `tab{child_doc}`.{apply_on} in ({items})".format( child_doc=child_doctype, apply_on=apply_on, items=",".join(["%s"] * len(items)) ) values.extend(items) data_set = frappe.db.sql( .format( parent_doc=doctype, child_doc=child_doctype, condition=condition, date_field=date_field ), tuple(values), as_dict=1, ) for data in data_set: sum_qty += data.get("stock_qty") sum_amt += data.get("amount") return [sum_qty, sum_amt] ``` ###Assistant : and `tab{child_doc}`.warehouse in ({warehouses}) SELECT `tab{child_doc}`.stock_qty, `tab{child_doc}`.amount FROM `tab{child_doc}`, `tab{parent_doc}` WHERE `tab{child_doc}`.parent = `tab{parent_doc}`.name and `tab{parent_doc}`.{date_field} between %s and %s and `tab{parent_doc}`.docstatus = 1 {condition} group by `tab{child_doc}`.name
330
def make_system(A, M, x0, b): A_ = A A = aslinearoperator(A) if A.shape[0] != A.shape[1]: raise ValueError(f'expected square matrix, but got shape={(A.shape,)}') N = A.shape[0] b = asanyarray(b) if not (b.shape == (N,1) or b.shape == (N,)): raise ValueError(f'shapes of A {A.shape} and b {b.shape} are ' 'incompatible') if b.dtype.char not in 'fdFD': b = b.astype('d') # upcast non-FP types to double
Make a linear system Ax=b Parameters ---------- A : LinearOperator sparse or dense matrix (or any valid input to aslinearoperator) M : {LinearOperator, Nones} preconditioner sparse or dense matrix (or any valid input to aslinearoperator) x0 : {array_like, str, None} initial guess to iterative method. ``x0 = 'Mb'`` means using the nonzero initial guess ``M @ b``. Default is `None`, which means using the zero initial guess. b : array_like right hand side Returns ------- (A, M, x, b, postprocess) A : LinearOperator matrix of the linear system M : LinearOperator preconditioner x : rank 1 ndarray initial guess b : rank 1 ndarray right hand side postprocess : function converts the solution vector to the appropriate type and dimensions (e.g. (N,1) matrix)
123
62
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def make_system(A, M, x0, b): A_ = A A = aslinearoperator(A) if A.shape[0] != A.shape[1]: raise ValueError(f'expected square matrix, but got shape={(A.shape,)}') N = A.shape[0] b = asanyarray(b) if not (b.shape == (N,1) or b.shape == (N,)): raise ValueError(f'shapes of A {A.shape} and b {b.shape} are ' 'incompatible') if b.dtype.char not in 'fdFD': b = b.astype('d') # upcast non-FP types to double ``` ###Assistant : Make a linear system Ax=b Parameters ---------- A : LinearOperator sparse or dense matrix (or any valid input to aslinearoperator) M : {LinearOperator, Nones} preconditioner sparse or dense matrix (or any valid input to aslinearoperator) x0 : {array_like, str, None} initial guess to iterative method. ``x0 = 'Mb'`` means using the nonzero initial guess ``M @ b``. Default is `None`, which means using the zero initial guess. b : array_like right hand side Returns ------- (A, M, x, b, postprocess) A : LinearOperator matrix of the linear system M : LinearOperator preconditioner x : rank 1 ndarray initial guess b : rank 1 ndarray right hand side postprocess : function converts the solution vector to the appropriate type and dimensions (e.g. (N,1) matrix)
331
def dodecahedral_graph(create_using=None): G = LCF_graph(20, [10, 7, 4, -4, -7, 10, -4, 7, -7, 4], 2, create_using) G.name = "Dodecahedral Graph" return G
Returns the Platonic Dodecahedral graph. The dodecahedral graph has 20 nodes and 30 edges. The skeleton of the dodecahedron forms a graph. It is one of 5 Platonic graphs [1]_. It can be described in LCF notation as: ``[10, 7, 4, -4, -7, 10, -4, 7, -7, 4]^2`` [2]_. Parameters ---------- create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- G : networkx Graph Dodecahedral Graph with 20 nodes and 30 edges References ---------- .. [1] https://en.wikipedia.org/wiki/Regular_dodecahedron#Dodecahedral_graph .. [2] https://mathworld.wolfram.com/DodecahedralGraph.html
91
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def dodecahedral_graph(create_using=None): G = LCF_graph(20, [10, 7, 4, -4, -7, 10, -4, 7, -7, 4], 2, create_using) G.name = "Dodecahedral Graph" return G ``` ###Assistant : Returns the Platonic Dodecahedral graph. The dodecahedral graph has 20 nodes and 30 edges. The skeleton of the dodecahedron forms a graph. It is one of 5 Platonic graphs [1]_. It can be described in LCF notation as: ``[10, 7, 4, -4, -7, 10, -4, 7, -7, 4]^2`` [2]_. Parameters ---------- create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Returns ------- G : networkx Graph Dodecahedral Graph with 20 nodes and 30 edges References ---------- .. [1] https://en.wikipedia.org/wiki/Regular_dodecahedron#Dodecahedral_graph .. [2] https://mathworld.wolfram.com/DodecahedralGraph.html
332
def arc_tangent(value, default=_SENTINEL): try: return math.atan(float(value)) except (ValueError, TypeError): if default is _SENTINEL: raise_no_default("atan", value) return default
Filter and function to get arc tangent of the value.
10
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def arc_tangent(value, default=_SENTINEL): try: return math.atan(float(value)) except (ValueError, TypeError): if default is _SENTINEL: raise_no_default("atan", value) return default ``` ###Assistant : Filter and function to get arc tangent of the value.
333
def sparse_top_k_categorical_matches(y_true, y_pred, k=5): reshape_matches = False y_true = tf.convert_to_tensor(y_true) y_pred = tf.convert_to_tensor(y_pred) y_true_rank = y_true.shape.ndims y_pred_rank = y_pred.shape.ndims y_true_org_shape = tf.shape(y_true) # Flatten y_pred to (batch_size, num_samples) and y_true to (num_samples,) if (y_true_rank is not None) and (y_pred_rank is not None): if y_pred_rank > 2: y_pred = tf.reshape(y_pred, [-1, y_pred.shape[-1]]) if y_true_rank > 1: reshape_matches = True y_true = tf.reshape(y_true, [-1]) matches = tf.cast( tf.math.in_top_k( predictions=y_pred, targets=tf.cast(y_true, "int32"), k=k ), dtype=backend.floatx(), ) # returned matches is expected to have same shape as y_true input if reshape_matches: return tf.reshape(matches, shape=y_true_org_shape) return matches
Creates float Tensor, 1.0 for label-TopK_prediction match, 0.0 for mismatch. Args: y_true: tensor of true targets. y_pred: tensor of predicted targets. k: (Optional) Number of top elements to look at for computing accuracy. Defaults to 5. Returns: Match tensor: 1.0 for label-prediction match, 0.0 for mismatch.
46
92
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def sparse_top_k_categorical_matches(y_true, y_pred, k=5): reshape_matches = False y_true = tf.convert_to_tensor(y_true) y_pred = tf.convert_to_tensor(y_pred) y_true_rank = y_true.shape.ndims y_pred_rank = y_pred.shape.ndims y_true_org_shape = tf.shape(y_true) # Flatten y_pred to (batch_size, num_samples) and y_true to (num_samples,) if (y_true_rank is not None) and (y_pred_rank is not None): if y_pred_rank > 2: y_pred = tf.reshape(y_pred, [-1, y_pred.shape[-1]]) if y_true_rank > 1: reshape_matches = True y_true = tf.reshape(y_true, [-1]) matches = tf.cast( tf.math.in_top_k( predictions=y_pred, targets=tf.cast(y_true, "int32"), k=k ), dtype=backend.floatx(), ) # returned matches is expected to have same shape as y_true input if reshape_matches: return tf.reshape(matches, shape=y_true_org_shape) return matches ``` ###Assistant : Creates float Tensor, 1.0 for label-TopK_prediction match, 0.0 for mismatch. Args: y_true: tensor of true targets. y_pred: tensor of predicted targets. k: (Optional) Number of top elements to look at for computing accuracy. Defaults to 5. Returns: Match tensor: 1.0 for label-prediction match, 0.0 for mismatch.
334
def tax_account_query(doctype, txt, searchfield, start, page_len, filters): company_currency = erpnext.get_company_currency(filters.get("company")) def get_accounts(with_account_type_filter): account_type_condition = "" if with_account_type_filter: account_type_condition = "AND account_type in %(account_types)s" accounts = frappe.db.sql( .format( account_type_condition=account_type_condition, searchfield=searchfield, mcond=get_match_cond(doctype), ), dict( account_types=filters.get("account_type"), company=filters.get("company"), disabled=filters.get("disabled", 0), currency=company_currency, txt="%{}%".format(txt), offset=start, limit=page_len, ), ) return accounts tax_accounts = get_accounts(True) if not tax_accounts: tax_accounts = get_accounts(False) return tax_accounts @frappe.whitelist() @frappe.validate_and_sanitize_search_inputs
SELECT name, parent_account FROM `tabAccount` WHERE `tabAccount`.docstatus!=2 {account_type_condition} AND is_group = 0 AND company = %(company)s AND disabled = %(disabled)s AND (account_currency = %(currency)s or ifnull(account_currency, '') = '') AND `{searchfield}` LIKE %(txt)s {mcond} ORDER BY idx DESC, name LIMIT %(offset)s, %(limit)s
42
57
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def tax_account_query(doctype, txt, searchfield, start, page_len, filters): company_currency = erpnext.get_company_currency(filters.get("company")) def get_accounts(with_account_type_filter): account_type_condition = "" if with_account_type_filter: account_type_condition = "AND account_type in %(account_types)s" accounts = frappe.db.sql( .format( account_type_condition=account_type_condition, searchfield=searchfield, mcond=get_match_cond(doctype), ), dict( account_types=filters.get("account_type"), company=filters.get("company"), disabled=filters.get("disabled", 0), currency=company_currency, txt="%{}%".format(txt), offset=start, limit=page_len, ), ) return accounts tax_accounts = get_accounts(True) if not tax_accounts: tax_accounts = get_accounts(False) return tax_accounts @frappe.whitelist() @frappe.validate_and_sanitize_search_inputs ``` ###Assistant : SELECT name, parent_account FROM `tabAccount` WHERE `tabAccount`.docstatus!=2 {account_type_condition} AND is_group = 0 AND company = %(company)s AND disabled = %(disabled)s AND (account_currency = %(currency)s or ifnull(account_currency, '') = '') AND `{searchfield}` LIKE %(txt)s {mcond} ORDER BY idx DESC, name LIMIT %(offset)s, %(limit)s
335
def test_add_post_duplicate_choose_permission(self): # Create group with access to admin and add permission. bakers_group = Group.objects.create(name="Bakers") access_admin_perm = Permission.objects.get( content_type__app_label="wagtailadmin", codename="access_admin" ) bakers_group.permissions.add(access_admin_perm) # Create the "Bakery" Collection and grant "add" permission to the Bakers group. root = Collection.objects.get(id=get_root_collection_id()) bakery_collection = root.add_child(instance=Collection(name="Bakery")) GroupCollectionPermission.objects.create( group=bakers_group, collection=bakery_collection, permission=Permission.objects.get( content_type__app_label="wagtailimages", codename="add_image" ), )
When a duplicate image is added but the user doesn't have permission to choose the original image, the add views lets the user upload it as if it weren't a duplicate.
31
49
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_add_post_duplicate_choose_permission(self): # Create group with access to admin and add permission. bakers_group = Group.objects.create(name="Bakers") access_admin_perm = Permission.objects.get( content_type__app_label="wagtailadmin", codename="access_admin" ) bakers_group.permissions.add(access_admin_perm) # Create the "Bakery" Collection and grant "add" permission to the Bakers group. root = Collection.objects.get(id=get_root_collection_id()) bakery_collection = root.add_child(instance=Collection(name="Bakery")) GroupCollectionPermission.objects.create( group=bakers_group, collection=bakery_collection, permission=Permission.objects.get( content_type__app_label="wagtailimages", codename="add_image" ), ) ``` ###Assistant : When a duplicate image is added but the user doesn't have permission to choose the original image, the add views lets the user upload it as if it weren't a duplicate.
336
def netmiko_commands(*commands, **kwargs): conn = _netmiko_conn(**kwargs) ret = [] for cmd in commands: ret.append(conn.send_command(cmd)) return ret @proxy_napalm_wrap
.. versionadded:: 2019.2.0 Invoke one or more commands to be executed on the remote device, via Netmiko. Returns a list of strings, with the output from each command. commands A list of commands to be executed. expect_string Regular expression pattern to use for determining end of output. If left blank will default to being based on router prompt. delay_factor: ``1`` Multiplying factor used to adjust delays (default: ``1``). max_loops: ``500`` Controls wait time in conjunction with delay_factor. Will default to be based upon self.timeout. auto_find_prompt: ``True`` Whether it should try to auto-detect the prompt (default: ``True``). strip_prompt: ``True`` Remove the trailing router prompt from the output (default: ``True``). strip_command: ``True`` Remove the echo of the command from the output (default: ``True``). normalize: ``True`` Ensure the proper enter is sent at end of command (default: ``True``). use_textfsm: ``False`` Process command output through TextFSM template (default: ``False``). CLI Example: .. code-block:: bash salt '*' napalm.netmiko_commands 'show version' 'show interfaces'
157
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def netmiko_commands(*commands, **kwargs): conn = _netmiko_conn(**kwargs) ret = [] for cmd in commands: ret.append(conn.send_command(cmd)) return ret @proxy_napalm_wrap ``` ###Assistant : .. versionadded:: 2019.2.0 Invoke one or more commands to be executed on the remote device, via Netmiko. Returns a list of strings, with the output from each command. commands A list of commands to be executed. expect_string Regular expression pattern to use for determining end of output. If left blank will default to being based on router prompt. delay_factor: ``1`` Multiplying factor used to adjust delays (default: ``1``). max_loops: ``500`` Controls wait time in conjunction with delay_factor. Will default to be based upon self.timeout. auto_find_prompt: ``True`` Whether it should try to auto-detect the prompt (default: ``True``). strip_prompt: ``True`` Remove the trailing router prompt from the output (default: ``True``). strip_command: ``True`` Remove the echo of the command from the output (default: ``True``). normalize: ``True`` Ensure the proper enter is sent at end of command (default: ``True``). use_textfsm: ``False`` Process command output through TextFSM template (default: ``False``). CLI Example: .. code-block:: bash salt '*' napalm.netmiko_commands 'show version' 'show interfaces'
337
def decoder(self, side): input_ = Input(shape=(8, 8, 512)) var_x = input_ var_x = UpscaleBlock(256, activation="leakyrelu")(var_x) var_x = UpscaleBlock(128, activation="leakyrelu")(var_x) var_x = UpscaleBlock(64, activation="leakyrelu")(var_x) var_x = Conv2DOutput(3, 5, name=f"face_out_{side}")(var_x) outputs = [var_x] if self.learn_mask: var_y = input_ var_y = UpscaleBlock(256, activation="leakyrelu")(var_y) var_y = UpscaleBlock(128, activation="leakyrelu")(var_y) var_y = UpscaleBlock(64, activation="leakyrelu")(var_y) var_y = Conv2DOutput(1, 5, name=f"mask_out_{side}")(var_y) outputs.append(var_y) return KerasModel(input_, outputs=outputs, name=f"decoder_{side}")
The original Faceswap Decoder Network. The decoders for the original model have separate weights for each side "A" and "B", so two instances are created in :func:`build_model`, one for each side. Parameters ---------- side: str Either `"a` or `"b"`. This is used for naming the decoder model. Returns ------- :class:`keras.models.Model` The Keras decoder model. This will be called twice, once for each side.
63
58
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def decoder(self, side): input_ = Input(shape=(8, 8, 512)) var_x = input_ var_x = UpscaleBlock(256, activation="leakyrelu")(var_x) var_x = UpscaleBlock(128, activation="leakyrelu")(var_x) var_x = UpscaleBlock(64, activation="leakyrelu")(var_x) var_x = Conv2DOutput(3, 5, name=f"face_out_{side}")(var_x) outputs = [var_x] if self.learn_mask: var_y = input_ var_y = UpscaleBlock(256, activation="leakyrelu")(var_y) var_y = UpscaleBlock(128, activation="leakyrelu")(var_y) var_y = UpscaleBlock(64, activation="leakyrelu")(var_y) var_y = Conv2DOutput(1, 5, name=f"mask_out_{side}")(var_y) outputs.append(var_y) return KerasModel(input_, outputs=outputs, name=f"decoder_{side}") ``` ###Assistant : The original Faceswap Decoder Network. The decoders for the original model have separate weights for each side "A" and "B", so two instances are created in :func:`build_model`, one for each side. Parameters ---------- side: str Either `"a` or `"b"`. This is used for naming the decoder model. Returns ------- :class:`keras.models.Model` The Keras decoder model. This will be called twice, once for each side.
338
def test_users_getting_add_peer_event(self) -> None: streams_to_sub = ["multi_user_stream"] othello = self.example_user("othello") cordelia = self.example_user("cordelia") iago = self.example_user("iago") orig_user_ids_to_subscribe = [self.test_user.id, othello.id] self.common_subscribe_to_streams( self.test_user, streams_to_sub, dict(principals=orjson.dumps(orig_user_ids_to_subscribe).decode()), ) new_user_ids_to_subscribe = [iago.id, cordelia.id] events: List[Mapping[str, Any]] = [] with self.tornado_redirected_to_list(events, expected_num_events=5): self.common_subscribe_to_streams( self.test_user, streams_to_sub, dict(principals=orjson.dumps(new_user_ids_to_subscribe).decode()), ) add_peer_events = [event for event in events if event["event"].get("op") == "peer_add"] (add_peer_event,) = add_peer_events self.assertEqual(add_peer_event["event"]["type"], "subscription") self.assertEqual(add_peer_event["event"]["op"], "peer_add") event_sent_to_ids = add_peer_event["users"] for user_id in new_user_ids_to_subscribe: # Make sure new users subscribed to stream is not in # peer_add event recipient list self.assertNotIn(user_id, event_sent_to_ids) for old_user in orig_user_ids_to_subscribe: # Check non-new users are in peer_add event recipient list. self.assertIn(old_user, event_sent_to_ids)
Check users getting add_peer_event is correct
6
101
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_users_getting_add_peer_event(self) -> None: streams_to_sub = ["multi_user_stream"] othello = self.example_user("othello") cordelia = self.example_user("cordelia") iago = self.example_user("iago") orig_user_ids_to_subscribe = [self.test_user.id, othello.id] self.common_subscribe_to_streams( self.test_user, streams_to_sub, dict(principals=orjson.dumps(orig_user_ids_to_subscribe).decode()), ) new_user_ids_to_subscribe = [iago.id, cordelia.id] events: List[Mapping[str, Any]] = [] with self.tornado_redirected_to_list(events, expected_num_events=5): self.common_subscribe_to_streams( self.test_user, streams_to_sub, dict(principals=orjson.dumps(new_user_ids_to_subscribe).decode()), ) add_peer_events = [event for event in events if event["event"].get("op") == "peer_add"] (add_peer_event,) = add_peer_events self.assertEqual(add_peer_event["event"]["type"], "subscription") self.assertEqual(add_peer_event["event"]["op"], "peer_add") event_sent_to_ids = add_peer_event["users"] for user_id in new_user_ids_to_subscribe: # Make sure new users subscribed to stream is not in # peer_add event recipient list self.assertNotIn(user_id, event_sent_to_ids) for old_user in orig_user_ids_to_subscribe: # Check non-new users are in peer_add event recipient list. self.assertIn(old_user, event_sent_to_ids) ``` ###Assistant : Check users getting add_peer_event is correct
339
def show_trace_2d(f, results): d2l.set_figsize() d2l.plt.plot(*zip(*results), '-o', color='#ff7f0e') x1, x2 = d2l.meshgrid(d2l.arange(-5.5, 1.0, 0.1), d2l.arange(-3.0, 1.0, 0.1)) d2l.plt.contour(x1, x2, f(x1, x2), colors='#1f77b4') d2l.plt.xlabel('x1') d2l.plt.ylabel('x2') d2l.DATA_HUB['airfoil'] = (d2l.DATA_URL + 'airfoil_self_noise.dat', '76e5be1548fd8222e5074cf0faae75edff8cf93f')
Show the trace of 2D variables during optimization. Defined in :numref:`subsec_gd-learningrate`
11
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def show_trace_2d(f, results): d2l.set_figsize() d2l.plt.plot(*zip(*results), '-o', color='#ff7f0e') x1, x2 = d2l.meshgrid(d2l.arange(-5.5, 1.0, 0.1), d2l.arange(-3.0, 1.0, 0.1)) d2l.plt.contour(x1, x2, f(x1, x2), colors='#1f77b4') d2l.plt.xlabel('x1') d2l.plt.ylabel('x2') d2l.DATA_HUB['airfoil'] = (d2l.DATA_URL + 'airfoil_self_noise.dat', '76e5be1548fd8222e5074cf0faae75edff8cf93f') ``` ###Assistant : Show the trace of 2D variables during optimization. Defined in :numref:`subsec_gd-learningrate`
340
def test_dataset(ray_start_4_cpus, use_local): model_creator = mlp_identity.model_creator optimizer_creator = mlp_identity.optimizer_creator dataset_creator = mlp_identity.dataset_creator DatasetOperator = TrainingOperator.from_creators( model_creator=model_creator, optimizer_creator=optimizer_creator, loss_creator=nn.MSELoss, ) trainer = TorchTrainer( training_operator_cls=DatasetOperator, use_local=use_local, num_workers=2, ) dataset = dataset_creator() for i in range(5): trainer.train(dataset=dataset, num_steps=100) x = mlp_identity.to_mat(0.5) prediction = float(trainer.get_model()(x)[0][0]) assert 0.4 <= prediction <= 0.6 trainer.shutdown() @pytest.mark.parametrize("use_local", [True, False])
This test tries training the mlp_identity example. We check the accuracy of the model as an all inclusive way of ensuring that we are properly sharding and iterating over the entire dataset (instead of repeating the first set of points for example).
42
51
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_dataset(ray_start_4_cpus, use_local): model_creator = mlp_identity.model_creator optimizer_creator = mlp_identity.optimizer_creator dataset_creator = mlp_identity.dataset_creator DatasetOperator = TrainingOperator.from_creators( model_creator=model_creator, optimizer_creator=optimizer_creator, loss_creator=nn.MSELoss, ) trainer = TorchTrainer( training_operator_cls=DatasetOperator, use_local=use_local, num_workers=2, ) dataset = dataset_creator() for i in range(5): trainer.train(dataset=dataset, num_steps=100) x = mlp_identity.to_mat(0.5) prediction = float(trainer.get_model()(x)[0][0]) assert 0.4 <= prediction <= 0.6 trainer.shutdown() @pytest.mark.parametrize("use_local", [True, False]) ``` ###Assistant : This test tries training the mlp_identity example. We check the accuracy of the model as an all inclusive way of ensuring that we are properly sharding and iterating over the entire dataset (instead of repeating the first set of points for example).
341
def lovasz_softmax_flat(probas, labels, classes='present', weighted=None): if probas.numel() == 0: # only void pixels, the gradients should be 0 return probas * 0. C = probas.size(1) losses = [] class_to_sum = list(range(C)) if classes in ['all', 'present'] else classes for c in class_to_sum: fg = (labels == c).float() # foreground for class c if (classes is 'present' and fg.sum() == 0): continue if C == 1: if len(classes) > 1: raise ValueError('Sigmoid output possible only with 1 class') class_pred = probas[:, 0] else: class_pred = probas[:, c] errors = (Variable(fg) - class_pred).abs() errors_sorted, perm = torch.sort(errors, 0, descending=True) perm = perm.data fg_sorted = fg[perm] if weighted is not None: losses.append(weighted[c]*torch.dot(errors_sorted, Variable(lovasz_grad(fg_sorted)))) else: losses.append(torch.dot(errors_sorted, Variable(lovasz_grad(fg_sorted)))) return mean(losses)
Multi-class Lovasz-Softmax loss probas: [P, C] Variable, class probabilities at each prediction (between 0 and 1) labels: [P] Tensor, ground truth labels (between 0 and C - 1) classes: 'all' for all, 'present' for classes present in labels, or a list of classes to average.
45
115
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def lovasz_softmax_flat(probas, labels, classes='present', weighted=None): if probas.numel() == 0: # only void pixels, the gradients should be 0 return probas * 0. C = probas.size(1) losses = [] class_to_sum = list(range(C)) if classes in ['all', 'present'] else classes for c in class_to_sum: fg = (labels == c).float() # foreground for class c if (classes is 'present' and fg.sum() == 0): continue if C == 1: if len(classes) > 1: raise ValueError('Sigmoid output possible only with 1 class') class_pred = probas[:, 0] else: class_pred = probas[:, c] errors = (Variable(fg) - class_pred).abs() errors_sorted, perm = torch.sort(errors, 0, descending=True) perm = perm.data fg_sorted = fg[perm] if weighted is not None: losses.append(weighted[c]*torch.dot(errors_sorted, Variable(lovasz_grad(fg_sorted)))) else: losses.append(torch.dot(errors_sorted, Variable(lovasz_grad(fg_sorted)))) return mean(losses) ``` ###Assistant : Multi-class Lovasz-Softmax loss probas: [P, C] Variable, class probabilities at each prediction (between 0 and 1) labels: [P] Tensor, ground truth labels (between 0 and C - 1) classes: 'all' for all, 'present' for classes present in labels, or a list of classes to average.
342
def mixin_distributed_feature_parser(parser): gp = add_arg_group(parser, title='Distributed') gp.add_argument( '--quiet-remote-logs', action='store_true', default=False, help='Do not display the streaming of remote logs on local console', ) gp.add_argument( '--upload-files', type=str, nargs='*', metavar='FILE', help=, ) gp.add_argument( '--disable-remote', action='store_true', default=False, help='If set, remote pod invocation is avoided. This is used by pods created by JinaD' if _SHOW_ALL_ARGS else argparse.SUPPRESS, )
Mixing in arguments required by :class:`BaseDeployment` into the given parser. :param parser: the parser instance to which we add arguments The files on the host to be uploaded to the remote workspace. This can be useful when your Deployment has more file dependencies beyond a single YAML file, e.g. Python files, data files. Note, - currently only flatten structure is supported, which means if you upload `[./foo/a.py, ./foo/b.pp, ./bar/c.yml]`, then they will be put under the _same_ workspace on the remote, losing all hierarchies. - by default, `--uses` YAML file is always uploaded. - uploaded files are by default isolated across the runs. To ensure files are submitted to the same workspace across different runs, use `--workspace-id` to specify the workspace.
121
53
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def mixin_distributed_feature_parser(parser): gp = add_arg_group(parser, title='Distributed') gp.add_argument( '--quiet-remote-logs', action='store_true', default=False, help='Do not display the streaming of remote logs on local console', ) gp.add_argument( '--upload-files', type=str, nargs='*', metavar='FILE', help=, ) gp.add_argument( '--disable-remote', action='store_true', default=False, help='If set, remote pod invocation is avoided. This is used by pods created by JinaD' if _SHOW_ALL_ARGS else argparse.SUPPRESS, ) ``` ###Assistant : Mixing in arguments required by :class:`BaseDeployment` into the given parser. :param parser: the parser instance to which we add arguments The files on the host to be uploaded to the remote workspace. This can be useful when your Deployment has more file dependencies beyond a single YAML file, e.g. Python files, data files. Note, - currently only flatten structure is supported, which means if you upload `[./foo/a.py, ./foo/b.pp, ./bar/c.yml]`, then they will be put under the _same_ workspace on the remote, losing all hierarchies. - by default, `--uses` YAML file is always uploaded. - uploaded files are by default isolated across the runs. To ensure files are submitted to the same workspace across different runs, use `--workspace-id` to specify the workspace.
343
def get_bootstrap_modules(): # Import 'struct' modules to get real paths to module file names. mod_struct = __import__('struct') # Basic modules necessary for the bootstrap process. loader_mods = TOC() loaderpath = os.path.join(HOMEPATH, 'PyInstaller', 'loader') # On some platforms (Windows, Debian/Ubuntu) '_struct' and zlib modules are built-in modules (linked statically) # and thus does not have attribute __file__. 'struct' module is required for reading Python bytecode from # executable. 'zlib' is required to decompress this bytecode. for mod_name in ['_struct', 'zlib']: mod = __import__(mod_name) # C extension. if hasattr(mod, '__file__'): mod_file = os.path.abspath(mod.__file__) if os.path.basename(os.path.dirname(mod_file)) == 'lib-dynload': # Divert extensions originating from python's lib-dynload directory, to match behavior of #5604. mod_name = os.path.join('lib-dynload', mod_name) loader_mods.append((mod_name, mod_file, 'EXTENSION')) # NOTE:These modules should be kept simple without any complicated dependencies. loader_mods += [ ('struct', os.path.abspath(mod_struct.__file__), 'PYMODULE'), ('pyimod01_os_path', os.path.join(loaderpath, 'pyimod01_os_path.py'), 'PYMODULE'), ('pyimod02_archive', os.path.join(loaderpath, 'pyimod02_archive.py'), 'PYMODULE'), ('pyimod03_importers', os.path.join(loaderpath, 'pyimod03_importers.py'), 'PYMODULE'), ('pyimod04_ctypes', os.path.join(loaderpath, 'pyimod04_ctypes.py'), 'PYMODULE'), ('pyiboot01_bootstrap', os.path.join(loaderpath, 'pyiboot01_bootstrap.py'), 'PYSOURCE'), ] return loader_mods
Get TOC with the bootstrapping modules and their dependencies. :return: TOC with modules
13
155
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_bootstrap_modules(): # Import 'struct' modules to get real paths to module file names. mod_struct = __import__('struct') # Basic modules necessary for the bootstrap process. loader_mods = TOC() loaderpath = os.path.join(HOMEPATH, 'PyInstaller', 'loader') # On some platforms (Windows, Debian/Ubuntu) '_struct' and zlib modules are built-in modules (linked statically) # and thus does not have attribute __file__. 'struct' module is required for reading Python bytecode from # executable. 'zlib' is required to decompress this bytecode. for mod_name in ['_struct', 'zlib']: mod = __import__(mod_name) # C extension. if hasattr(mod, '__file__'): mod_file = os.path.abspath(mod.__file__) if os.path.basename(os.path.dirname(mod_file)) == 'lib-dynload': # Divert extensions originating from python's lib-dynload directory, to match behavior of #5604. mod_name = os.path.join('lib-dynload', mod_name) loader_mods.append((mod_name, mod_file, 'EXTENSION')) # NOTE:These modules should be kept simple without any complicated dependencies. loader_mods += [ ('struct', os.path.abspath(mod_struct.__file__), 'PYMODULE'), ('pyimod01_os_path', os.path.join(loaderpath, 'pyimod01_os_path.py'), 'PYMODULE'), ('pyimod02_archive', os.path.join(loaderpath, 'pyimod02_archive.py'), 'PYMODULE'), ('pyimod03_importers', os.path.join(loaderpath, 'pyimod03_importers.py'), 'PYMODULE'), ('pyimod04_ctypes', os.path.join(loaderpath, 'pyimod04_ctypes.py'), 'PYMODULE'), ('pyiboot01_bootstrap', os.path.join(loaderpath, 'pyiboot01_bootstrap.py'), 'PYSOURCE'), ] return loader_mods ``` ###Assistant : Get TOC with the bootstrapping modules and their dependencies. :return: TOC with modules
344
def getquoted(self): if self.is_geometry: # Psycopg will figure out whether to use E'\\000' or '\000'. return b"%s(%s)" % ( b"ST_GeogFromWKB" if self.geography else b"ST_GeomFromEWKB", self._adapter.getquoted(), ) else: # For rasters, add explicit type cast to WKB string. return b"'%s'::raster" % self.ewkb.encode()
Return a properly quoted string for use in PostgreSQL/PostGIS.
9
41
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def getquoted(self): if self.is_geometry: # Psycopg will figure out whether to use E'\\000' or '\000'. return b"%s(%s)" % ( b"ST_GeogFromWKB" if self.geography else b"ST_GeomFromEWKB", self._adapter.getquoted(), ) else: # For rasters, add explicit type cast to WKB string. return b"'%s'::raster" % self.ewkb.encode() ``` ###Assistant : Return a properly quoted string for use in PostgreSQL/PostGIS.
345
def _set_skip_list(self) -> None: if self._skip_num == 1 and not self._alignments.data: logger.debug("No frames to be skipped") return skip_list = [] for idx, filename in enumerate(self._images.file_list): if idx % self._skip_num != 0: logger.trace("Adding image '%s' to skip list due to extract_every_n = %s", filename, self._skip_num) skip_list.append(idx) # Items may be in the alignments file if skip-existing[-faces] is selected elif os.path.basename(filename) in self._alignments.data: self._existing_count += 1 logger.trace("Removing image: '%s' due to previously existing", filename) skip_list.append(idx) if self._existing_count != 0: logger.info("Skipping %s frames due to skip_existing/skip_existing_faces.", self._existing_count) logger.debug("Adding skip list: %s", skip_list) self._images.add_skip_list(skip_list)
Add the skip list to the image loader Checks against `extract_every_n` and the existence of alignments data (can exist if `skip_existing` or `skip_existing_faces` has been provided) and compiles a list of frame indices that should not be processed, providing these to :class:`lib.image.ImagesLoader`.
42
90
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _set_skip_list(self) -> None: if self._skip_num == 1 and not self._alignments.data: logger.debug("No frames to be skipped") return skip_list = [] for idx, filename in enumerate(self._images.file_list): if idx % self._skip_num != 0: logger.trace("Adding image '%s' to skip list due to extract_every_n = %s", filename, self._skip_num) skip_list.append(idx) # Items may be in the alignments file if skip-existing[-faces] is selected elif os.path.basename(filename) in self._alignments.data: self._existing_count += 1 logger.trace("Removing image: '%s' due to previously existing", filename) skip_list.append(idx) if self._existing_count != 0: logger.info("Skipping %s frames due to skip_existing/skip_existing_faces.", self._existing_count) logger.debug("Adding skip list: %s", skip_list) self._images.add_skip_list(skip_list) ``` ###Assistant : Add the skip list to the image loader Checks against `extract_every_n` and the existence of alignments data (can exist if `skip_existing` or `skip_existing_faces` has been provided) and compiles a list of frame indices that should not be processed, providing these to :class:`lib.image.ImagesLoader`.
346
def caplog(caplog): config = setup_logging() for name, logger_config in config["loggers"].items(): if not logger_config.get("propagate", True): logger = get_logger(name) logger.handlers.append(caplog.handler) yield caplog
Overrides caplog to apply to all of our loggers that do not propagate and consequently would not be captured by caplog.
21
20
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def caplog(caplog): config = setup_logging() for name, logger_config in config["loggers"].items(): if not logger_config.get("propagate", True): logger = get_logger(name) logger.handlers.append(caplog.handler) yield caplog ``` ###Assistant : Overrides caplog to apply to all of our loggers that do not propagate and consequently would not be captured by caplog.
347
def _show_mesh(self, mesh_ids, face_index, detected_face, top_left): state = "normal" if (self._tk_vars["selected_editor"].get() != "Mask" or self._optional_annotations["mesh"]) else "hidden" kwargs = dict(polygon=dict(fill="", width=2, outline=self._canvas.control_colors["Mesh"]), line=dict(fill=self._canvas.control_colors["Mesh"], width=2)) edited = (self._tk_vars["edited"].get() and self._tk_vars["selected_editor"].get() not in ("Mask", "View")) landmarks = self._viewport.get_landmarks(self.frame_index, face_index, detected_face, top_left, edited) for key, kwarg in kwargs.items(): for idx, mesh_id in enumerate(mesh_ids[key]): self._canvas.coords(mesh_id, *landmarks[key][idx].flatten()) self._canvas.itemconfig(mesh_id, state=state, **kwarg) self._canvas.addtag_withtag(f"active_mesh_{key}", mesh_id)
Display the mesh annotation for the given face, at the given location. Parameters ---------- mesh_ids: dict Dictionary containing the `polygon` and `line` tkinter canvas identifiers that make up the mesh for the given face face_index: int The face index within the frame for the given face detected_face: :class:`~lib.align.DetectedFace` The detected face object that contains the landmarks for generating the mesh top_left: tuple The (x, y) top left co-ordinates of the mesh's bounding box
73
57
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _show_mesh(self, mesh_ids, face_index, detected_face, top_left): state = "normal" if (self._tk_vars["selected_editor"].get() != "Mask" or self._optional_annotations["mesh"]) else "hidden" kwargs = dict(polygon=dict(fill="", width=2, outline=self._canvas.control_colors["Mesh"]), line=dict(fill=self._canvas.control_colors["Mesh"], width=2)) edited = (self._tk_vars["edited"].get() and self._tk_vars["selected_editor"].get() not in ("Mask", "View")) landmarks = self._viewport.get_landmarks(self.frame_index, face_index, detected_face, top_left, edited) for key, kwarg in kwargs.items(): for idx, mesh_id in enumerate(mesh_ids[key]): self._canvas.coords(mesh_id, *landmarks[key][idx].flatten()) self._canvas.itemconfig(mesh_id, state=state, **kwarg) self._canvas.addtag_withtag(f"active_mesh_{key}", mesh_id) ``` ###Assistant : Display the mesh annotation for the given face, at the given location. Parameters ---------- mesh_ids: dict Dictionary containing the `polygon` and `line` tkinter canvas identifiers that make up the mesh for the given face face_index: int The face index within the frame for the given face detected_face: :class:`~lib.align.DetectedFace` The detected face object that contains the landmarks for generating the mesh top_left: tuple The (x, y) top left co-ordinates of the mesh's bounding box
348
def _get_curr_status(self) -> Tuple[DeploymentStatusInfo, bool]: # TODO(edoakes): we could make this more efficient in steady-state by # having a "healthy" flag that gets flipped if an update or replica # failure happens. target_version = self._target_version target_replica_count = self._target_replicas all_running_replica_cnt = self._replicas.count(states=[ReplicaState.RUNNING]) running_at_target_version_replica_cnt = self._replicas.count( states=[ReplicaState.RUNNING], version=target_version ) failed_to_start_count = self._replica_constructor_retry_counter failed_to_start_threshold = min( MAX_DEPLOYMENT_CONSTRUCTOR_RETRY_COUNT, target_replica_count * 3 ) # Got to make a call to complete current deploy() goal after # start failure threshold reached, while we might still have # pending replicas in current goal. if ( failed_to_start_count >= failed_to_start_threshold and failed_to_start_threshold != 0 ): if running_at_target_version_replica_cnt > 0: # At least one RUNNING replica at target state, partial # success; We can stop tracking constructor failures and # leave it to the controller to fully scale to target # number of replicas and only return as completed once # reached target replica count self._replica_constructor_retry_counter = -1 else: return ( DeploymentStatusInfo( status=DeploymentStatus.FAILED, message=( "The Deployment constructor failed " f"{failed_to_start_count} times in a row. See " "logs for details." ), ), False, ) # If we have pending ops, the current goal is *not* ready. if ( self._replicas.count( states=[ ReplicaState.STARTING, ReplicaState.UPDATING, ReplicaState.RECOVERING, ReplicaState.STOPPING, ] ) == 0 ): # Check for deleting. if target_replica_count == 0 and all_running_replica_cnt == 0: return DeploymentStatusInfo(status=DeploymentStatus.UPDATING), True # Check for a non-zero number of deployments. elif target_replica_count == running_at_target_version_replica_cnt: return DeploymentStatusInfo(status=DeploymentStatus.RUNNING), False return ( DeploymentStatusInfo( status=DeploymentStatus.UPDATING, message=( f"Running replicas of target version: " f"{running_at_target_version_replica_cnt}, target " "replicas: {target_replica_count}" ), ), False, )
Get the current deployment status. Checks the difference between the target vs. running replica count for the target version. TODO(edoakes): we should report the status as FAILED if replicas are repeatedly failing health checks. Need a reasonable heuristic here. Returns: (DeploymentStatusInfo, was_deleted)
42
248
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_curr_status(self) -> Tuple[DeploymentStatusInfo, bool]: # TODO(edoakes): we could make this more efficient in steady-state by # having a "healthy" flag that gets flipped if an update or replica # failure happens. target_version = self._target_version target_replica_count = self._target_replicas all_running_replica_cnt = self._replicas.count(states=[ReplicaState.RUNNING]) running_at_target_version_replica_cnt = self._replicas.count( states=[ReplicaState.RUNNING], version=target_version ) failed_to_start_count = self._replica_constructor_retry_counter failed_to_start_threshold = min( MAX_DEPLOYMENT_CONSTRUCTOR_RETRY_COUNT, target_replica_count * 3 ) # Got to make a call to complete current deploy() goal after # start failure threshold reached, while we might still have # pending replicas in current goal. if ( failed_to_start_count >= failed_to_start_threshold and failed_to_start_threshold != 0 ): if running_at_target_version_replica_cnt > 0: # At least one RUNNING replica at target state, partial # success; We can stop tracking constructor failures and # leave it to the controller to fully scale to target # number of replicas and only return as completed once # reached target replica count self._replica_constructor_retry_counter = -1 else: return ( DeploymentStatusInfo( status=DeploymentStatus.FAILED, message=( "The Deployment constructor failed " f"{failed_to_start_count} times in a row. See " "logs for details." ), ), False, ) # If we have pending ops, the current goal is *not* ready. if ( self._replicas.count( states=[ ReplicaState.STARTING, ReplicaState.UPDATING, ReplicaState.RECOVERING, ReplicaState.STOPPING, ] ) == 0 ): # Check for deleting. if target_replica_count == 0 and all_running_replica_cnt == 0: return DeploymentStatusInfo(status=DeploymentStatus.UPDATING), True # Check for a non-zero number of deployments. elif target_replica_count == running_at_target_version_replica_cnt: return DeploymentStatusInfo(status=DeploymentStatus.RUNNING), False return ( DeploymentStatusInfo( status=DeploymentStatus.UPDATING, message=( f"Running replicas of target version: " f"{running_at_target_version_replica_cnt}, target " "replicas: {target_replica_count}" ), ), False, ) ``` ###Assistant : Get the current deployment status. Checks the difference between the target vs. running replica count for the target version. TODO(edoakes): we should report the status as FAILED if replicas are repeatedly failing health checks. Need a reasonable heuristic here. Returns: (DeploymentStatusInfo, was_deleted)
349
def generate_square_subsequent_mask(self, length): return paddle.tensor.triu( (paddle.ones( (length, length), dtype=paddle.get_default_dtype()) * -np.inf), 1)
Generate a square mask for the sequence. The mask ensures that the predictions for position i can depend only on the known outputs at positions less than i. Parameters: length (int|Tensor): The length of sequence. Returns: Tensor: Generated square mask according to the given length. Examples: .. code-block:: python import paddle from paddle.nn.layer.transformer import Transformer length = 5 d_model, n_head, dim_feedforward = 8, 4, 64 transformer_paddle = Transformer( d_model, n_head, dim_feedforward=dim_feedforward) mask = transformer_paddle.generate_square_subsequent_mask(length) print(mask) # [[ 0. -inf -inf -inf -inf] # [ 0. 0. -inf -inf -inf] # [ 0. 0. 0. -inf -inf] # [ 0. 0. 0. 0. -inf] # [ 0. 0. 0. 0. 0.]]
110
12
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def generate_square_subsequent_mask(self, length): return paddle.tensor.triu( (paddle.ones( (length, length), dtype=paddle.get_default_dtype()) * -np.inf), 1) ``` ###Assistant : Generate a square mask for the sequence. The mask ensures that the predictions for position i can depend only on the known outputs at positions less than i. Parameters: length (int|Tensor): The length of sequence. Returns: Tensor: Generated square mask according to the given length. Examples: .. code-block:: python import paddle from paddle.nn.layer.transformer import Transformer length = 5 d_model, n_head, dim_feedforward = 8, 4, 64 transformer_paddle = Transformer( d_model, n_head, dim_feedforward=dim_feedforward) mask = transformer_paddle.generate_square_subsequent_mask(length) print(mask) # [[ 0. -inf -inf -inf -inf] # [ 0. 0. -inf -inf -inf] # [ 0. 0. 0. -inf -inf] # [ 0. 0. 0. 0. -inf] # [ 0. 0. 0. 0. 0.]]
350
def find_requirement(self, req, upgrade): # type: (InstallRequirement, bool) -> Optional[InstallationCandidate] hashes = req.hashes(trust_internet=False) best_candidate_result = self.find_best_candidate( req.name, specifier=req.specifier, hashes=hashes, ) best_candidate = best_candidate_result.best_candidate installed_version = None # type: Optional[_BaseVersion] if req.satisfied_by is not None: installed_version = parse_version(req.satisfied_by.version)
Try to find a Link matching req Expects req, an InstallRequirement and upgrade, a boolean Returns a InstallationCandidate if found, Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise
25
37
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def find_requirement(self, req, upgrade): # type: (InstallRequirement, bool) -> Optional[InstallationCandidate] hashes = req.hashes(trust_internet=False) best_candidate_result = self.find_best_candidate( req.name, specifier=req.specifier, hashes=hashes, ) best_candidate = best_candidate_result.best_candidate installed_version = None # type: Optional[_BaseVersion] if req.satisfied_by is not None: installed_version = parse_version(req.satisfied_by.version) ``` ###Assistant : Try to find a Link matching req Expects req, an InstallRequirement and upgrade, a boolean Returns a InstallationCandidate if found, Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise
351
def wrap(self, source, outfile): if self.wrapcode: return self._wrap_div(self._wrap_pre(self._wrap_code(source))) else: return self._wrap_div(self._wrap_pre(source))
Wrap the ``source``, which is a generator yielding individual lines, in custom generators. See docstring for `format`. Can be overridden.
20
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def wrap(self, source, outfile): if self.wrapcode: return self._wrap_div(self._wrap_pre(self._wrap_code(source))) else: return self._wrap_div(self._wrap_pre(source)) ``` ###Assistant : Wrap the ``source``, which is a generator yielding individual lines, in custom generators. See docstring for `format`. Can be overridden.
352
def get_assessment_criteria(course): return frappe.get_all( "Course Assessment Criteria", fields=["assessment_criteria", "weightage"], filters={"parent": course}, order_by="idx", ) @frappe.whitelist()
Returns Assessmemt Criteria and their Weightage from Course Master. :param Course: Course
12
14
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_assessment_criteria(course): return frappe.get_all( "Course Assessment Criteria", fields=["assessment_criteria", "weightage"], filters={"parent": course}, order_by="idx", ) @frappe.whitelist() ``` ###Assistant : Returns Assessmemt Criteria and their Weightage from Course Master. :param Course: Course
353
def rm_filesystems(name, device, config="/etc/filesystems"): modified = False view_lines = [] if "AIX" not in __grains__["kernel"]: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in fsys_filedict.items(): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except OSError as exc: raise CommandExecutionError("Couldn't read from {}: {}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, "wb") as ofile: for fsys_view in view_lines: entry = fsys_view[1] list_strgs = _FileSystemsEntry.dict_to_list_lines(entry) ofile.writelines(salt.utils.data.encode(list_strgs)) except OSError as exc: raise CommandExecutionError("Couldn't write to {}: {}".format(config, exc)) except Exception as exc: raise CommandExecutionError("rm_filesystems error exception {exc}") return modified
.. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg
20
93
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def rm_filesystems(name, device, config="/etc/filesystems"): modified = False view_lines = [] if "AIX" not in __grains__["kernel"]: return modified criteria = _FileSystemsEntry(name=name, dev=device) try: fsys_filedict = _filesystems(config, False) for fsys_view in fsys_filedict.items(): try: if criteria.match(fsys_view): modified = True else: view_lines.append(fsys_view) except _FileSystemsEntry.ParseError: view_lines.append(fsys_view) except OSError as exc: raise CommandExecutionError("Couldn't read from {}: {}".format(config, exc)) if modified: try: with salt.utils.files.fopen(config, "wb") as ofile: for fsys_view in view_lines: entry = fsys_view[1] list_strgs = _FileSystemsEntry.dict_to_list_lines(entry) ofile.writelines(salt.utils.data.encode(list_strgs)) except OSError as exc: raise CommandExecutionError("Couldn't write to {}: {}".format(config, exc)) except Exception as exc: raise CommandExecutionError("rm_filesystems error exception {exc}") return modified ``` ###Assistant : .. versionadded:: 2018.3.3 Remove the mount point from the filesystems CLI Example: .. code-block:: bash salt '*' mount.rm_filesystems /mnt/foo /dev/sdg
354
def complete_graph(n, create_using=None): _, nodes = n G = empty_graph(nodes, create_using) if len(nodes) > 1: if G.is_directed(): edges = itertools.permutations(nodes, 2) else: edges = itertools.combinations(nodes, 2) G.add_edges_from(edges) return G
Return the complete graph `K_n` with n nodes. A complete graph on `n` nodes means that all pairs of distinct nodes have an edge connecting them. Parameters ---------- n : int or iterable container of nodes If n is an integer, nodes are from range(n). If n is a container of nodes, those nodes appear in the graph. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Examples -------- >>> G = nx.complete_graph(9) >>> len(G) 9 >>> G.size() 36 >>> G = nx.complete_graph(range(11, 14)) >>> list(G.nodes()) [11, 12, 13] >>> G = nx.complete_graph(4, nx.DiGraph()) >>> G.is_directed() True
106
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def complete_graph(n, create_using=None): _, nodes = n G = empty_graph(nodes, create_using) if len(nodes) > 1: if G.is_directed(): edges = itertools.permutations(nodes, 2) else: edges = itertools.combinations(nodes, 2) G.add_edges_from(edges) return G ``` ###Assistant : Return the complete graph `K_n` with n nodes. A complete graph on `n` nodes means that all pairs of distinct nodes have an edge connecting them. Parameters ---------- n : int or iterable container of nodes If n is an integer, nodes are from range(n). If n is a container of nodes, those nodes appear in the graph. create_using : NetworkX graph constructor, optional (default=nx.Graph) Graph type to create. If graph instance, then cleared before populated. Examples -------- >>> G = nx.complete_graph(9) >>> len(G) 9 >>> G.size() 36 >>> G = nx.complete_graph(range(11, 14)) >>> list(G.nodes()) [11, 12, 13] >>> G = nx.complete_graph(4, nx.DiGraph()) >>> G.is_directed() True
355
def fit_predict(self, X, y=None, **fit_params): self._validate_params() fit_params_steps = self._check_fit_params(**fit_params) Xt = self._fit(X, y, **fit_params_steps) fit_params_last_step = fit_params_steps[self.steps[-1][0]] with _print_elapsed_time("Pipeline", self._log_message(len(self.steps) - 1)): y_pred = self.steps[-1][1].fit_predict(Xt, y, **fit_params_last_step) return y_pred
Transform the data, and apply `fit_predict` with the final estimator. Call `fit_transform` of each transformer in the pipeline. The transformed data are finally passed to the final estimator that calls `fit_predict` method. Only valid if the final estimator implements `fit_predict`. Parameters ---------- X : iterable Training data. Must fulfill input requirements of first step of the pipeline. y : iterable, default=None Training targets. Must fulfill label requirements for all steps of the pipeline. **fit_params : dict of string -> object Parameters passed to the ``fit`` method of each step, where each parameter name is prefixed such that parameter ``p`` for step ``s`` has key ``s__p``. Returns ------- y_pred : ndarray Result of calling `fit_predict` on the final estimator.
118
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def fit_predict(self, X, y=None, **fit_params): self._validate_params() fit_params_steps = self._check_fit_params(**fit_params) Xt = self._fit(X, y, **fit_params_steps) fit_params_last_step = fit_params_steps[self.steps[-1][0]] with _print_elapsed_time("Pipeline", self._log_message(len(self.steps) - 1)): y_pred = self.steps[-1][1].fit_predict(Xt, y, **fit_params_last_step) return y_pred ``` ###Assistant : Transform the data, and apply `fit_predict` with the final estimator. Call `fit_transform` of each transformer in the pipeline. The transformed data are finally passed to the final estimator that calls `fit_predict` method. Only valid if the final estimator implements `fit_predict`. Parameters ---------- X : iterable Training data. Must fulfill input requirements of first step of the pipeline. y : iterable, default=None Training targets. Must fulfill label requirements for all steps of the pipeline. **fit_params : dict of string -> object Parameters passed to the ``fit`` method of each step, where each parameter name is prefixed such that parameter ``p`` for step ``s`` has key ``s__p``. Returns ------- y_pred : ndarray Result of calling `fit_predict` on the final estimator.
356
def test_issue4849(entity_ruler_factory): nlp = English() patterns = [ {"label": "PERSON", "pattern": "joe biden", "id": "joe-biden"}, {"label": "PERSON", "pattern": "bernie sanders", "id": "bernie-sanders"}, ] ruler = nlp.add_pipe( entity_ruler_factory, name="entity_ruler", config={"phrase_matcher_attr": "LOWER"}, ) ruler.add_patterns(patterns) text = # USING 1 PROCESS count_ents = 0 for doc in nlp.pipe([text], n_process=1): count_ents += len([ent for ent in doc.ents if ent.ent_id > 0]) assert count_ents == 2 # USING 2 PROCESSES if isinstance(get_current_ops, NumpyOps): count_ents = 0 for doc in nlp.pipe([text], n_process=2): count_ents += len([ent for ent in doc.ents if ent.ent_id > 0]) assert count_ents == 2 @pytest.mark.issue(5918) @pytest.mark.parametrize("entity_ruler_factory", ENTITY_RULERS)
The left is starting to take aim at Democratic front-runner Joe Biden. Sen. Bernie Sanders joined in her criticism: "There is no 'middle ground' when it comes to climate policy."
30
94
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_issue4849(entity_ruler_factory): nlp = English() patterns = [ {"label": "PERSON", "pattern": "joe biden", "id": "joe-biden"}, {"label": "PERSON", "pattern": "bernie sanders", "id": "bernie-sanders"}, ] ruler = nlp.add_pipe( entity_ruler_factory, name="entity_ruler", config={"phrase_matcher_attr": "LOWER"}, ) ruler.add_patterns(patterns) text = # USING 1 PROCESS count_ents = 0 for doc in nlp.pipe([text], n_process=1): count_ents += len([ent for ent in doc.ents if ent.ent_id > 0]) assert count_ents == 2 # USING 2 PROCESSES if isinstance(get_current_ops, NumpyOps): count_ents = 0 for doc in nlp.pipe([text], n_process=2): count_ents += len([ent for ent in doc.ents if ent.ent_id > 0]) assert count_ents == 2 @pytest.mark.issue(5918) @pytest.mark.parametrize("entity_ruler_factory", ENTITY_RULERS) ``` ###Assistant : The left is starting to take aim at Democratic front-runner Joe Biden. Sen. Bernie Sanders joined in her criticism: "There is no 'middle ground' when it comes to climate policy."
357
def get_serializer_context(self): context = super().get_serializer_context() if hasattr(self.queryset.model, 'custom_fields'): content_type = ContentType.objects.get_for_model(self.queryset.model) context.update({ 'custom_fields': content_type.custom_fields.all(), }) return context
For models which support custom fields, populate the `custom_fields` context.
10
17
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_serializer_context(self): context = super().get_serializer_context() if hasattr(self.queryset.model, 'custom_fields'): content_type = ContentType.objects.get_for_model(self.queryset.model) context.update({ 'custom_fields': content_type.custom_fields.all(), }) return context ``` ###Assistant : For models which support custom fields, populate the `custom_fields` context.
358
def execute (func, args, msg=None, verbose=0, dry_run=0): if msg is None: msg = "%s%r" % (func.__name__, args) if msg[-2:] == ',)': # correct for singleton tuple msg = msg[0:-2] + ')' log.info(msg) if not dry_run: func(*args)
Perform some action that affects the outside world (eg. by writing to the filesystem). Such actions are special because they are disabled by the 'dry_run' flag. This method takes care of all that bureaucracy for you; all you have to do is supply the function to call and an argument tuple for it (to embody the "external action" being performed), and an optional message to print.
66
36
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def execute (func, args, msg=None, verbose=0, dry_run=0): if msg is None: msg = "%s%r" % (func.__name__, args) if msg[-2:] == ',)': # correct for singleton tuple msg = msg[0:-2] + ')' log.info(msg) if not dry_run: func(*args) ``` ###Assistant : Perform some action that affects the outside world (eg. by writing to the filesystem). Such actions are special because they are disabled by the 'dry_run' flag. This method takes care of all that bureaucracy for you; all you have to do is supply the function to call and an argument tuple for it (to embody the "external action" being performed), and an optional message to print.
359
def call(self, features, cols_to_output_tensors=None, training=None): if training is None: training = backend.learning_phase() if not isinstance(features, dict): raise ValueError( "We expected a dictionary here. Instead we got: ", features ) transformation_cache = ( tf.__internal__.feature_column.FeatureTransformationCache(features) ) output_tensors = [] for column in self._feature_columns: with backend.name_scope(column.name): try: tensor = column.get_dense_tensor( transformation_cache, self._state_manager, training=training, ) except TypeError: tensor = column.get_dense_tensor( transformation_cache, self._state_manager ) processed_tensors = self._process_dense_tensor(column, tensor) if cols_to_output_tensors is not None: cols_to_output_tensors[column] = processed_tensors output_tensors.append(processed_tensors) return self._verify_and_concat_tensors(output_tensors)
Returns a dense tensor corresponding to the `feature_columns`. Example usage: >>> t1 = tf.feature_column.embedding_column( ... tf.feature_column.categorical_column_with_hash_bucket("t1", 2), ... dimension=8) >>> t2 = tf.feature_column.numeric_column('t2') >>> feature_layer = tf.compat.v1.keras.layers.DenseFeatures([t1, t2]) >>> features = {"t1": tf.constant(["a", "b"]), "t2": tf.constant([1, 2])} >>> dense_tensor = feature_layer(features, training=True) Args: features: A mapping from key to tensors. `FeatureColumn`s look up via these keys. For example `numeric_column('price')` will look at 'price' key in this dict. Values can be a `SparseTensor` or a `Tensor` depends on corresponding `FeatureColumn`. cols_to_output_tensors: If not `None`, this will be filled with a dict mapping feature columns to output tensors created. training: Python boolean or None, indicating whether to the layer is being run in training mode. This argument is passed to the call method of any `FeatureColumn` that takes a `training` argument. For example, if a `FeatureColumn` performed dropout, the column could expose a `training` argument to control whether the dropout should be applied. If `None`, defaults to `tf.keras.backend.learning_phase()`. Returns: A `Tensor` which represents input layer of a model. Its shape is (batch_size, first_layer_dimension) and its dtype is `float32`. first_layer_dimension is determined based on given `feature_columns`. Raises: ValueError: If features are not a dictionary.
191
74
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def call(self, features, cols_to_output_tensors=None, training=None): if training is None: training = backend.learning_phase() if not isinstance(features, dict): raise ValueError( "We expected a dictionary here. Instead we got: ", features ) transformation_cache = ( tf.__internal__.feature_column.FeatureTransformationCache(features) ) output_tensors = [] for column in self._feature_columns: with backend.name_scope(column.name): try: tensor = column.get_dense_tensor( transformation_cache, self._state_manager, training=training, ) except TypeError: tensor = column.get_dense_tensor( transformation_cache, self._state_manager ) processed_tensors = self._process_dense_tensor(column, tensor) if cols_to_output_tensors is not None: cols_to_output_tensors[column] = processed_tensors output_tensors.append(processed_tensors) return self._verify_and_concat_tensors(output_tensors) ``` ###Assistant : Returns a dense tensor corresponding to the `feature_columns`. Example usage: >>> t1 = tf.feature_column.embedding_column( ... tf.feature_column.categorical_column_with_hash_bucket("t1", 2), ... dimension=8) >>> t2 = tf.feature_column.numeric_column('t2') >>> feature_layer = tf.compat.v1.keras.layers.DenseFeatures([t1, t2]) >>> features = {"t1": tf.constant(["a", "b"]), "t2": tf.constant([1, 2])} >>> dense_tensor = feature_layer(features, training=True) Args: features: A mapping from key to tensors. `FeatureColumn`s look up via these keys. For example `numeric_column('price')` will look at 'price' key in this dict. Values can be a `SparseTensor` or a `Tensor` depends on corresponding `FeatureColumn`. cols_to_output_tensors: If not `None`, this will be filled with a dict mapping feature columns to output tensors created. training: Python boolean or None, indicating whether to the layer is being run in training mode. This argument is passed to the call method of any `FeatureColumn` that takes a `training` argument. For example, if a `FeatureColumn` performed dropout, the column could expose a `training` argument to control whether the dropout should be applied. If `None`, defaults to `tf.keras.backend.learning_phase()`. Returns: A `Tensor` which represents input layer of a model. Its shape is (batch_size, first_layer_dimension) and its dtype is `float32`. first_layer_dimension is determined based on given `feature_columns`. Raises: ValueError: If features are not a dictionary.
360
def patch_pickle() -> Iterator[None]: orig_loads = pkl.loads try: setattr(pkl, "loads", loads) yield finally: setattr(pkl, "loads", orig_loads)
Temporarily patch pickle to use our unpickler.
7
16
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def patch_pickle() -> Iterator[None]: orig_loads = pkl.loads try: setattr(pkl, "loads", loads) yield finally: setattr(pkl, "loads", orig_loads) ``` ###Assistant : Temporarily patch pickle to use our unpickler.
361
def get_filesystem_type(filepath): # We import it locally so that click autocomplete works import psutil root_type = "unknown" for part in psutil.disk_partitions(): if part.mountpoint == '/': root_type = part.fstype continue if filepath.startswith(part.mountpoint): return part.fstype return root_type
Determine the type of filesystem used - we might want to use different parameters if tmpfs is used. :param filepath: path to check :return: type of filesystem
27
35
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_filesystem_type(filepath): # We import it locally so that click autocomplete works import psutil root_type = "unknown" for part in psutil.disk_partitions(): if part.mountpoint == '/': root_type = part.fstype continue if filepath.startswith(part.mountpoint): return part.fstype return root_type ``` ###Assistant : Determine the type of filesystem used - we might want to use different parameters if tmpfs is used. :param filepath: path to check :return: type of filesystem
362
def panther_similarity(G, source, k=5, path_length=5, c=0.5, delta=0.1, eps=None): r import numpy as np num_nodes = G.number_of_nodes() if num_nodes < k: warnings.warn( f"Number of nodes is {num_nodes}, but requested k is {k}. " "Setting k to number of nodes." ) k = num_nodes # According to [1], they empirically determined # a good value for ``eps`` to be sqrt( 1 / |E| ) if eps is None: eps = np.sqrt(1.0 / G.number_of_edges()) inv_node_map = {name: index for index, name in enumerate(G.nodes)} node_map = np.array(G) # Calculate the sample size ``R`` for how many paths # to randomly generate t_choose_2 = math.comb(path_length, 2) sample_size = int((c / eps**2) * (np.log2(t_choose_2) + 1 + np.log(1 / delta))) index_map = {} _ = list( generate_random_paths( G, sample_size, path_length=path_length, index_map=index_map ) ) S = np.zeros(num_nodes) inv_sample_size = 1 / sample_size source_paths = set(index_map[source]) # Calculate the path similarities # between ``source`` (v) and ``node`` (v_j) # using our inverted index mapping of # vertices to paths for node, paths in index_map.items(): # Only consider paths where both # ``node`` and ``source`` are present common_paths = source_paths.intersection(paths) S[inv_node_map[node]] = len(common_paths) * inv_sample_size # Retrieve top ``k`` similar # Note: the below performed anywhere from 4-10x faster # (depending on input sizes) vs the equivalent ``np.argsort(S)[::-1]`` top_k_unsorted = np.argpartition(S, -k)[-k:] top_k_sorted = top_k_unsorted[np.argsort(S[top_k_unsorted])][::-1] # Add back the similarity scores top_k_sorted_names = map(lambda n: node_map[n], top_k_sorted) top_k_with_val = dict(zip(top_k_sorted_names, S[top_k_sorted])) # Remove the self-similarity top_k_with_val.pop(source, None) return top_k_with_val
Returns the Panther similarity of nodes in the graph `G` to node ``v``. Panther is a similarity metric that says "two objects are considered to be similar if they frequently appear on the same paths." [1]_. Parameters ---------- G : NetworkX graph A NetworkX graph source : node Source node for which to find the top `k` similar other nodes k : int (default = 5) The number of most similar nodes to return path_length : int (default = 5) How long the randomly generated paths should be (``T`` in [1]_) c : float (default = 0.5) A universal positive constant used to scale the number of sample random paths to generate. delta : float (default = 0.1) The probability that the similarity $S$ is not an epsilon-approximation to (R, phi), where $R$ is the number of random paths and $\phi$ is the probability that an element sampled from a set $A \subseteq D$, where $D$ is the domain. eps : float or None (default = None) The error bound. Per [1]_, a good value is ``sqrt(1/|E|)``. Therefore, if no value is provided, the recommended computed value will be used. Returns ------- similarity : dictionary Dictionary of nodes to similarity scores (as floats). Note: the self-similarity (i.e., ``v``) will not be included in the returned dictionary. Examples -------- >>> G = nx.star_graph(10) >>> sim = nx.panther_similarity(G, 0) References ---------- .. [1] Zhang, J., Tang, J., Ma, C., Tong, H., Jing, Y., & Li, J. Panther: Fast top-k similarity search on large networks. In Proceedings of the ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (Vol. 2015-August, pp. 1445–1454). Association for Computing Machinery. https://doi.org/10.1145/2783258.2783267.
275
240
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def panther_similarity(G, source, k=5, path_length=5, c=0.5, delta=0.1, eps=None): r import numpy as np num_nodes = G.number_of_nodes() if num_nodes < k: warnings.warn( f"Number of nodes is {num_nodes}, but requested k is {k}. " "Setting k to number of nodes." ) k = num_nodes # According to [1], they empirically determined # a good value for ``eps`` to be sqrt( 1 / |E| ) if eps is None: eps = np.sqrt(1.0 / G.number_of_edges()) inv_node_map = {name: index for index, name in enumerate(G.nodes)} node_map = np.array(G) # Calculate the sample size ``R`` for how many paths # to randomly generate t_choose_2 = math.comb(path_length, 2) sample_size = int((c / eps**2) * (np.log2(t_choose_2) + 1 + np.log(1 / delta))) index_map = {} _ = list( generate_random_paths( G, sample_size, path_length=path_length, index_map=index_map ) ) S = np.zeros(num_nodes) inv_sample_size = 1 / sample_size source_paths = set(index_map[source]) # Calculate the path similarities # between ``source`` (v) and ``node`` (v_j) # using our inverted index mapping of # vertices to paths for node, paths in index_map.items(): # Only consider paths where both # ``node`` and ``source`` are present common_paths = source_paths.intersection(paths) S[inv_node_map[node]] = len(common_paths) * inv_sample_size # Retrieve top ``k`` similar # Note: the below performed anywhere from 4-10x faster # (depending on input sizes) vs the equivalent ``np.argsort(S)[::-1]`` top_k_unsorted = np.argpartition(S, -k)[-k:] top_k_sorted = top_k_unsorted[np.argsort(S[top_k_unsorted])][::-1] # Add back the similarity scores top_k_sorted_names = map(lambda n: node_map[n], top_k_sorted) top_k_with_val = dict(zip(top_k_sorted_names, S[top_k_sorted])) # Remove the self-similarity top_k_with_val.pop(source, None) return top_k_with_val ``` ###Assistant : Returns the Panther similarity of nodes in the graph `G` to node ``v``. Panther is a similarity metric that says "two objects are considered to be similar if they frequently appear on the same paths." [1]_. Parameters ---------- G : NetworkX graph A NetworkX graph source : node Source node for which to find the top `k` similar other nodes k : int (default = 5) The number of most similar nodes to return path_length : int (default = 5) How long the randomly generated paths should be (``T`` in [1]_) c : float (default = 0.5) A universal positive constant used to scale the number of sample random paths to generate. delta : float (default = 0.1) The probability that the similarity $S$ is not an epsilon-approximation to (R, phi), where $R$ is the number of random paths and $\phi$ is the probability that an element sampled from a set $A \subseteq D$, where $D$ is the domain. eps : float or None (default = None) The error bound. Per [1]_, a good value is ``sqrt(1/|E|)``. Therefore, if no value is provided, the recommended computed value will be used. Returns ------- similarity : dictionary Dictionary of nodes to similarity scores (as floats). Note: the self-similarity (i.e., ``v``) will not be included in the returned dictionary. Examples -------- >>> G = nx.star_graph(10) >>> sim = nx.panther_similarity(G, 0) References ---------- .. [1] Zhang, J., Tang, J., Ma, C., Tong, H., Jing, Y., & Li, J. Panther: Fast top-k similarity search on large networks. In Proceedings of the ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (Vol. 2015-August, pp. 1445–1454). Association for Computing Machinery. https://doi.org/10.1145/2783258.2783267.
363
def _phonemize_preprocess(self, text) -> Tuple[List[str], List]: text = text.strip() if self._keep_puncs: # a tuple (text, punctuation marks) return self._punctuator.strip_to_restore(text) return [self._punctuator.strip(text)], []
Preprocess the text before phonemization 1. remove spaces 2. remove punctuation Override this if you need a different behaviour
19
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _phonemize_preprocess(self, text) -> Tuple[List[str], List]: text = text.strip() if self._keep_puncs: # a tuple (text, punctuation marks) return self._punctuator.strip_to_restore(text) return [self._punctuator.strip(text)], [] ``` ###Assistant : Preprocess the text before phonemization 1. remove spaces 2. remove punctuation Override this if you need a different behaviour
364
def ensure_pathy(path): from pathy import Pathy # noqa: F811 return Pathy.fluid(path)
Temporary helper to prevent importing Pathy globally (which can cause slow and annoying Google Cloud warning).
16
11
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def ensure_pathy(path): from pathy import Pathy # noqa: F811 return Pathy.fluid(path) ``` ###Assistant : Temporary helper to prevent importing Pathy globally (which can cause slow and annoying Google Cloud warning).
365
def index(self, request, extra_context=None): app_list = self.get_app_list(request) context = { **self.each_context(request), "title": self.index_title, "subtitle": None, "app_list": app_list, **(extra_context or {}), } request.current_app = self.name return TemplateResponse( request, self.index_template or "admin/index.html", context )
Display the main admin index page, which lists all of the installed apps that have been registered in this site.
20
32
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def index(self, request, extra_context=None): app_list = self.get_app_list(request) context = { **self.each_context(request), "title": self.index_title, "subtitle": None, "app_list": app_list, **(extra_context or {}), } request.current_app = self.name return TemplateResponse( request, self.index_template or "admin/index.html", context ) ``` ###Assistant : Display the main admin index page, which lists all of the installed apps that have been registered in this site.
366
def generate_config_from_template(config_dir, config_path, environ, ownership): for v in ("SYNAPSE_SERVER_NAME", "SYNAPSE_REPORT_STATS"): if v not in environ: error( "Environment variable '%s' is mandatory when generating a config file." % (v,) ) # populate some params from data files (if they exist, else create new ones) environ = environ.copy() secrets = { "registration": "SYNAPSE_REGISTRATION_SHARED_SECRET", "macaroon": "SYNAPSE_MACAROON_SECRET_KEY", } for name, secret in secrets.items(): if secret not in environ: filename = "/data/%s.%s.key" % (environ["SYNAPSE_SERVER_NAME"], name) # if the file already exists, load in the existing value; otherwise, # generate a new secret and write it to a file if os.path.exists(filename): log("Reading %s from %s" % (secret, filename)) with open(filename) as handle: value = handle.read() else: log("Generating a random secret for {}".format(secret)) value = codecs.encode(os.urandom(32), "hex").decode() with open(filename, "w") as handle: handle.write(value) environ[secret] = value environ["SYNAPSE_APPSERVICES"] = glob.glob("/data/appservices/*.yaml") if not os.path.exists(config_dir): os.mkdir(config_dir) # Convert SYNAPSE_NO_TLS to boolean if exists if "SYNAPSE_NO_TLS" in environ: tlsanswerstring = str.lower(environ["SYNAPSE_NO_TLS"]) if tlsanswerstring in ("true", "on", "1", "yes"): environ["SYNAPSE_NO_TLS"] = True else: if tlsanswerstring in ("false", "off", "0", "no"): environ["SYNAPSE_NO_TLS"] = False else: error( 'Environment variable "SYNAPSE_NO_TLS" found but value "' + tlsanswerstring + '" unrecognized; exiting.' ) if "SYNAPSE_LOG_CONFIG" not in environ: environ["SYNAPSE_LOG_CONFIG"] = config_dir + "/log.config" log("Generating synapse config file " + config_path) convert("/conf/homeserver.yaml", config_path, environ) log_config_file = environ["SYNAPSE_LOG_CONFIG"] log("Generating log config file " + log_config_file) convert("/conf/log.config", log_config_file, environ) # Hopefully we already have a signing key, but generate one if not. args = [ sys.executable, "-m", "synapse.app.homeserver", "--config-path", config_path, # tell synapse to put generated keys in /data rather than /compiled "--keys-directory", config_dir, "--generate-keys", ] if ownership is not None: log(f"Setting ownership on /data to {ownership}") subprocess.check_output(["chown", "-R", ownership, "/data"]) args = ["gosu", ownership] + args subprocess.check_output(args)
Generate a homeserver.yaml from environment variables Args: config_dir (str): where to put generated config files config_path (str): where to put the main config file environ (dict): environment dictionary ownership (str|None): "<user>:<group>" string which will be used to set ownership of the generated configs. If None, ownership will not change.
49
279
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def generate_config_from_template(config_dir, config_path, environ, ownership): for v in ("SYNAPSE_SERVER_NAME", "SYNAPSE_REPORT_STATS"): if v not in environ: error( "Environment variable '%s' is mandatory when generating a config file." % (v,) ) # populate some params from data files (if they exist, else create new ones) environ = environ.copy() secrets = { "registration": "SYNAPSE_REGISTRATION_SHARED_SECRET", "macaroon": "SYNAPSE_MACAROON_SECRET_KEY", } for name, secret in secrets.items(): if secret not in environ: filename = "/data/%s.%s.key" % (environ["SYNAPSE_SERVER_NAME"], name) # if the file already exists, load in the existing value; otherwise, # generate a new secret and write it to a file if os.path.exists(filename): log("Reading %s from %s" % (secret, filename)) with open(filename) as handle: value = handle.read() else: log("Generating a random secret for {}".format(secret)) value = codecs.encode(os.urandom(32), "hex").decode() with open(filename, "w") as handle: handle.write(value) environ[secret] = value environ["SYNAPSE_APPSERVICES"] = glob.glob("/data/appservices/*.yaml") if not os.path.exists(config_dir): os.mkdir(config_dir) # Convert SYNAPSE_NO_TLS to boolean if exists if "SYNAPSE_NO_TLS" in environ: tlsanswerstring = str.lower(environ["SYNAPSE_NO_TLS"]) if tlsanswerstring in ("true", "on", "1", "yes"): environ["SYNAPSE_NO_TLS"] = True else: if tlsanswerstring in ("false", "off", "0", "no"): environ["SYNAPSE_NO_TLS"] = False else: error( 'Environment variable "SYNAPSE_NO_TLS" found but value "' + tlsanswerstring + '" unrecognized; exiting.' ) if "SYNAPSE_LOG_CONFIG" not in environ: environ["SYNAPSE_LOG_CONFIG"] = config_dir + "/log.config" log("Generating synapse config file " + config_path) convert("/conf/homeserver.yaml", config_path, environ) log_config_file = environ["SYNAPSE_LOG_CONFIG"] log("Generating log config file " + log_config_file) convert("/conf/log.config", log_config_file, environ) # Hopefully we already have a signing key, but generate one if not. args = [ sys.executable, "-m", "synapse.app.homeserver", "--config-path", config_path, # tell synapse to put generated keys in /data rather than /compiled "--keys-directory", config_dir, "--generate-keys", ] if ownership is not None: log(f"Setting ownership on /data to {ownership}") subprocess.check_output(["chown", "-R", ownership, "/data"]) args = ["gosu", ownership] + args subprocess.check_output(args) ``` ###Assistant : Generate a homeserver.yaml from environment variables Args: config_dir (str): where to put generated config files config_path (str): where to put the main config file environ (dict): environment dictionary ownership (str|None): "<user>:<group>" string which will be used to set ownership of the generated configs. If None, ownership will not change.
367
def donation_vector(donate_argnums, args, kwargs) -> Tuple[bool, ...]: res: List[bool] = [] for i, arg in enumerate(args): donate = bool(i in donate_argnums) res.extend((donate,) * tree_structure(arg).num_leaves) res.extend((False,) * tree_structure(kwargs).num_leaves) return tuple(res)
Returns a tuple with a boolean value for each leaf in args.
12
29
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def donation_vector(donate_argnums, args, kwargs) -> Tuple[bool, ...]: res: List[bool] = [] for i, arg in enumerate(args): donate = bool(i in donate_argnums) res.extend((donate,) * tree_structure(arg).num_leaves) res.extend((False,) * tree_structure(kwargs).num_leaves) return tuple(res) ``` ###Assistant : Returns a tuple with a boolean value for each leaf in args.
368
def set_exception(self, exception): if self._state != _PENDING: raise exceptions.InvalidStateError(f'{self._state}: {self!r}') if isinstance(exception, type): exception = exception() if type(exception) is StopIteration: raise TypeError("StopIteration interacts badly with generators " "and cannot be raised into a Future") self._exception = exception self._state = _FINISHED self.__schedule_callbacks() self.__log_traceback = True
Mark the future done and set an exception. If the future is already done when this method is called, raises InvalidStateError.
21
44
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_exception(self, exception): if self._state != _PENDING: raise exceptions.InvalidStateError(f'{self._state}: {self!r}') if isinstance(exception, type): exception = exception() if type(exception) is StopIteration: raise TypeError("StopIteration interacts badly with generators " "and cannot be raised into a Future") self._exception = exception self._state = _FINISHED self.__schedule_callbacks() self.__log_traceback = True ``` ###Assistant : Mark the future done and set an exception. If the future is already done when this method is called, raises InvalidStateError.
369
def statistics(self, refresh=False, approximate=False): # Prepare array with arguments for capi function smin, smax, smean, sstd = c_double(), c_double(), c_double(), c_double() stats_args = [ self._ptr, c_int(approximate), byref(smin), byref(smax), byref(smean), byref(sstd), c_void_p(), c_void_p(), ] if refresh or self._stats_refresh: func = capi.compute_band_statistics else: # Add additional argument to force computation if there is no # existing PAM file to take the values from. force = True stats_args.insert(2, c_int(force)) func = capi.get_band_statistics # Computation of statistics fails for empty bands. try: func(*stats_args) result = smin.value, smax.value, smean.value, sstd.value except GDALException: result = (None, None, None, None) self._stats_refresh = False return result
Compute statistics on the pixel values of this band. The return value is a tuple with the following structure: (minimum, maximum, mean, standard deviation). If approximate=True, the statistics may be computed based on overviews or a subset of image tiles. If refresh=True, the statistics will be computed from the data directly, and the cache will be updated where applicable. For empty bands (where all pixel values are nodata), all statistics values are returned as None. For raster formats using Persistent Auxiliary Metadata (PAM) services, the statistics might be cached in an auxiliary file.
93
98
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def statistics(self, refresh=False, approximate=False): # Prepare array with arguments for capi function smin, smax, smean, sstd = c_double(), c_double(), c_double(), c_double() stats_args = [ self._ptr, c_int(approximate), byref(smin), byref(smax), byref(smean), byref(sstd), c_void_p(), c_void_p(), ] if refresh or self._stats_refresh: func = capi.compute_band_statistics else: # Add additional argument to force computation if there is no # existing PAM file to take the values from. force = True stats_args.insert(2, c_int(force)) func = capi.get_band_statistics # Computation of statistics fails for empty bands. try: func(*stats_args) result = smin.value, smax.value, smean.value, sstd.value except GDALException: result = (None, None, None, None) self._stats_refresh = False return result ``` ###Assistant : Compute statistics on the pixel values of this band. The return value is a tuple with the following structure: (minimum, maximum, mean, standard deviation). If approximate=True, the statistics may be computed based on overviews or a subset of image tiles. If refresh=True, the statistics will be computed from the data directly, and the cache will be updated where applicable. For empty bands (where all pixel values are nodata), all statistics values are returned as None. For raster formats using Persistent Auxiliary Metadata (PAM) services, the statistics might be cached in an auxiliary file.
370
def test_smaller_request_deduplicated(self) -> None: req1 = ensureDeferred( self.state_datastore._get_state_for_group_using_inflight_cache( 42, StateFilter.from_types((("test.type", None),)) ) ) self.pump(by=0.1) # This should have gone to the database self.assertEqual(len(self.get_state_group_calls), 1) self.assertFalse(req1.called) req2 = ensureDeferred( self.state_datastore._get_state_for_group_using_inflight_cache( 42, StateFilter.from_types((("test.type", "b"),)) ) ) self.pump(by=0.1) # No more calls should have gone to the database, because the second # request was already in the in-flight cache! self.assertEqual(len(self.get_state_group_calls), 1) self.assertFalse(req1.called) self.assertFalse(req2.called) groups, sf, d = self.get_state_group_calls[0] self.assertEqual(groups, (42,)) # The state filter is expanded internally for increased cache hit rate, # so we the database sees a wider state filter than requested. self.assertEqual(sf, ALL_NON_MEMBERS_STATE_FILTER) # Now we can complete the request self._complete_request_fake(groups, sf, d) self.assertEqual( self.get_success(req1), {("test.type", "a"): "AAA", ("test.type", "b"): "BBB"}, ) self.assertEqual(self.get_success(req2), {("test.type", "b"): "BBB"})
Tests that duplicate requests for state are deduplicated. This test: - requests some state (state group 42, 'all' state filter) - requests a subset of that state, before the first request finishes - checks to see that only one database query was made - completes the database query - checks that both requests see the correct retrieved state
58
116
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_smaller_request_deduplicated(self) -> None: req1 = ensureDeferred( self.state_datastore._get_state_for_group_using_inflight_cache( 42, StateFilter.from_types((("test.type", None),)) ) ) self.pump(by=0.1) # This should have gone to the database self.assertEqual(len(self.get_state_group_calls), 1) self.assertFalse(req1.called) req2 = ensureDeferred( self.state_datastore._get_state_for_group_using_inflight_cache( 42, StateFilter.from_types((("test.type", "b"),)) ) ) self.pump(by=0.1) # No more calls should have gone to the database, because the second # request was already in the in-flight cache! self.assertEqual(len(self.get_state_group_calls), 1) self.assertFalse(req1.called) self.assertFalse(req2.called) groups, sf, d = self.get_state_group_calls[0] self.assertEqual(groups, (42,)) # The state filter is expanded internally for increased cache hit rate, # so we the database sees a wider state filter than requested. self.assertEqual(sf, ALL_NON_MEMBERS_STATE_FILTER) # Now we can complete the request self._complete_request_fake(groups, sf, d) self.assertEqual( self.get_success(req1), {("test.type", "a"): "AAA", ("test.type", "b"): "BBB"}, ) self.assertEqual(self.get_success(req2), {("test.type", "b"): "BBB"}) ``` ###Assistant : Tests that duplicate requests for state are deduplicated. This test: - requests some state (state group 42, 'all' state filter) - requests a subset of that state, before the first request finishes - checks to see that only one database query was made - completes the database query - checks that both requests see the correct retrieved state
371
def get_observation(self, agent): speed = 0 distance = self._config["scenario_config"]["misc"]["max_distance"] if agent in self.simulation.veh_subscriptions: speed = round( self.simulation.veh_subscriptions[agent][tc.VAR_SPEED] * MS_TO_KMH ) leader = self.simulation.veh_subscriptions[agent][tc.VAR_LEADER] if leader: # compatible with traci veh, dist = leader if veh: # compatible with libsumo distance = round(dist) ret = [speed, distance] logger.debug("Agent %s --> Obs: %s", agent, pformat(ret)) return ret
Returns the observation of a given agent. See http://sumo.sourceforge.net/pydoc/traci._simulation.html
9
55
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_observation(self, agent): speed = 0 distance = self._config["scenario_config"]["misc"]["max_distance"] if agent in self.simulation.veh_subscriptions: speed = round( self.simulation.veh_subscriptions[agent][tc.VAR_SPEED] * MS_TO_KMH ) leader = self.simulation.veh_subscriptions[agent][tc.VAR_LEADER] if leader: # compatible with traci veh, dist = leader if veh: # compatible with libsumo distance = round(dist) ret = [speed, distance] logger.debug("Agent %s --> Obs: %s", agent, pformat(ret)) return ret ``` ###Assistant : Returns the observation of a given agent. See http://sumo.sourceforge.net/pydoc/traci._simulation.html
372
def register(self, name, color_list): if name in self._BUILTIN_COLOR_SEQUENCES: raise ValueError(f"{name!r} is a reserved name for a builtin " "color sequence") color_list = list(color_list) # force copy and coerce type to list for color in color_list: try: to_rgba(color) except ValueError: raise ValueError( f"{color!r} is not a valid color specification") self._color_sequences[name] = color_list
Register a new color sequence. The color sequence registry stores a copy of the given *color_list*, so that future changes to the original list do not affect the registered color sequence. Think of this as the registry taking a snapshot of *color_list* at registration. Parameters ---------- name : str The name for the color sequence. color_list : list of colors An iterable returning valid Matplotlib colors when iterating over. Note however that the returned color sequence will always be a list regardless of the input type.
86
51
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def register(self, name, color_list): if name in self._BUILTIN_COLOR_SEQUENCES: raise ValueError(f"{name!r} is a reserved name for a builtin " "color sequence") color_list = list(color_list) # force copy and coerce type to list for color in color_list: try: to_rgba(color) except ValueError: raise ValueError( f"{color!r} is not a valid color specification") self._color_sequences[name] = color_list ``` ###Assistant : Register a new color sequence. The color sequence registry stores a copy of the given *color_list*, so that future changes to the original list do not affect the registered color sequence. Think of this as the registry taking a snapshot of *color_list* at registration. Parameters ---------- name : str The name for the color sequence. color_list : list of colors An iterable returning valid Matplotlib colors when iterating over. Note however that the returned color sequence will always be a list regardless of the input type.
373
def test_get_states_no_attributes(hass_recorder): hass = hass_recorder() now, future, states = _setup_get_states(hass) for state in states: state.attributes = {} # Get states returns everything before POINT for all entities for state1, state2 in zip( states, sorted( history.get_states(hass, future, no_attributes=True), key=lambda state: state.entity_id, ), ): assert state1 == state2 # Get states returns everything before POINT for tested entities entities = [f"test.point_in_time_{i % 5}" for i in range(5)] for state1, state2 in zip( states, sorted( history.get_states(hass, future, entities, no_attributes=True), key=lambda state: state.entity_id, ), ): assert state1 == state2 # Test get_state here because we have a DB setup assert states[0] == history.get_state( hass, future, states[0].entity_id, no_attributes=True ) time_before_recorder_ran = now - timedelta(days=1000) assert history.get_states(hass, time_before_recorder_ran, no_attributes=True) == [] assert ( history.get_state(hass, time_before_recorder_ran, "demo.id", no_attributes=True) is None ) @pytest.mark.parametrize( "attributes, no_attributes, limit", [ ({"attr": True}, False, 5000), ({}, True, 5000), ({"attr": True}, False, 3), ({}, True, 3), ], )
Test getting states without attributes at a specific point in time.
11
145
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_get_states_no_attributes(hass_recorder): hass = hass_recorder() now, future, states = _setup_get_states(hass) for state in states: state.attributes = {} # Get states returns everything before POINT for all entities for state1, state2 in zip( states, sorted( history.get_states(hass, future, no_attributes=True), key=lambda state: state.entity_id, ), ): assert state1 == state2 # Get states returns everything before POINT for tested entities entities = [f"test.point_in_time_{i % 5}" for i in range(5)] for state1, state2 in zip( states, sorted( history.get_states(hass, future, entities, no_attributes=True), key=lambda state: state.entity_id, ), ): assert state1 == state2 # Test get_state here because we have a DB setup assert states[0] == history.get_state( hass, future, states[0].entity_id, no_attributes=True ) time_before_recorder_ran = now - timedelta(days=1000) assert history.get_states(hass, time_before_recorder_ran, no_attributes=True) == [] assert ( history.get_state(hass, time_before_recorder_ran, "demo.id", no_attributes=True) is None ) @pytest.mark.parametrize( "attributes, no_attributes, limit", [ ({"attr": True}, False, 5000), ({}, True, 5000), ({"attr": True}, False, 3), ({}, True, 3), ], ) ``` ###Assistant : Test getting states without attributes at a specific point in time.
374
def set_until(self, frame, lineno=None): # the name "until" is borrowed from gdb if lineno is None: lineno = frame.f_lineno + 1 self._set_stopinfo(frame, frame, lineno)
Stop when the line with the lineno greater than the current one is reached or when returning from current frame.
20
24
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def set_until(self, frame, lineno=None): # the name "until" is borrowed from gdb if lineno is None: lineno = frame.f_lineno + 1 self._set_stopinfo(frame, frame, lineno) ``` ###Assistant : Stop when the line with the lineno greater than the current one is reached or when returning from current frame.
375
async def get_device_state(self, hass): websession = async_get_clientsession(hass, self._verify_ssl) rendered_headers = template.render_complex(self._headers, parse_result=False) rendered_params = template.render_complex(self._params)
Get the latest data from REST API and update the state.
11
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python async def get_device_state(self, hass): websession = async_get_clientsession(hass, self._verify_ssl) rendered_headers = template.render_complex(self._headers, parse_result=False) rendered_params = template.render_complex(self._params) ``` ###Assistant : Get the latest data from REST API and update the state.
376
def reset_channel(self) -> None: if self.channel: self.channel.close() self.channel = grpc.insecure_channel(self.real_addr, options=GRPC_OPTIONS) grpc.channel_ready_future(self.channel) self.task_servicer.set_channel(self.channel) self.data_servicer.set_channel(self.channel) self.logs_servicer.set_channel(self.channel)
Manually close and reopen the channel to the real ray server. This simulates a disconnection between the client and the server.
21
15
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def reset_channel(self) -> None: if self.channel: self.channel.close() self.channel = grpc.insecure_channel(self.real_addr, options=GRPC_OPTIONS) grpc.channel_ready_future(self.channel) self.task_servicer.set_channel(self.channel) self.data_servicer.set_channel(self.channel) self.logs_servicer.set_channel(self.channel) ``` ###Assistant : Manually close and reopen the channel to the real ray server. This simulates a disconnection between the client and the server.
377
def wait_scroll_pos_changed(self, x=None, y=None): __tracebackhide__ = (lambda e: e.errisinstance(testprocess.WaitForTimeout)) if (x is None and y is not None) or (y is None and x is not None): raise ValueError("Either both x/y or neither must be given!") if x is None and y is None: point = 'Py*.QtCore.QPoint(*, *)' # not counting 0/0 here elif x == '0' and y == '0': point = 'Py*.QtCore.QPoint()' else: point = 'Py*.QtCore.QPoint({}, {})'.format(x, y) self.wait_for(category='webview', message='Scroll position changed to ' + point)
Wait until a "Scroll position changed" message was found. With QtWebEngine, on older Qt versions which lack QWebEnginePage.scrollPositionChanged, this also skips the test.
23
78
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def wait_scroll_pos_changed(self, x=None, y=None): __tracebackhide__ = (lambda e: e.errisinstance(testprocess.WaitForTimeout)) if (x is None and y is not None) or (y is None and x is not None): raise ValueError("Either both x/y or neither must be given!") if x is None and y is None: point = 'Py*.QtCore.QPoint(*, *)' # not counting 0/0 here elif x == '0' and y == '0': point = 'Py*.QtCore.QPoint()' else: point = 'Py*.QtCore.QPoint({}, {})'.format(x, y) self.wait_for(category='webview', message='Scroll position changed to ' + point) ``` ###Assistant : Wait until a "Scroll position changed" message was found. With QtWebEngine, on older Qt versions which lack QWebEnginePage.scrollPositionChanged, this also skips the test.
378
def test_write_tfrecords(ray_start_regular_shared, tmp_path): import tensorflow as tf # The dataset we will write to a .tfrecords file. ds = ray.data.from_items( [ # Row one. { "int_item": 1, "int_list": [2, 2, 3], "float_item": 1.0, "float_list": [2.0, 3.0, 4.0], "bytes_item": b"abc", "bytes_list": [b"abc", b"1234"], }, # Row two. { "int_item": 2, "int_list": [3, 3, 4], "float_item": 2.0, "float_list": [2.0, 2.0, 3.0], "bytes_item": b"def", "bytes_list": [b"def", b"1234"], }, ] ) # The corresponding tf.train.Example that we would expect to read # from this dataset. expected_records = [ # Record one (corresponding to row one). tf.train.Example( features=tf.train.Features( feature={ "int_item": tf.train.Feature( int64_list=tf.train.Int64List(value=[1]) ), "int_list": tf.train.Feature( int64_list=tf.train.Int64List(value=[2, 2, 3]) ), "float_item": tf.train.Feature( float_list=tf.train.FloatList(value=[1.0]) ), "float_list": tf.train.Feature( float_list=tf.train.FloatList(value=[2.0, 3.0, 4.0]) ), "bytes_item": tf.train.Feature( bytes_list=tf.train.BytesList(value=[b"abc"]) ), "bytes_list": tf.train.Feature( bytes_list=tf.train.BytesList(value=[b"abc", b"1234"]) ), } ) ), # Record two (corresponding to row two). tf.train.Example( features=tf.train.Features( feature={ "int_item": tf.train.Feature( int64_list=tf.train.Int64List(value=[2]) ), "int_list": tf.train.Feature( int64_list=tf.train.Int64List(value=[3, 3, 4]) ), "float_item": tf.train.Feature( float_list=tf.train.FloatList(value=[2.0]) ), "float_list": tf.train.Feature( float_list=tf.train.FloatList(value=[2.0, 2.0, 3.0]) ), "bytes_item": tf.train.Feature( bytes_list=tf.train.BytesList(value=[b"def"]) ), "bytes_list": tf.train.Feature( bytes_list=tf.train.BytesList(value=[b"def", b"1234"]) ), } ) ), ] # Perform the test. # Write the dataset to a .tfrecords file. ds.write_tfrecords(tmp_path) # Read the Examples back out from the .tfrecords file. # This follows the offical TFRecords tutorial: # https://www.tensorflow.org/tutorials/load_data/tfrecord#reading_a_tfrecord_file_2 filenames = sorted(os.listdir(tmp_path)) filepaths = [os.path.join(tmp_path, filename) for filename in filenames] raw_dataset = tf.data.TFRecordDataset(filepaths) tfrecords = [] for raw_record in raw_dataset: example = tf.train.Example() example.ParseFromString(raw_record.numpy()) tfrecords.append(example) assert tfrecords == expected_records
Test that write_tfrecords writes TFRecords correctly. Test this by writing a Dataset to a TFRecord (function under test), reading it back out into a tf.train.Example, and checking that the result is analogous to the original Dataset.
36
231
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_write_tfrecords(ray_start_regular_shared, tmp_path): import tensorflow as tf # The dataset we will write to a .tfrecords file. ds = ray.data.from_items( [ # Row one. { "int_item": 1, "int_list": [2, 2, 3], "float_item": 1.0, "float_list": [2.0, 3.0, 4.0], "bytes_item": b"abc", "bytes_list": [b"abc", b"1234"], }, # Row two. { "int_item": 2, "int_list": [3, 3, 4], "float_item": 2.0, "float_list": [2.0, 2.0, 3.0], "bytes_item": b"def", "bytes_list": [b"def", b"1234"], }, ] ) # The corresponding tf.train.Example that we would expect to read # from this dataset. expected_records = [ # Record one (corresponding to row one). tf.train.Example( features=tf.train.Features( feature={ "int_item": tf.train.Feature( int64_list=tf.train.Int64List(value=[1]) ), "int_list": tf.train.Feature( int64_list=tf.train.Int64List(value=[2, 2, 3]) ), "float_item": tf.train.Feature( float_list=tf.train.FloatList(value=[1.0]) ), "float_list": tf.train.Feature( float_list=tf.train.FloatList(value=[2.0, 3.0, 4.0]) ), "bytes_item": tf.train.Feature( bytes_list=tf.train.BytesList(value=[b"abc"]) ), "bytes_list": tf.train.Feature( bytes_list=tf.train.BytesList(value=[b"abc", b"1234"]) ), } ) ), # Record two (corresponding to row two). tf.train.Example( features=tf.train.Features( feature={ "int_item": tf.train.Feature( int64_list=tf.train.Int64List(value=[2]) ), "int_list": tf.train.Feature( int64_list=tf.train.Int64List(value=[3, 3, 4]) ), "float_item": tf.train.Feature( float_list=tf.train.FloatList(value=[2.0]) ), "float_list": tf.train.Feature( float_list=tf.train.FloatList(value=[2.0, 2.0, 3.0]) ), "bytes_item": tf.train.Feature( bytes_list=tf.train.BytesList(value=[b"def"]) ), "bytes_list": tf.train.Feature( bytes_list=tf.train.BytesList(value=[b"def", b"1234"]) ), } ) ), ] # Perform the test. # Write the dataset to a .tfrecords file. ds.write_tfrecords(tmp_path) # Read the Examples back out from the .tfrecords file. # This follows the offical TFRecords tutorial: # https://www.tensorflow.org/tutorials/load_data/tfrecord#reading_a_tfrecord_file_2 filenames = sorted(os.listdir(tmp_path)) filepaths = [os.path.join(tmp_path, filename) for filename in filenames] raw_dataset = tf.data.TFRecordDataset(filepaths) tfrecords = [] for raw_record in raw_dataset: example = tf.train.Example() example.ParseFromString(raw_record.numpy()) tfrecords.append(example) assert tfrecords == expected_records ``` ###Assistant : Test that write_tfrecords writes TFRecords correctly. Test this by writing a Dataset to a TFRecord (function under test), reading it back out into a tf.train.Example, and checking that the result is analogous to the original Dataset.
379
def test_float_conversion_dtype(self): x = np.array([-1, 1]) # Test all combinations of dtypes conversions dtype_combin = np.array( np.meshgrid( OutputPreprocessing.float_dtype_list, OutputPreprocessing.float_dtype_list, ) ).T.reshape(-1, 2) for dtype_in, dtype_out in dtype_combin: x = x.astype(dtype_in) y = gr.processing_utils._convert(x, dtype_out) assert y.dtype == np.dtype(dtype_out)
Test any convertion from a float dtype to an other.
10
38
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_float_conversion_dtype(self): x = np.array([-1, 1]) # Test all combinations of dtypes conversions dtype_combin = np.array( np.meshgrid( OutputPreprocessing.float_dtype_list, OutputPreprocessing.float_dtype_list, ) ).T.reshape(-1, 2) for dtype_in, dtype_out in dtype_combin: x = x.astype(dtype_in) y = gr.processing_utils._convert(x, dtype_out) assert y.dtype == np.dtype(dtype_out) ``` ###Assistant : Test any convertion from a float dtype to an other.
380
def fix_mime_types(): # Known to be problematic when Visual Studio is installed: # <https://github.com/tensorflow/tensorboard/issues/3120> # https://github.com/spotDL/spotify-downloader/issues/1540 mimetypes.add_type("application/javascript", ".js") # Not known to be problematic, but used by spotDL: mimetypes.add_type("text/css", ".css") mimetypes.add_type("image/svg+xml", ".svg") mimetypes.add_type("text/html", ".html") @app.server.websocket("/api/ws")
Fix incorrect entries in the `mimetypes` registry. On Windows, the Python standard library's `mimetypes` reads in mappings from file extension to MIME type from the Windows registry. Other applications can and do write incorrect values to this registry, which causes `mimetypes.guess_type` to return incorrect values, which causes spotDL to fail to render on the frontend. This method hard-codes the correct mappings for certain MIME types that are known to be either used by TensorBoard or problematic in general.
78
35
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def fix_mime_types(): # Known to be problematic when Visual Studio is installed: # <https://github.com/tensorflow/tensorboard/issues/3120> # https://github.com/spotDL/spotify-downloader/issues/1540 mimetypes.add_type("application/javascript", ".js") # Not known to be problematic, but used by spotDL: mimetypes.add_type("text/css", ".css") mimetypes.add_type("image/svg+xml", ".svg") mimetypes.add_type("text/html", ".html") @app.server.websocket("/api/ws") ``` ###Assistant : Fix incorrect entries in the `mimetypes` registry. On Windows, the Python standard library's `mimetypes` reads in mappings from file extension to MIME type from the Windows registry. Other applications can and do write incorrect values to this registry, which causes `mimetypes.guess_type` to return incorrect values, which causes spotDL to fail to render on the frontend. This method hard-codes the correct mappings for certain MIME types that are known to be either used by TensorBoard or problematic in general.
381
def _get_threads(self) -> MultiThread: # TODO Check if multiple threads actually speeds anything up save_queue = queue_manager.get_queue("convert_out") patch_queue = queue_manager.get_queue("patch") return MultiThread(self._converter.process, patch_queue, save_queue, thread_count=self._pool_processes, name="patch")
Get the threads for patching the converted faces onto the frames. Returns :class:`lib.multithreading.MultiThread` The threads that perform the patching of swapped faces onto the output frames
26
26
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _get_threads(self) -> MultiThread: # TODO Check if multiple threads actually speeds anything up save_queue = queue_manager.get_queue("convert_out") patch_queue = queue_manager.get_queue("patch") return MultiThread(self._converter.process, patch_queue, save_queue, thread_count=self._pool_processes, name="patch") ``` ###Assistant : Get the threads for patching the converted faces onto the frames. Returns :class:`lib.multithreading.MultiThread` The threads that perform the patching of swapped faces onto the output frames
382
def verify_metadata(self): # send the info to the server and report the result (code, result) = self.post_to_server(self.build_post_data('verify')) log.info('Server response (%s): %s', code, result)
Send the metadata to the package index server to be checked.
11
23
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def verify_metadata(self): # send the info to the server and report the result (code, result) = self.post_to_server(self.build_post_data('verify')) log.info('Server response (%s): %s', code, result) ``` ###Assistant : Send the metadata to the package index server to be checked.
383
def test_subscriptions_add_for_principal_invite_only(self) -> None: invitee = self.example_user("iago") current_streams = self.get_streams(invitee) invite_streams = self.make_random_stream_names(current_streams) self.assert_adding_subscriptions_for_principal( invitee.id, invitee.realm, invite_streams, invite_only=True, policy_name="Private, protected history", )
You can subscribe other people to invite only streams.
9
22
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_subscriptions_add_for_principal_invite_only(self) -> None: invitee = self.example_user("iago") current_streams = self.get_streams(invitee) invite_streams = self.make_random_stream_names(current_streams) self.assert_adding_subscriptions_for_principal( invitee.id, invitee.realm, invite_streams, invite_only=True, policy_name="Private, protected history", ) ``` ###Assistant : You can subscribe other people to invite only streams.
384
def get_module_dict_key_from_name(name): key = name.replace(".", "__ludwig_punct_period__") return key + FEATURE_NAME_SUFFIX
Returns a key that's guaranteed to be compatible with torch.
10
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_module_dict_key_from_name(name): key = name.replace(".", "__ludwig_punct_period__") return key + FEATURE_NAME_SUFFIX ``` ###Assistant : Returns a key that's guaranteed to be compatible with torch.
385
def test_hdk_import(import_strategy, has_other_engines): remove_other_engines = if not has_other_engines: import_strategy = f"{remove_other_engines}\n{import_strategy}" res = subprocess.run( [sys.executable, "-c", import_strategy], stderr=subprocess.PIPE, stdout=subprocess.PIPE, ) if res.returncode != 0: pytest.fail(str(res.stderr)) @pytest.mark.parametrize( "import_strategy, expected_to_fail", [ pytest.param( , True, id="import_pydbe_first-pyarrow_gandiva_second", ), pytest.param( , False, id="import_pyarrow_gandiva_first-pydbe_second", ), ], )
Test import of HDK engine. The import of DbWorker requires to set special dlopen flags which make it then incompatible to import some other libraries further (like ``pyarrow.gandiva``). This test verifies that it's not the case when a user naturally imports Modin with HDK engine. Parameters ---------- import_strategy : str There are several scenarios of how a user can import Modin with HDK engine: configure Modin first to use HDK engine and then import ``modin.pandas`` or vice versa. This parameters holds a python code, implementing one of these scenarios. has_other_engines : bool The problem with import may appear depending on whether other engines are installed. This parameter indicates whether to remove modules for non-hdk engines before the test. Notes ----- The failed import flow may cause segfault, which causes to crash the pytest itself. This makes us to run the test in a separate process and check its exit-code to decide the success of the test. import sys sys.modules['ray'] = None sys.modules['dask'] = None from modin.experimental.core.execution.native.implementations.hdk_on_native.db_worker import DbWorker import pyarrow.gandiva import pyarrow.gandiva from modin.experimental.core.execution.native.implementations.hdk_on_native.db_worker import DbWorker
176
41
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_hdk_import(import_strategy, has_other_engines): remove_other_engines = if not has_other_engines: import_strategy = f"{remove_other_engines}\n{import_strategy}" res = subprocess.run( [sys.executable, "-c", import_strategy], stderr=subprocess.PIPE, stdout=subprocess.PIPE, ) if res.returncode != 0: pytest.fail(str(res.stderr)) @pytest.mark.parametrize( "import_strategy, expected_to_fail", [ pytest.param( , True, id="import_pydbe_first-pyarrow_gandiva_second", ), pytest.param( , False, id="import_pyarrow_gandiva_first-pydbe_second", ), ], ) ``` ###Assistant : Test import of HDK engine. The import of DbWorker requires to set special dlopen flags which make it then incompatible to import some other libraries further (like ``pyarrow.gandiva``). This test verifies that it's not the case when a user naturally imports Modin with HDK engine. Parameters ---------- import_strategy : str There are several scenarios of how a user can import Modin with HDK engine: configure Modin first to use HDK engine and then import ``modin.pandas`` or vice versa. This parameters holds a python code, implementing one of these scenarios. has_other_engines : bool The problem with import may appear depending on whether other engines are installed. This parameter indicates whether to remove modules for non-hdk engines before the test. Notes ----- The failed import flow may cause segfault, which causes to crash the pytest itself. This makes us to run the test in a separate process and check its exit-code to decide the success of the test. import sys sys.modules['ray'] = None sys.modules['dask'] = None from modin.experimental.core.execution.native.implementations.hdk_on_native.db_worker import DbWorker import pyarrow.gandiva import pyarrow.gandiva from modin.experimental.core.execution.native.implementations.hdk_on_native.db_worker import DbWorker
386
def _iter_tree_entries_next(root_full, dir_rel, memo, on_error, follow_links): dir_full = os.path.join(root_full, dir_rel) dir_real = os.path.realpath(dir_full) # Remember each encountered ancestor directory and its canonical # (real) path. If a canonical path is encountered more than once, # recursion has occurred. if dir_real not in memo: memo[dir_real] = dir_rel else: raise RecursionError( real_path=dir_real, first_path=memo[dir_real], second_path=dir_rel ) for node_name in os.listdir(dir_full): node_rel = os.path.join(dir_rel, node_name) node_full = os.path.join(root_full, node_rel) # Inspect child node. try: node_lstat = os.lstat(node_full) except OSError as e: if on_error is not None: on_error(e) continue if stat.S_ISLNK(node_lstat.st_mode): # Child node is a link, inspect the target node. is_link = True try: node_stat = os.stat(node_full) except OSError as e: if on_error is not None: on_error(e) continue else: is_link = False node_stat = node_lstat if stat.S_ISDIR(node_stat.st_mode) and (follow_links or not is_link): # Child node is a directory, recurse into it and yield its # descendant files. yield TreeEntry(node_name, node_rel, node_lstat, node_stat) for entry in _iter_tree_entries_next( root_full, node_rel, memo, on_error, follow_links ): yield entry elif stat.S_ISREG(node_stat.st_mode) or is_link: # Child node is either a file or an unfollowed link, yield it. yield TreeEntry(node_name, node_rel, node_lstat, node_stat) # NOTE: Make sure to remove the canonical (real) path of the directory # from the ancestors memo once we are done with it. This allows the # same directory to appear multiple times. If this is not done, the # second occurrence of the directory will be incorrectly interpreted # as a recursion. See <https://github.com/cpburnz/python-path-specification/pull/7>. del memo[dir_real]
Scan the directory for all descendant files. *root_full* (:class:`str`) the absolute path to the root directory. *dir_rel* (:class:`str`) the path to the directory to scan relative to *root_full*. *memo* (:class:`dict`) keeps track of ancestor directories encountered. Maps each ancestor real path (:class:`str`) to relative path (:class:`str`). *on_error* (:class:`~collections.abc.Callable` or :data:`None`) optionally is the error handler for file-system exceptions. *follow_links* (:class:`bool`) is whether to walk symbolic links that resolve to directories. Yields each entry (:class:`.TreeEntry`).
74
240
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _iter_tree_entries_next(root_full, dir_rel, memo, on_error, follow_links): dir_full = os.path.join(root_full, dir_rel) dir_real = os.path.realpath(dir_full) # Remember each encountered ancestor directory and its canonical # (real) path. If a canonical path is encountered more than once, # recursion has occurred. if dir_real not in memo: memo[dir_real] = dir_rel else: raise RecursionError( real_path=dir_real, first_path=memo[dir_real], second_path=dir_rel ) for node_name in os.listdir(dir_full): node_rel = os.path.join(dir_rel, node_name) node_full = os.path.join(root_full, node_rel) # Inspect child node. try: node_lstat = os.lstat(node_full) except OSError as e: if on_error is not None: on_error(e) continue if stat.S_ISLNK(node_lstat.st_mode): # Child node is a link, inspect the target node. is_link = True try: node_stat = os.stat(node_full) except OSError as e: if on_error is not None: on_error(e) continue else: is_link = False node_stat = node_lstat if stat.S_ISDIR(node_stat.st_mode) and (follow_links or not is_link): # Child node is a directory, recurse into it and yield its # descendant files. yield TreeEntry(node_name, node_rel, node_lstat, node_stat) for entry in _iter_tree_entries_next( root_full, node_rel, memo, on_error, follow_links ): yield entry elif stat.S_ISREG(node_stat.st_mode) or is_link: # Child node is either a file or an unfollowed link, yield it. yield TreeEntry(node_name, node_rel, node_lstat, node_stat) # NOTE: Make sure to remove the canonical (real) path of the directory # from the ancestors memo once we are done with it. This allows the # same directory to appear multiple times. If this is not done, the # second occurrence of the directory will be incorrectly interpreted # as a recursion. See <https://github.com/cpburnz/python-path-specification/pull/7>. del memo[dir_real] ``` ###Assistant : Scan the directory for all descendant files. *root_full* (:class:`str`) the absolute path to the root directory. *dir_rel* (:class:`str`) the path to the directory to scan relative to *root_full*. *memo* (:class:`dict`) keeps track of ancestor directories encountered. Maps each ancestor real path (:class:`str`) to relative path (:class:`str`). *on_error* (:class:`~collections.abc.Callable` or :data:`None`) optionally is the error handler for file-system exceptions. *follow_links* (:class:`bool`) is whether to walk symbolic links that resolve to directories. Yields each entry (:class:`.TreeEntry`).
387
def _remove_gens(base, strong_gens, basic_orbits=None, strong_gens_distr=None): from sympy.combinatorics.perm_groups import _orbit base_len = len(base) degree = strong_gens[0].size if strong_gens_distr is None: strong_gens_distr = _distribute_gens_by_base(base, strong_gens) if basic_orbits is None: basic_orbits = [] for i in range(base_len): basic_orbit = _orbit(degree, strong_gens_distr[i], base[i]) basic_orbits.append(basic_orbit) strong_gens_distr.append([]) res = strong_gens[:] for i in range(base_len - 1, -1, -1): gens_copy = strong_gens_distr[i][:] for gen in strong_gens_distr[i]: if gen not in strong_gens_distr[i + 1]: temp_gens = gens_copy[:] temp_gens.remove(gen) if temp_gens == []: continue temp_orbit = _orbit(degree, temp_gens, base[i]) if temp_orbit == basic_orbits[i]: gens_copy.remove(gen) res.remove(gen) return res
Remove redundant generators from a strong generating set. Parameters ========== ``base`` - a base ``strong_gens`` - a strong generating set relative to ``base`` ``basic_orbits`` - basic orbits ``strong_gens_distr`` - strong generators distributed by membership in basic stabilizers Returns ======= A strong generating set with respect to ``base`` which is a subset of ``strong_gens``. Examples ======== >>> from sympy.combinatorics import SymmetricGroup >>> from sympy.combinatorics.util import _remove_gens >>> from sympy.combinatorics.testutil import _verify_bsgs >>> S = SymmetricGroup(15) >>> base, strong_gens = S.schreier_sims_incremental() >>> new_gens = _remove_gens(base, strong_gens) >>> len(new_gens) 14 >>> _verify_bsgs(S, base, new_gens) True Notes ===== This procedure is outlined in [1],p.95. References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory"
115
88
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _remove_gens(base, strong_gens, basic_orbits=None, strong_gens_distr=None): from sympy.combinatorics.perm_groups import _orbit base_len = len(base) degree = strong_gens[0].size if strong_gens_distr is None: strong_gens_distr = _distribute_gens_by_base(base, strong_gens) if basic_orbits is None: basic_orbits = [] for i in range(base_len): basic_orbit = _orbit(degree, strong_gens_distr[i], base[i]) basic_orbits.append(basic_orbit) strong_gens_distr.append([]) res = strong_gens[:] for i in range(base_len - 1, -1, -1): gens_copy = strong_gens_distr[i][:] for gen in strong_gens_distr[i]: if gen not in strong_gens_distr[i + 1]: temp_gens = gens_copy[:] temp_gens.remove(gen) if temp_gens == []: continue temp_orbit = _orbit(degree, temp_gens, base[i]) if temp_orbit == basic_orbits[i]: gens_copy.remove(gen) res.remove(gen) return res ``` ###Assistant : Remove redundant generators from a strong generating set. Parameters ========== ``base`` - a base ``strong_gens`` - a strong generating set relative to ``base`` ``basic_orbits`` - basic orbits ``strong_gens_distr`` - strong generators distributed by membership in basic stabilizers Returns ======= A strong generating set with respect to ``base`` which is a subset of ``strong_gens``. Examples ======== >>> from sympy.combinatorics import SymmetricGroup >>> from sympy.combinatorics.util import _remove_gens >>> from sympy.combinatorics.testutil import _verify_bsgs >>> S = SymmetricGroup(15) >>> base, strong_gens = S.schreier_sims_incremental() >>> new_gens = _remove_gens(base, strong_gens) >>> len(new_gens) 14 >>> _verify_bsgs(S, base, new_gens) True Notes ===== This procedure is outlined in [1],p.95. References ========== .. [1] Holt, D., Eick, B., O'Brien, E. "Handbook of computational group theory"
388
def from_dict(cls, file_dict): return cls( file_dict["filename"], file_dict["content"], file_dict.get("content-type", "text/plain"), )
Create a SimpleUploadedFile object from a dictionary with keys: - filename - content-type - content
15
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def from_dict(cls, file_dict): return cls( file_dict["filename"], file_dict["content"], file_dict.get("content-type", "text/plain"), ) ``` ###Assistant : Create a SimpleUploadedFile object from a dictionary with keys: - filename - content-type - content
389
def test_change_list_sorting_callable(self): response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": 2} ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on callable are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on callable are out of order.", )
Ensure we can sort on a list_display field that is a callable (column 2 is callable_year in ArticleAdmin)
18
41
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_change_list_sorting_callable(self): response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": 2} ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on callable are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on callable are out of order.", ) ``` ###Assistant : Ensure we can sort on a list_display field that is a callable (column 2 is callable_year in ArticleAdmin)
390
def pre_encode(self) -> Optional[Callable[[np.ndarray], List[bytes]]]: dummy = np.zeros((20, 20, 3), dtype="uint8") test = self._writer.pre_encode(dummy) retval: Optional[Callable[[np.ndarray], List[bytes]]] = None if test is None else self._writer.pre_encode logger.debug("Writer pre_encode function: %s", retval) return retval
python function: Selected writer's pre-encode function, if it has one, otherwise ``None``
12
32
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def pre_encode(self) -> Optional[Callable[[np.ndarray], List[bytes]]]: dummy = np.zeros((20, 20, 3), dtype="uint8") test = self._writer.pre_encode(dummy) retval: Optional[Callable[[np.ndarray], List[bytes]]] = None if test is None else self._writer.pre_encode logger.debug("Writer pre_encode function: %s", retval) return retval ``` ###Assistant : python function: Selected writer's pre-encode function, if it has one, otherwise ``None``
391
def disconnect(self): if self.is_connected is False: return self.connection.close() self.is_connected = False return self.is_connected
Close any existing connections.
4
13
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def disconnect(self): if self.is_connected is False: return self.connection.close() self.is_connected = False return self.is_connected ``` ###Assistant : Close any existing connections.
392
def resolve(self) -> Tuple[List, Dict]: objects_mapping = [] for obj_ref in self.workflow_outputs: obj, ref = _resolve_object_ref(obj_ref.ref) objects_mapping.append(obj) workflow_ref_mapping = _resolve_dynamic_workflow_refs(self.workflow_refs) with serialization_context.workflow_args_resolving_context( objects_mapping, workflow_ref_mapping ): # reconstruct input arguments under correct serialization context flattened_args: List[Any] = ray.get(self.args) # dereference arguments like Ray remote functions flattened_args = [ ray.get(a) if isinstance(a, ObjectRef) else a for a in flattened_args ] return signature.recover_args(flattened_args)
This function resolves the inputs for the code inside a workflow step (works on the callee side). For outputs from other workflows, we resolve them into object instances inplace. For each ObjectRef argument, the function returns both the ObjectRef and the object instance. If the ObjectRef is a chain of nested ObjectRefs, then we resolve it recursively until we get the object instance, and we return the *direct* ObjectRef of the instance. This function does not resolve ObjectRef inside another object (e.g. list of ObjectRefs) to give users some flexibility. Returns: Instances of arguments.
94
60
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def resolve(self) -> Tuple[List, Dict]: objects_mapping = [] for obj_ref in self.workflow_outputs: obj, ref = _resolve_object_ref(obj_ref.ref) objects_mapping.append(obj) workflow_ref_mapping = _resolve_dynamic_workflow_refs(self.workflow_refs) with serialization_context.workflow_args_resolving_context( objects_mapping, workflow_ref_mapping ): # reconstruct input arguments under correct serialization context flattened_args: List[Any] = ray.get(self.args) # dereference arguments like Ray remote functions flattened_args = [ ray.get(a) if isinstance(a, ObjectRef) else a for a in flattened_args ] return signature.recover_args(flattened_args) ``` ###Assistant : This function resolves the inputs for the code inside a workflow step (works on the callee side). For outputs from other workflows, we resolve them into object instances inplace. For each ObjectRef argument, the function returns both the ObjectRef and the object instance. If the ObjectRef is a chain of nested ObjectRefs, then we resolve it recursively until we get the object instance, and we return the *direct* ObjectRef of the instance. This function does not resolve ObjectRef inside another object (e.g. list of ObjectRefs) to give users some flexibility. Returns: Instances of arguments.
393
def _maybe_create_attribute(self, name, default_value): if not hasattr(self, name): self.__setattr__(name, default_value)
Create the attribute with the default value if it hasn't been created. This is useful for fields that is used for tracking purpose, _trainable_weights, or _layers. Note that user could create a layer subclass and assign an internal field before invoking the Layer.__init__(), the __setattr__() need to create the tracking fields and __init__() need to not override them. Args: name: String, the name of the attribute. default_value: Object, the default value of the attribute.
74
10
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _maybe_create_attribute(self, name, default_value): if not hasattr(self, name): self.__setattr__(name, default_value) ``` ###Assistant : Create the attribute with the default value if it hasn't been created. This is useful for fields that is used for tracking purpose, _trainable_weights, or _layers. Note that user could create a layer subclass and assign an internal field before invoking the Layer.__init__(), the __setattr__() need to create the tracking fields and __init__() need to not override them. Args: name: String, the name of the attribute. default_value: Object, the default value of the attribute.
394
def add_nodes_from(self, nodes_for_adding, **attr): for n in nodes_for_adding: try: newnode = n not in self._node newdict = attr except TypeError: n, ndict = n newnode = n not in self._node newdict = attr.copy() newdict.update(ndict) if newnode: if n is None: raise ValueError("None cannot be a node") self._succ[n] = self.adjlist_inner_dict_factory() self._pred[n] = self.adjlist_inner_dict_factory() self._node[n] = self.node_attr_dict_factory() self._node[n].update(newdict)
Add multiple nodes. Parameters ---------- nodes_for_adding : iterable container A container of nodes (list, dict, set, etc.). OR A container of (node, attribute dict) tuples. Node attributes are updated using the attribute dict. attr : keyword arguments, optional (default= no attributes) Update attributes for all nodes in nodes. Node attributes specified in nodes as a tuple take precedence over attributes specified via keyword arguments. See Also -------- add_node Notes ------- When adding nodes from an iterator over the graph you are changing, a `RuntimeError` can be raised with message: `RuntimeError: dictionary changed size during iteration`. This happens when the graph's underlying dictionary is modified during iteration. To avoid this error, evaluate the iterator into a separate object, e.g. by using `list(iterator_of_nodes)`, and pass this object to `G.add_nodes_from`. Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_nodes_from("Hello") >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)]) >>> G.add_nodes_from(K3) >>> sorted(G.nodes(), key=str) [0, 1, 2, 'H', 'e', 'l', 'o'] Use keywords to update specific node attributes for every node. >>> G.add_nodes_from([1, 2], size=10) >>> G.add_nodes_from([3, 4], weight=0.4) Use (node, attrdict) tuples to update attributes for specific nodes. >>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})]) >>> G.nodes[1]["size"] 11 >>> H = nx.Graph() >>> H.add_nodes_from(G.nodes(data=True)) >>> H.nodes[1]["size"] 11 Evaluate an iterator over a graph if using it to modify the same graph >>> G = nx.DiGraph([(0, 1), (1, 2), (3, 4)]) >>> # wrong way - will raise RuntimeError >>> # G.add_nodes_from(n + 1 for n in G.nodes) >>> # correct way >>> G.add_nodes_from(list(n + 1 for n in G.nodes))
260
56
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def add_nodes_from(self, nodes_for_adding, **attr): for n in nodes_for_adding: try: newnode = n not in self._node newdict = attr except TypeError: n, ndict = n newnode = n not in self._node newdict = attr.copy() newdict.update(ndict) if newnode: if n is None: raise ValueError("None cannot be a node") self._succ[n] = self.adjlist_inner_dict_factory() self._pred[n] = self.adjlist_inner_dict_factory() self._node[n] = self.node_attr_dict_factory() self._node[n].update(newdict) ``` ###Assistant : Add multiple nodes. Parameters ---------- nodes_for_adding : iterable container A container of nodes (list, dict, set, etc.). OR A container of (node, attribute dict) tuples. Node attributes are updated using the attribute dict. attr : keyword arguments, optional (default= no attributes) Update attributes for all nodes in nodes. Node attributes specified in nodes as a tuple take precedence over attributes specified via keyword arguments. See Also -------- add_node Notes ------- When adding nodes from an iterator over the graph you are changing, a `RuntimeError` can be raised with message: `RuntimeError: dictionary changed size during iteration`. This happens when the graph's underlying dictionary is modified during iteration. To avoid this error, evaluate the iterator into a separate object, e.g. by using `list(iterator_of_nodes)`, and pass this object to `G.add_nodes_from`. Examples -------- >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G.add_nodes_from("Hello") >>> K3 = nx.Graph([(0, 1), (1, 2), (2, 0)]) >>> G.add_nodes_from(K3) >>> sorted(G.nodes(), key=str) [0, 1, 2, 'H', 'e', 'l', 'o'] Use keywords to update specific node attributes for every node. >>> G.add_nodes_from([1, 2], size=10) >>> G.add_nodes_from([3, 4], weight=0.4) Use (node, attrdict) tuples to update attributes for specific nodes. >>> G.add_nodes_from([(1, dict(size=11)), (2, {"color": "blue"})]) >>> G.nodes[1]["size"] 11 >>> H = nx.Graph() >>> H.add_nodes_from(G.nodes(data=True)) >>> H.nodes[1]["size"] 11 Evaluate an iterator over a graph if using it to modify the same graph >>> G = nx.DiGraph([(0, 1), (1, 2), (3, 4)]) >>> # wrong way - will raise RuntimeError >>> # G.add_nodes_from(n + 1 for n in G.nodes) >>> # correct way >>> G.add_nodes_from(list(n + 1 for n in G.nodes))
395
def test_submitted_email_notifications_sent(self): self.login(self.submitter) self.submit() self.assertEqual(len(mail.outbox), 4) task_submission_emails = [ email for email in mail.outbox if "task" in email.subject ] task_submission_emailed_addresses = [ address for email in task_submission_emails for address in email.to ] workflow_submission_emails = [ email for email in mail.outbox if "workflow" in email.subject ] workflow_submission_emailed_addresses = [ address for email in workflow_submission_emails for address in email.to ] self.assertEqual(len(task_submission_emails), 3) # the moderator is in the Group assigned to the GroupApproval task, so should get an email self.assertIn(self.moderator.email, task_submission_emailed_addresses) self.assertIn(self.moderator2.email, task_submission_emailed_addresses) # with `WAGTAILADMIN_NOTIFICATION_INCLUDE_SUPERUSERS`, the superuser should get a task email self.assertIn(self.superuser.email, task_submission_emailed_addresses) # the submitter triggered this workflow update, so should not get an email self.assertNotIn(self.submitter.email, task_submission_emailed_addresses) self.assertEqual(len(workflow_submission_emails), 1) # the moderator should not get a workflow email self.assertNotIn(self.moderator.email, workflow_submission_emailed_addresses) self.assertNotIn(self.moderator2.email, workflow_submission_emailed_addresses) # with `WAGTAILADMIN_NOTIFICATION_INCLUDE_SUPERUSERS`, the superuser should get a workflow email self.assertIn(self.superuser.email, workflow_submission_emailed_addresses) # as the submitter was the triggering user, the submitter should not get an email notification self.assertNotIn(self.submitter.email, workflow_submission_emailed_addresses)
Test that 'submitted' notifications for WorkflowState and TaskState are both sent correctly
12
153
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def test_submitted_email_notifications_sent(self): self.login(self.submitter) self.submit() self.assertEqual(len(mail.outbox), 4) task_submission_emails = [ email for email in mail.outbox if "task" in email.subject ] task_submission_emailed_addresses = [ address for email in task_submission_emails for address in email.to ] workflow_submission_emails = [ email for email in mail.outbox if "workflow" in email.subject ] workflow_submission_emailed_addresses = [ address for email in workflow_submission_emails for address in email.to ] self.assertEqual(len(task_submission_emails), 3) # the moderator is in the Group assigned to the GroupApproval task, so should get an email self.assertIn(self.moderator.email, task_submission_emailed_addresses) self.assertIn(self.moderator2.email, task_submission_emailed_addresses) # with `WAGTAILADMIN_NOTIFICATION_INCLUDE_SUPERUSERS`, the superuser should get a task email self.assertIn(self.superuser.email, task_submission_emailed_addresses) # the submitter triggered this workflow update, so should not get an email self.assertNotIn(self.submitter.email, task_submission_emailed_addresses) self.assertEqual(len(workflow_submission_emails), 1) # the moderator should not get a workflow email self.assertNotIn(self.moderator.email, workflow_submission_emailed_addresses) self.assertNotIn(self.moderator2.email, workflow_submission_emailed_addresses) # with `WAGTAILADMIN_NOTIFICATION_INCLUDE_SUPERUSERS`, the superuser should get a workflow email self.assertIn(self.superuser.email, workflow_submission_emailed_addresses) # as the submitter was the triggering user, the submitter should not get an email notification self.assertNotIn(self.submitter.email, workflow_submission_emailed_addresses) ``` ###Assistant : Test that 'submitted' notifications for WorkflowState and TaskState are both sent correctly
396
def forward(self, masks_queries_logits, class_queries_logits, mask_labels, class_labels) -> List[Tuple[Tensor]]: indices: List[Tuple[np.array]] = [] preds_masks = masks_queries_logits preds_probs = class_queries_logits.softmax(dim=-1) # downsample all masks in one go -> save memory mask_labels = nn.functional.interpolate(mask_labels, size=preds_masks.shape[-2:], mode="nearest") # iterate through batch size for pred_probs, pred_mask, target_mask, labels in zip(preds_probs, preds_masks, mask_labels, class_labels): # Compute the classification cost. Contrary to the loss, we don't use the NLL, # but approximate it in 1 - proba[target class]. # The 1 is a constant that doesn't change the matching, it can be ommitted. cost_class = -pred_probs[:, labels] # flatten spatial dimension "q h w -> q (h w)" num_queries, height, width = pred_mask.shape pred_mask_flat = pred_mask.view(num_queries, height * width) # [num_queries, H*W] # same for target_mask "c h w -> c (h w)" num_channels, height, width = target_mask.shape target_mask_flat = target_mask.view(num_channels, height * width) # [num_total_labels, H*W] # compute the focal loss between each mask pairs -> shape [NUM_QUERIES, CLASSES] cost_mask = pair_wise_sigmoid_focal_loss(pred_mask_flat, target_mask_flat) # Compute the dice loss betwen each mask pairs -> shape [NUM_QUERIES, CLASSES] cost_dice = pair_wise_dice_loss(pred_mask_flat, target_mask_flat) # final cost matrix cost_matrix = self.cost_mask * cost_mask + self.cost_class * cost_class + self.cost_dice * cost_dice # do the assigmented using the hungarian algorithm in scipy assigned_indices: Tuple[np.array] = linear_sum_assignment(cost_matrix.cpu()) indices.append(assigned_indices) # It could be stacked in one tensor matched_indices = [ (torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices ] return matched_indices
Performs the matching Params: masks_queries_logits (`torch.Tensor`): A tensor` of dim `batch_size, num_queries, num_classes` with the classification logits. class_queries_logits (`torch.Tensor`): A tensor` of dim `batch_size, num_queries, height, width` with the predicted masks. class_labels (`torch.Tensor`): A tensor` of dim `num_target_boxes` (where num_target_boxes is the number of ground-truth objects in the target) containing the class labels. mask_labels (`torch.Tensor`): A tensor` of dim `num_target_boxes, height, width` containing the target masks. Returns: `List[Tuple[Tensor]]`: A list of size batch_size, containing tuples of (index_i, index_j) where: - index_i is the indices of the selected predictions (in order) - index_j is the indices of the corresponding selected labels (in order) For each batch element, it holds: len(index_i) = len(index_j) = min(num_queries, num_target_boxes).
114
229
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def forward(self, masks_queries_logits, class_queries_logits, mask_labels, class_labels) -> List[Tuple[Tensor]]: indices: List[Tuple[np.array]] = [] preds_masks = masks_queries_logits preds_probs = class_queries_logits.softmax(dim=-1) # downsample all masks in one go -> save memory mask_labels = nn.functional.interpolate(mask_labels, size=preds_masks.shape[-2:], mode="nearest") # iterate through batch size for pred_probs, pred_mask, target_mask, labels in zip(preds_probs, preds_masks, mask_labels, class_labels): # Compute the classification cost. Contrary to the loss, we don't use the NLL, # but approximate it in 1 - proba[target class]. # The 1 is a constant that doesn't change the matching, it can be ommitted. cost_class = -pred_probs[:, labels] # flatten spatial dimension "q h w -> q (h w)" num_queries, height, width = pred_mask.shape pred_mask_flat = pred_mask.view(num_queries, height * width) # [num_queries, H*W] # same for target_mask "c h w -> c (h w)" num_channels, height, width = target_mask.shape target_mask_flat = target_mask.view(num_channels, height * width) # [num_total_labels, H*W] # compute the focal loss between each mask pairs -> shape [NUM_QUERIES, CLASSES] cost_mask = pair_wise_sigmoid_focal_loss(pred_mask_flat, target_mask_flat) # Compute the dice loss betwen each mask pairs -> shape [NUM_QUERIES, CLASSES] cost_dice = pair_wise_dice_loss(pred_mask_flat, target_mask_flat) # final cost matrix cost_matrix = self.cost_mask * cost_mask + self.cost_class * cost_class + self.cost_dice * cost_dice # do the assigmented using the hungarian algorithm in scipy assigned_indices: Tuple[np.array] = linear_sum_assignment(cost_matrix.cpu()) indices.append(assigned_indices) # It could be stacked in one tensor matched_indices = [ (torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices ] return matched_indices ``` ###Assistant : Performs the matching Params: masks_queries_logits (`torch.Tensor`): A tensor` of dim `batch_size, num_queries, num_classes` with the classification logits. class_queries_logits (`torch.Tensor`): A tensor` of dim `batch_size, num_queries, height, width` with the predicted masks. class_labels (`torch.Tensor`): A tensor` of dim `num_target_boxes` (where num_target_boxes is the number of ground-truth objects in the target) containing the class labels. mask_labels (`torch.Tensor`): A tensor` of dim `num_target_boxes, height, width` containing the target masks. Returns: `List[Tuple[Tensor]]`: A list of size batch_size, containing tuples of (index_i, index_j) where: - index_i is the indices of the selected predictions (in order) - index_j is the indices of the corresponding selected labels (in order) For each batch element, it holds: len(index_i) = len(index_j) = min(num_queries, num_target_boxes).
397
def cancel_dispatcher_process(self): if not self.celery_task_id: return canceled = [] try: # Use control and reply mechanism to cancel and obtain confirmation timeout = 5 canceled = ControlDispatcher('dispatcher', self.controller_node).cancel([self.celery_task_id]) except socket.timeout: logger.error(f'could not reach dispatcher on {self.controller_node} within {timeout}s') except Exception: logger.exception("error encountered when checking task status") return bool(self.celery_task_id in canceled) # True or False, whether confirmation was obtained
Returns True if dispatcher running this job acknowledged request and sent SIGTERM
12
58
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def cancel_dispatcher_process(self): if not self.celery_task_id: return canceled = [] try: # Use control and reply mechanism to cancel and obtain confirmation timeout = 5 canceled = ControlDispatcher('dispatcher', self.controller_node).cancel([self.celery_task_id]) except socket.timeout: logger.error(f'could not reach dispatcher on {self.controller_node} within {timeout}s') except Exception: logger.exception("error encountered when checking task status") return bool(self.celery_task_id in canceled) # True or False, whether confirmation was obtained ``` ###Assistant : Returns True if dispatcher running this job acknowledged request and sent SIGTERM
398
def _mangle_index_names(cls, names): return [ f"__index__{i}_{'__None__' if n is None else n}" for i, n in enumerate(names) ]
Return mangled index names for index labels. Mangled names are used for index columns because index labels cannot always be used as HDK table column names. E.e. label can be a non-string value or an unallowed string (empty strings, etc.) for a table column name. Parameters ---------- names : list of str Index labels. Returns ------- list of str Mangled names.
61
18
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def _mangle_index_names(cls, names): return [ f"__index__{i}_{'__None__' if n is None else n}" for i, n in enumerate(names) ] ``` ###Assistant : Return mangled index names for index labels. Mangled names are used for index columns because index labels cannot always be used as HDK table column names. E.e. label can be a non-string value or an unallowed string (empty strings, etc.) for a table column name. Parameters ---------- names : list of str Index labels. Returns ------- list of str Mangled names.
399
def get_b2cs_json(data, gstin): company_state_number = gstin[0:2] out = [] for d in data: if not d.get("place_of_supply"): frappe.throw( _( ).format(frappe.bold("Place Of Supply")) ) pos = d.get("place_of_supply").split("-")[0] tax_details = {} rate = d.get("rate", 0) tax = flt((d["taxable_value"] * rate) / 100.0, 2) if company_state_number == pos: tax_details.update({"camt": flt(tax / 2.0, 2), "samt": flt(tax / 2.0, 2)}) else: tax_details.update({"iamt": tax}) inv = { "sply_ty": "INTRA" if company_state_number == pos else "INTER", "pos": pos, "typ": d.get("type"), "txval": flt(d.get("taxable_value"), 2), "rt": rate, "iamt": flt(tax_details.get("iamt"), 2), "camt": flt(tax_details.get("camt"), 2), "samt": flt(tax_details.get("samt"), 2), "csamt": flt(d.get("cess_amount"), 2), } if d.get("type") == "E" and d.get("ecommerce_gstin"): inv.update({"etin": d.get("ecommerce_gstin")}) out.append(inv) return out
{0} not entered in some invoices. Please update and try again
11
101
Python
###User : Below is a Python method which does a task. Create a documentation for the below code : ```Python def get_b2cs_json(data, gstin): company_state_number = gstin[0:2] out = [] for d in data: if not d.get("place_of_supply"): frappe.throw( _( ).format(frappe.bold("Place Of Supply")) ) pos = d.get("place_of_supply").split("-")[0] tax_details = {} rate = d.get("rate", 0) tax = flt((d["taxable_value"] * rate) / 100.0, 2) if company_state_number == pos: tax_details.update({"camt": flt(tax / 2.0, 2), "samt": flt(tax / 2.0, 2)}) else: tax_details.update({"iamt": tax}) inv = { "sply_ty": "INTRA" if company_state_number == pos else "INTER", "pos": pos, "typ": d.get("type"), "txval": flt(d.get("taxable_value"), 2), "rt": rate, "iamt": flt(tax_details.get("iamt"), 2), "camt": flt(tax_details.get("camt"), 2), "samt": flt(tax_details.get("samt"), 2), "csamt": flt(d.get("cess_amount"), 2), } if d.get("type") == "E" and d.get("ecommerce_gstin"): inv.update({"etin": d.get("ecommerce_gstin")}) out.append(inv) return out ``` ###Assistant : {0} not entered in some invoices. Please update and try again