language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
pypa__warehouse
tests/unit/admin/views/test_prohibited_project_names.py
{ "start": 4288, "end": 9223 }
class ____: def test_no_project(self): request = pretend.stub(POST={}) with pytest.raises(HTTPBadRequest): views.add_prohibited_project_names(request) def test_no_confirm(self): request = pretend.stub( POST={"project": "foo"}, session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)), current_route_path=lambda: "/foo/bar/", ) result = views.add_prohibited_project_names(request) assert request.session.flash.calls == [ pretend.call("Confirm the prohibited project name request", queue="error") ] assert result.status_code == 303 assert result.headers["Location"] == "/foo/bar/" def test_wrong_confirm(self): request = pretend.stub( POST={"project": "foo", "confirm": "bar"}, session=pretend.stub(flash=pretend.call_recorder(lambda *a, **kw: None)), current_route_path=lambda: "/foo/bar/", ) result = views.add_prohibited_project_names(request) assert request.session.flash.calls == [ pretend.call("'bar' is not the same as 'foo'", queue="error") ] assert result.status_code == 303 assert result.headers["Location"] == "/foo/bar/" @pytest.mark.parametrize( ("project_name", "prohibit_name"), [ ("foobar", "foobar"), ("FoObAr", "fOoBaR"), ], ) def test_already_existing_prohibited_project_names( self, db_request, project_name, prohibit_name ): ProhibitedProjectFactory.create(name=project_name) db_request.db.expire_all() db_request.user = UserFactory.create() db_request.POST["project"] = prohibit_name db_request.POST["confirm"] = prohibit_name db_request.POST["comment"] = "This is a comment" db_request.session = pretend.stub( flash=pretend.call_recorder(lambda *a, **kw: None) ) db_request.route_path = lambda a: "/admin/prohibited_project_names/" result = views.add_prohibited_project_names(db_request) assert db_request.session.flash.calls == [ pretend.call( f"{prohibit_name!r} has already been prohibited.", queue="error", ) ] assert result.status_code == 303 assert result.headers["Location"] == "/admin/prohibited_project_names/" def test_adds_prohibited_project_name(self, db_request): db_request.user = UserFactory.create() db_request.POST["project"] = "foo" db_request.POST["confirm"] = "foo" db_request.POST["comment"] = "This is a comment" db_request.session = pretend.stub( flash=pretend.call_recorder(lambda *a, **kw: None) ) db_request.route_path = lambda a: "/admin/prohibited_project_names/" views.add_prohibited_project_names(db_request) assert db_request.session.flash.calls == [ pretend.call("Prohibited Project Name 'foo'", queue="success") ] prohibited_project_name = ( db_request.db.query(ProhibitedProjectName) .filter(ProhibitedProjectName.name == "foo") .one() ) assert prohibited_project_name.name == "foo" assert prohibited_project_name.prohibited_by == db_request.user assert prohibited_project_name.comment == "This is a comment" def test_adds_prohibited_project_name_with_deletes(self, db_request): db_request.user = UserFactory.create() db_request.POST["project"] = "foo" db_request.POST["confirm"] = "foo" db_request.POST["comment"] = "This is a comment" db_request.session = pretend.stub( flash=pretend.call_recorder(lambda *a, **kw: None) ) db_request.route_path = lambda a: "/admin/prohibited_project_names/" project = ProjectFactory.create(name="foo") release = ReleaseFactory.create(project=project) FileFactory.create(release=release, filename="who cares") RoleFactory.create(project=project, user=db_request.user) views.add_prohibited_project_names(db_request) assert db_request.session.flash.calls == [ pretend.call("Deleted the project 'foo'", queue="success"), pretend.call("Prohibited Project Name 'foo'", queue="success"), ] prohibited_project_name = ( db_request.db.query(ProhibitedProjectName) .filter(ProhibitedProjectName.name == "foo") .one() ) assert prohibited_project_name.name == "foo" assert prohibited_project_name.prohibited_by == db_request.user assert prohibited_project_name.comment == "This is a comment" assert not (db_request.db.query(Project).filter(Project.name == "foo").count())
TestAddProhibitedProjectName
python
apache__airflow
airflow-core/src/airflow/models/asset.py
{ "start": 19438, "end": 21482 }
class ____(Base): """References from a DAG to an asset of which it is a consumer.""" asset_id: Mapped[int] = mapped_column(Integer, primary_key=True, nullable=False) dag_id: Mapped[str] = mapped_column(StringID(), primary_key=True, nullable=False) created_at: Mapped[datetime] = mapped_column(UtcDateTime, default=timezone.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column( UtcDateTime, default=timezone.utcnow, onupdate=timezone.utcnow, nullable=False ) asset = relationship("AssetModel", back_populates="scheduled_dags") dag = relationship("DagModel", back_populates="schedule_asset_references") queue_records = relationship( "AssetDagRunQueue", primaryjoin="""and_( DagScheduleAssetReference.asset_id == foreign(AssetDagRunQueue.asset_id), DagScheduleAssetReference.dag_id == foreign(AssetDagRunQueue.target_dag_id), )""", cascade="all, delete, delete-orphan", ) __tablename__ = "dag_schedule_asset_reference" __table_args__ = ( PrimaryKeyConstraint(asset_id, dag_id, name="dsar_pkey"), ForeignKeyConstraint( (asset_id,), ["asset.id"], name="dsar_asset_fkey", ondelete="CASCADE", ), ForeignKeyConstraint( columns=(dag_id,), refcolumns=["dag.dag_id"], name="dsar_dag_id_fkey", ondelete="CASCADE", ), Index("idx_dag_schedule_asset_reference_dag_id", dag_id), ) def __eq__(self, other: object) -> bool: if isinstance(other, self.__class__): return self.asset_id == other.asset_id and self.dag_id == other.dag_id return NotImplemented def __hash__(self): return hash(self.__mapper__.primary_key) def __repr__(self): args = [f"{attr}={getattr(self, attr)!r}" for attr in [x.name for x in self.__mapper__.primary_key]] return f"{self.__class__.__name__}({', '.join(args)})"
DagScheduleAssetReference
python
ansible__ansible
lib/ansible/parsing/mod_args.py
{ "start": 2630, "end": 15090 }
class ____: """ There are several ways a module and argument set can be expressed: # legacy form (for a shell command) - action: shell echo hi # common shorthand for local actions vs delegate_to - local_action: shell echo hi # most commonly: - copy: src=a dest=b # legacy form - action: copy src=a dest=b # complex args form, for passing structured data - copy: src: a dest: b # gross, but technically legal - action: module: copy args: src: a dest: b # Standard YAML form for command-type modules. In this case, the args specified # will act as 'defaults' and will be overridden by any args specified # in one of the other formats (complex args under the action, or # parsed from the k=v string - command: 'pwd' args: chdir: '/tmp' This class has some of the logic to canonicalize these into the form - module: <module_name> delegate_to: <optional> args: <args> Args may also be munged for certain shell command parameters. """ def __init__(self, task_ds=None, collection_list=None): task_ds = {} if task_ds is None else task_ds if not isinstance(task_ds, dict): raise AnsibleAssertionError("the type of 'task_ds' should be a dict, but is a %s" % type(task_ds)) self._task_ds = task_ds self._collection_list = collection_list # delayed local imports to prevent circular import from ansible.playbook.task import Task from ansible.playbook.handler import Handler # store the valid Task/Handler attrs for quick access self._task_attrs = set(Task.fattributes) self._task_attrs.update(set(Handler.fattributes)) # HACK: why are these not FieldAttributes on task with a post-validate to check usage? self._task_attrs.update(['local_action', 'static']) self._task_attrs = frozenset(self._task_attrs) self._resolved_action = None def _split_module_string(self, module_string: str) -> tuple[str, str]: """ when module names are expressed like: action: copy src=a dest=b the first part of the string is the name of the module and the rest are strings pertaining to the arguments. """ tokens = split_args(module_string) if len(tokens) > 1: result = (tokens[0].strip(), " ".join(tokens[1:])) else: result = (tokens[0].strip(), "") return AnsibleTagHelper.tag_copy(module_string, result[0]), AnsibleTagHelper.tag_copy(module_string, result[1]) def _normalize_parameters(self, thing, action=None, additional_args=None): """ arguments can be fuzzy. Deal with all the forms. """ # final args are the ones we'll eventually return, so first update # them with any additional args specified, which have lower priority # than those which may be parsed/normalized next final_args = dict() if additional_args is not Sentinel: if isinstance(additional_args, str) and _jinja_bits.is_possibly_all_template(additional_args): final_args['_variable_params'] = additional_args elif isinstance(additional_args, dict): final_args.update(additional_args) elif additional_args is None: Display().deprecated( msg="Ignoring empty task `args` keyword.", version="2.23", help_text='A mapping or template which resolves to a mapping is required.', obj=self._task_ds, ) else: raise AnsibleParserError( message='The value of the task `args` keyword is invalid.', help_text='A mapping or template which resolves to a mapping is required.', obj=additional_args, ) # how we normalize depends if we figured out what the module name is # yet. If we have already figured it out, it's a 'new style' invocation. # otherwise, it's not if action is not None: args = self._normalize_new_style_args(thing, action, additional_args) else: (action, args) = self._normalize_old_style_args(thing) # this can occasionally happen, simplify if args and 'args' in args: tmp_args = args.pop('args') if isinstance(tmp_args, str): tmp_args = parse_kv(tmp_args) args.update(tmp_args) # only internal variables can start with an underscore, so # we don't allow users to set them directly in arguments if args and action not in FREEFORM_ACTIONS: for arg in args: arg = to_text(arg) if arg.startswith('_ansible_'): err_msg = ( f"Invalid parameter specified beginning with keyword '_ansible_' for action '{action !s}': '{arg !s}'. " "The prefix '_ansible_' is reserved for internal use only." ) raise AnsibleError(err_msg) # finally, update the args we're going to return with the ones # which were normalized above if args: final_args.update(args) return (action, final_args) def _normalize_new_style_args(self, thing, action, additional_args): """ deals with fuzziness in new style module invocations accepting key=value pairs and dictionaries, and returns a dictionary of arguments possible example inputs: 'echo hi', 'shell' {'region': 'xyz'}, 'ec2' standardized outputs like: { _raw_params: 'echo hi', _uses_shell: True } """ if isinstance(thing, dict): # form is like: { xyz: { x: 2, y: 3 } } args = thing elif isinstance(thing, str): # form is like: copy: src=a dest=b check_raw = action in FREEFORM_ACTIONS args = parse_kv(thing, check_raw=check_raw) args_keys = set(args) - {'_raw_params'} if args_keys and additional_args is not Sentinel: kv_args = ', '.join(repr(arg) for arg in sorted(args_keys)) Display().deprecated( msg=f"Merging legacy k=v args ({kv_args}) into task args.", help_text="Include all task args in the task `args` mapping.", version="2.23", obj=thing, ) elif isinstance(thing, EncryptedString): # k=v parsing intentionally omitted args = dict(_raw_params=thing) elif thing is None: # this can happen with modules which take no params, like ping: args = None else: raise AnsibleParserError("unexpected parameter type in action: %s" % type(thing), obj=self._task_ds) return args def _normalize_old_style_args(self, thing): """ deals with fuzziness in old-style (action/local_action) module invocations returns tuple of (module_name, dictionary_args) possible example inputs: { 'shell' : 'echo hi' } 'shell echo hi' {'module': 'ec2', 'x': 1 } standardized outputs like: ('ec2', { 'x': 1} ) """ action = None args = None if isinstance(thing, dict): # form is like: action: { module: 'copy', src: 'a', dest: 'b' } Display().deprecated("Using a mapping for `action` is deprecated.", version='2.23', help_text='Use a string value for `action`.', obj=thing) thing = thing.copy() if 'module' in thing: action, module_args = self._split_module_string(thing['module']) args = thing.copy() check_raw = action in FREEFORM_ACTIONS args.update(parse_kv(module_args, check_raw=check_raw)) del args['module'] elif isinstance(thing, str): # form is like: action: copy src=a dest=b (action, args) = self._split_module_string(thing) check_raw = action in FREEFORM_ACTIONS args = parse_kv(args, check_raw=check_raw) else: # need a dict or a string, so giving up raise AnsibleParserError("unexpected parameter type in action: %s" % type(thing), obj=self._task_ds) return (action, args) def parse(self, skip_action_validation=False): """ Given a task in one of the supported forms, parses and returns returns the action, arguments, and delegate_to values for the task, dealing with all sorts of levels of fuzziness. """ action = None delegate_to = self._task_ds.get('delegate_to', Sentinel) args = dict() # This is the standard YAML form for command-type modules. We grab # the args and pass them in as additional arguments, which can/will # be overwritten via dict updates from the other arg sources below additional_args = self._task_ds.get('args', Sentinel) # We can have one of action, local_action, or module specified # action if 'action' in self._task_ds: # an old school 'action' statement thing = self._task_ds['action'] action, args = self._normalize_parameters(thing, additional_args=additional_args) # local_action if 'local_action' in self._task_ds: # local_action is similar but also implies a delegate_to if action is not None: raise AnsibleParserError("action and local_action are mutually exclusive", obj=self._task_ds) thing = self._task_ds.get('local_action', '') delegate_to = 'localhost' action, args = self._normalize_parameters(thing, additional_args=additional_args) # module: <stuff> is the more new-style invocation # filter out task attributes so we're only querying unrecognized keys as actions/modules non_task_ds = dict((k, v) for k, v in self._task_ds.items() if (k not in self._task_attrs) and (not k.startswith('with_'))) # walk the filtered input dictionary to see if we recognize a module name for item, value in non_task_ds.items(): if item in BUILTIN_TASKS: is_action_candidate = True elif skip_action_validation: is_action_candidate = True else: try: # DTFIX-FUTURE: extract to a helper method, shared with Task.post_validate_args context = _get_action_context(item, self._collection_list) except AnsibleError as e: if e.obj is None: e.obj = self._task_ds raise e is_action_candidate = context.resolved and bool(context.redirect_list) if is_action_candidate: self._resolved_action = context.resolved_fqcn if is_action_candidate: # finding more than one module name is a problem if action is not None: raise AnsibleParserError("conflicting action statements: %s, %s" % (action, item), obj=self._task_ds) action = item thing = value action, args = self._normalize_parameters(thing, action=action, additional_args=additional_args) # if we didn't see any module in the task at all, it's not a task really if action is None: if non_task_ds: # there was one non-task action, but we couldn't find it bad_action = list(non_task_ds.keys())[0] raise AnsibleParserError("couldn't resolve module/action '{0}'. This often indicates a " "misspelling, missing collection, or incorrect module path.".format(bad_action), obj=self._task_ds) else: raise AnsibleParserError("no module/action detected in task.", obj=self._task_ds) return action, args, delegate_to
ModuleArgsParser
python
huggingface__transformers
tests/models/donut/test_image_processing_donut.py
{ "start": 10373, "end": 10576 }
class ____(DonutImageProcessingTest): def setUp(self): super().setUp() self.image_processor_tester = DonutImageProcessingTester(self, do_align_axis=True)
DonutImageProcessingAlignAxisTest
python
dagster-io__dagster
python_modules/dagster/dagster/_grpc/types.py
{ "start": 13775, "end": 14793 }
class ____( NamedTuple( "_ListRepositoriesInput", [ ("module_name", Optional[str]), ("python_file", Optional[str]), ("working_directory", Optional[str]), ("attribute", Optional[str]), ], ) ): def __new__( cls, module_name: Optional[str], python_file: Optional[str], working_directory: Optional[str], attribute: Optional[str], ): check.invariant(not (module_name and python_file), "Must set only one") check.invariant(module_name or python_file, "Must set at least one") return super().__new__( cls, module_name=check.opt_str_param(module_name, "module_name"), python_file=check.opt_str_param(python_file, "python_file"), working_directory=check.opt_str_param(working_directory, "working_directory"), attribute=check.opt_str_param(attribute, "attribute"), ) @whitelist_for_serdes
ListRepositoriesInput
python
weaviate__weaviate-python-client
weaviate/collections/aggregations/over_all/sync.py
{ "start": 191, "end": 250 }
class ____(_OverAllExecutor[ConnectionSync]): pass
_OverAll
python
huggingface__transformers
src/transformers/models/glpn/modeling_glpn.py
{ "start": 8631, "end": 9260 }
class ____(nn.Module): def __init__(self, dim=768): super().__init__() self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim) def forward(self, hidden_states, height, width): batch_size, seq_len, num_channels = hidden_states.shape hidden_states = hidden_states.transpose(1, 2).view(batch_size, num_channels, height, width) hidden_states = self.dwconv(hidden_states) hidden_states = hidden_states.flatten(2).transpose(1, 2) return hidden_states # Copied from transformers.models.segformer.modeling_segformer.SegformerMixFFN with Segformer->GLPN
GLPNDWConv
python
langchain-ai__langchain
libs/core/langchain_core/prompts/dict.py
{ "start": 433, "end": 4700 }
class ____(RunnableSerializable[dict, dict]): """Template represented by a dict. Recognizes variables in f-string or mustache formatted string dict values. Does NOT recognize variables in dict keys. Applies recursively. """ template: dict[str, Any] template_format: Literal["f-string", "mustache"] @property def input_variables(self) -> list[str]: """Template input variables.""" return _get_input_variables(self.template, self.template_format) def format(self, **kwargs: Any) -> dict[str, Any]: """Format the prompt with the inputs. Returns: A formatted dict. """ return _insert_input_variables(self.template, kwargs, self.template_format) async def aformat(self, **kwargs: Any) -> dict[str, Any]: """Format the prompt with the inputs. Returns: A formatted dict. """ return self.format(**kwargs) @override def invoke( self, input: dict, config: RunnableConfig | None = None, **kwargs: Any ) -> dict: return self._call_with_config( lambda x: self.format(**x), input, ensure_config(config), run_type="prompt", serialized=self._serialized, **kwargs, ) @property def _prompt_type(self) -> str: return "dict-prompt" @cached_property def _serialized(self) -> dict[str, Any]: return dumpd(self) @classmethod def is_lc_serializable(cls) -> bool: """Return `True` as this class is serializable.""" return True @classmethod def get_lc_namespace(cls) -> list[str]: """Get the namespace of the LangChain object. Returns: `["langchain_core", "prompts", "dict"]` """ return ["langchain_core", "prompts", "dict"] def pretty_repr(self, *, html: bool = False) -> str: """Human-readable representation. Args: html: Whether to format as HTML. Returns: Human-readable representation. """ raise NotImplementedError def _get_input_variables( template: dict, template_format: Literal["f-string", "mustache"] ) -> list[str]: input_variables = [] for v in template.values(): if isinstance(v, str): input_variables += get_template_variables(v, template_format) elif isinstance(v, dict): input_variables += _get_input_variables(v, template_format) elif isinstance(v, (list, tuple)): for x in v: if isinstance(x, str): input_variables += get_template_variables(x, template_format) elif isinstance(x, dict): input_variables += _get_input_variables(x, template_format) return list(set(input_variables)) def _insert_input_variables( template: dict[str, Any], inputs: dict[str, Any], template_format: Literal["f-string", "mustache"], ) -> dict[str, Any]: formatted = {} formatter = DEFAULT_FORMATTER_MAPPING[template_format] for k, v in template.items(): if isinstance(v, str): formatted[k] = formatter(v, **inputs) elif isinstance(v, dict): if k == "image_url" and "path" in v: msg = ( "Specifying image inputs via file path in environments with " "user-input paths is a security vulnerability. Out of an abundance " "of caution, the utility has been removed to prevent possible " "misuse." ) warnings.warn(msg, stacklevel=2) formatted[k] = _insert_input_variables(v, inputs, template_format) elif isinstance(v, (list, tuple)): formatted_v = [] for x in v: if isinstance(x, str): formatted_v.append(formatter(x, **inputs)) elif isinstance(x, dict): formatted_v.append( _insert_input_variables(x, inputs, template_format) ) formatted[k] = type(v)(formatted_v) else: formatted[k] = v return formatted
DictPromptTemplate
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 7594, "end": 7774 }
class ____(sgqlc.types.Enum): """ See source code for more info. """ __schema__ = graphql_schema __choices__ = ("CREATED_AT", "LOGIN")
EnterpriseMemberOrderField
python
kamyu104__LeetCode-Solutions
Python/minimum-cost-to-split-an-array.py
{ "start": 57, "end": 645 }
class ____(object): def minCost(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ dp = [float("inf")]*(len(nums)+1) dp[0] = 0 for i in xrange(len(dp)-1): cnt = [0]*len(nums) d = 0 for j in xrange(i+1, len(dp)): cnt[nums[j-1]] += 1 if cnt[nums[j-1]] == 1: d += 1 elif cnt[nums[j-1]] == 2: d -= 1 dp[j] = min(dp[j], dp[i]+k+((j-i)-d)) return dp[-1]
Solution
python
great-expectations__great_expectations
contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/expectations/expect_profile_numeric_columns_percent_diff_between_exclusive_threshold_range.py
{ "start": 7869, "end": 15679 }
class ____( ProfileNumericColumnsDiffExpectation ): """Expect a statistic's percent delta for a given column of a DataProfiler percent difference report to be within the specified threshold, exclusive. This expectation takes the percent difference report between the data it is called on and a DataProfiler profile of the same schema loaded from a provided path. Each numerical column percent delta will be checked against a user provided dictionary of columns paired with dictionaries of statistics containing lower and upper bounds. This function builds upon the custom ProfileNumericColumnsDiff Expectation of Capital One's DataProfiler Expectations. It is expected that a statistic's percent delta for a given column is within the specified threshold, exclusive. Args: profile_path (str): A path to a saved DataProfiler profile object on the local filesystem. limit_check_report_keys (dict): A dict, containing column names as keys and dicts as values that contain statistics as keys and dicts as values containing two keys: "lower" denoting the lower bound for the threshold range, and "upper" denoting the upper bound for the threshold range. mostly (float - optional): a value indicating the lower bound percentage of successful values that must be present to evaluate to success=True. validator.expect_profile_numerical_columns_percent_diff_between_exclusive_threshold_range( profile_path = "C:/path_to/my_profile.pkl", limit_check_report_keys = { "column_one": { "min": {"lower": 0.5, "upper": 1.5}, #Indicating 50% lower bound and 150% upper bound }, "*": { "*": {"lower": 0.0, "upper": 2.0}, #Indicating 0% lower bound and 200% upper bound }, } ) Note: In limit_check_report_keys, "*" in place of a column denotes a general operator in which the value it stores will be applied to every column in the data that has no explicit key. "*" in place of a statistic denotes a general operator in which the bounds it stores will be applied to every statistic for the given column that has no explicit key. """ example_profile_data = [ [2, 5, "10", "ten", 25], [4, 10, "20", "twenty", 50], [6, 15, "30", "thirty", 75], [8, 20, "40", "forty", 100], [10, 25, "50", "fifty", 125], ] example_profile_columns = [ "by_2", "by_5", "str_by_10", "words_by_10", "by_25", ] df = pd.DataFrame(example_profile_data, columns=example_profile_columns) profiler_opts = dp.ProfilerOptions() profiler_opts.structured_options.multiprocess.is_enabled = False example_profile = dp.Profiler(df, options=profiler_opts) profile_path = "/example_profiles/expect_profile_diff_less_than_threshold_profile.pkl" dir_path = os.path.dirname(os.path.abspath(__file__)) # noqa: PTH120, PTH100 profile_path = dir_path + profile_path example_profile.save(filepath=profile_path) examples = [ { "data": { "by_2": [4, 6, 8, 10, 12], "by_5": [10, 15, 20, 25, 30], "str_by_10": ["20", "30", "40", "50", "60"], "words_by_10": ["twenty", "thirty", "forty", "fifty", "sixty"], "by_25": [50, 75, 100, 125, 150], }, "tests": [ { "title": "profile_min_delta_witin_threshold", "exact_match_out": False, "include_in_gallery": True, "in": { "profile_path": profile_path, "limit_check_report_keys": { "*": { "min": {"lower": 0.5, "upper": 2.0}, }, }, }, "out": {"success": True}, }, { "title": "single_column_min_delta_witin_threshold", "exact_match_out": False, "include_in_gallery": True, "in": { "profile_path": profile_path, "limit_check_report_keys": { "by_2": { "min": {"lower": 0.99, "upper": 1.01}, }, }, }, "out": {"success": True}, }, { "title": "single_column_min_delta_equals_threshold", "exact_match_out": False, "include_in_gallery": True, "in": { "profile_path": profile_path, "limit_check_report_keys": { "by_2": { "min": {"lower": 1.0, "upper": 1.0}, }, }, }, "out": {"success": False}, }, { "title": "profile_all_stats_beyond_delta_threshold", "exact_match_out": False, "include_in_gallery": True, "in": { "profile_path": profile_path, "limit_check_report_keys": { "*": {"*": {"lower": 0, "upper": 0}}, }, }, "out": {"success": False}, }, ], }, ] profile_metric = "data_profiler.profile_numeric_columns_percent_diff_between_threshold_range" success_keys = ( "profile_path", "limit_check_report_keys", "numerical_diff_statistics", "mostly", ) default_limit_check_report_keys = { "*": { "min": {"lower": 0, "upper": 0}, "max": {"lower": 0, "upper": 0}, "sum": {"lower": 0, "upper": 0}, "mean": {"lower": 0, "upper": 0}, "median": {"lower": 0, "upper": 0}, "median_absolute_deviation": {"lower": 0, "upper": 0}, "variance": {"lower": 0, "upper": 0}, "stddev": {"lower": 0, "upper": 0}, "unique_count": {"lower": 0, "upper": 0}, "unique_ratio": {"lower": 0, "upper": 0}, "gini_impurity": {"lower": 0, "upper": 0}, "unalikeability": {"lower": 0, "upper": 0}, "sample_size": {"lower": 0, "upper": 0}, "null_count": {"lower": 0, "upper": 0}, } } numerical_diff_statistics = list(default_limit_check_report_keys["*"].keys()) default_kwarg_values = { "limit_check_report_keys": default_limit_check_report_keys, "numerical_diff_statistics": numerical_diff_statistics, "mostly": 1.0, } library_metadata = { "requirements": ["dataprofiler", "tensorflow", "scikit-learn", "numpy"], "maturity": "experimental", # "concept_only", "experimental", "beta", or "production" "tags": [ "dataprofiler", "dataassistance", ], # Tags for this Expectation in the Gallery "contributors": [ # Github handles for all contributors to this Expectation. "@stevensecreti", # Don't forget to add your github handle here! ], } if __name__ == "__main__": diagnostics_report = ( ExpectProfileNumericColumnsPercentDiffBetweenExclusiveThresholdRange().run_diagnostics() ) print(diagnostics_report.generate_checklist())
ExpectProfileNumericColumnsPercentDiffBetweenExclusiveThresholdRange
python
doocs__leetcode
solution/2700-2799/2771.Longest Non-decreasing Subarray From Two Arrays/Solution.py
{ "start": 0, "end": 594 }
class ____: def maxNonDecreasingLength(self, nums1: List[int], nums2: List[int]) -> int: n = len(nums1) f = g = 1 ans = 1 for i in range(1, n): ff = gg = 1 if nums1[i] >= nums1[i - 1]: ff = max(ff, f + 1) if nums1[i] >= nums2[i - 1]: ff = max(ff, g + 1) if nums2[i] >= nums1[i - 1]: gg = max(gg, f + 1) if nums2[i] >= nums2[i - 1]: gg = max(gg, g + 1) f, g = ff, gg ans = max(ans, f, g) return ans
Solution
python
django__django
tests/forms_tests/tests/tests.py
{ "start": 9344, "end": 12417 }
class ____(TestCase): def test_unicode_filename(self): # FileModel with Unicode filename and data. file1 = SimpleUploadedFile( "我隻氣墊船裝滿晒鱔.txt", "मेरी मँडराने वाली नाव सर्पमीनों से भरी ह".encode() ) f = FileForm(data={}, files={"file1": file1}, auto_id=False) self.assertTrue(f.is_valid()) self.assertIn("file1", f.cleaned_data) m = FileModel.objects.create(file=f.cleaned_data["file1"]) self.assertEqual( m.file.name, "tests/\u6211\u96bb\u6c23\u588a\u8239\u88dd\u6eff\u6652\u9c54.txt", ) m.file.delete() m.delete() def test_boundary_conditions(self): # Boundary conditions on a PositiveIntegerField. class BoundaryForm(ModelForm): class Meta: model = BoundaryModel fields = "__all__" f = BoundaryForm({"positive_integer": 100}) self.assertTrue(f.is_valid()) f = BoundaryForm({"positive_integer": 0}) self.assertTrue(f.is_valid()) f = BoundaryForm({"positive_integer": -100}) self.assertFalse(f.is_valid()) def test_formfield_initial(self): # If the model has default values for some fields, they are used as the # formfield initial values. class DefaultsForm(ModelForm): class Meta: model = Defaults fields = "__all__" self.assertEqual(DefaultsForm().fields["name"].initial, "class default value") self.assertEqual( DefaultsForm().fields["def_date"].initial, datetime.date(1980, 1, 1) ) self.assertEqual(DefaultsForm().fields["value"].initial, 42) r1 = DefaultsForm()["callable_default"].as_widget() r2 = DefaultsForm()["callable_default"].as_widget() self.assertNotEqual(r1, r2) # In a ModelForm that is passed an instance, the initial values come # from the instance's values, not the model's defaults. foo_instance = Defaults( name="instance value", def_date=datetime.date(1969, 4, 4), value=12 ) instance_form = DefaultsForm(instance=foo_instance) self.assertEqual(instance_form.initial["name"], "instance value") self.assertEqual(instance_form.initial["def_date"], datetime.date(1969, 4, 4)) self.assertEqual(instance_form.initial["value"], 12) from django.forms import CharField class ExcludingForm(ModelForm): name = CharField(max_length=255) class Meta: model = Defaults exclude = ["name", "callable_default"] f = ExcludingForm( {"name": "Hello", "value": 99, "def_date": datetime.date(1999, 3, 2)} ) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["name"], "Hello") obj = f.save() self.assertEqual(obj.name, "class default value") self.assertEqual(obj.value, 99) self.assertEqual(obj.def_date, datetime.date(1999, 3, 2))
FormsModelTestCase
python
keras-team__keras
keras/src/layers/preprocessing/image_preprocessing/bounding_boxes/formats.py
{ "start": 1456, "end": 1904 }
class ____: """XYWH contains axis indices for the XYWH format. All values in the XYWH format should be absolute pixel values. The XYWH format consists of the following required indices: - X: X coordinate of the left of the bounding box - Y: Y coordinate of the top of the bounding box - WIDTH: width of the bounding box - HEIGHT: height of the bounding box """ X = 0 Y = 1 WIDTH = 2 HEIGHT = 3
XYWH
python
tornadoweb__tornado
tornado/test/simple_httpclient_test.py
{ "start": 22686, "end": 23981 }
class ____(AsyncTestCase): def setUp(self): super().setUp() self.saved = AsyncHTTPClient._save_configuration() def tearDown(self): AsyncHTTPClient._restore_configuration(self.saved) super().tearDown() def test_max_clients(self): AsyncHTTPClient.configure(SimpleAsyncHTTPClient) with closing(AsyncHTTPClient(force_instance=True)) as client: self.assertEqual(client.max_clients, 10) # type: ignore with closing(AsyncHTTPClient(max_clients=11, force_instance=True)) as client: self.assertEqual(client.max_clients, 11) # type: ignore # Now configure max_clients statically and try overriding it # with each way max_clients can be passed AsyncHTTPClient.configure(SimpleAsyncHTTPClient, max_clients=12) with closing(AsyncHTTPClient(force_instance=True)) as client: self.assertEqual(client.max_clients, 12) # type: ignore with closing(AsyncHTTPClient(max_clients=13, force_instance=True)) as client: self.assertEqual(client.max_clients, 13) # type: ignore with closing(AsyncHTTPClient(max_clients=14, force_instance=True)) as client: self.assertEqual(client.max_clients, 14) # type: ignore
CreateAsyncHTTPClientTestCase
python
pytest-dev__pytest
testing/test_runner.py
{ "start": 5981, "end": 15483 }
class ____: def test_passfunction(self, pytester: Pytester) -> None: reports = pytester.runitem( """ def test_func(): pass """ ) rep = reports[1] assert rep.passed assert not rep.failed assert rep.outcome == "passed" assert not rep.longrepr def test_failfunction(self, pytester: Pytester) -> None: reports = pytester.runitem( """ def test_func(): assert 0 """ ) rep = reports[1] assert not rep.passed assert not rep.skipped assert rep.failed assert rep.when == "call" assert rep.outcome == "failed" # assert isinstance(rep.longrepr, ReprExceptionInfo) def test_skipfunction(self, pytester: Pytester) -> None: reports = pytester.runitem( """ import pytest def test_func(): pytest.skip("hello") """ ) rep = reports[1] assert not rep.failed assert not rep.passed assert rep.skipped assert rep.outcome == "skipped" # assert rep.skipped.when == "call" # assert rep.skipped.when == "call" # assert rep.skipped == "%sreason == "hello" # assert rep.skipped.location.lineno == 3 # assert rep.skipped.location.path # assert not rep.skipped.failurerepr def test_skip_in_setup_function(self, pytester: Pytester) -> None: reports = pytester.runitem( """ import pytest def setup_function(func): pytest.skip("hello") def test_func(): pass """ ) print(reports) rep = reports[0] assert not rep.failed assert not rep.passed assert rep.skipped # assert rep.skipped.reason == "hello" # assert rep.skipped.location.lineno == 3 # assert rep.skipped.location.lineno == 3 assert len(reports) == 2 assert reports[1].passed # teardown def test_failure_in_setup_function(self, pytester: Pytester) -> None: reports = pytester.runitem( """ import pytest def setup_function(func): raise ValueError(42) def test_func(): pass """ ) rep = reports[0] assert not rep.skipped assert not rep.passed assert rep.failed assert rep.when == "setup" assert len(reports) == 2 def test_failure_in_teardown_function(self, pytester: Pytester) -> None: reports = pytester.runitem( """ import pytest def teardown_function(func): raise ValueError(42) def test_func(): pass """ ) print(reports) assert len(reports) == 3 rep = reports[2] assert not rep.skipped assert not rep.passed assert rep.failed assert rep.when == "teardown" # assert rep.longrepr.reprcrash.lineno == 3 # assert rep.longrepr.reprtraceback.reprentries def test_custom_failure_repr(self, pytester: Pytester) -> None: pytester.makepyfile( conftest=""" import pytest class Function(pytest.Function): def repr_failure(self, excinfo): return "hello" """ ) reports = pytester.runitem( """ import pytest def test_func(): assert 0 """ ) rep = reports[1] assert not rep.skipped assert not rep.passed assert rep.failed # assert rep.outcome.when == "call" # assert rep.failed.where.lineno == 3 # assert rep.failed.where.path.basename == "test_func.py" # assert rep.failed.failurerepr == "hello" def test_teardown_final_returncode(self, pytester: Pytester) -> None: rec = pytester.inline_runsource( """ def test_func(): pass def teardown_function(func): raise ValueError(42) """ ) assert rec.ret == 1 def test_logstart_logfinish_hooks(self, pytester: Pytester) -> None: rec = pytester.inline_runsource( """ import pytest def test_func(): pass """ ) reps = rec.getcalls("pytest_runtest_logstart pytest_runtest_logfinish") assert [x._name for x in reps] == [ "pytest_runtest_logstart", "pytest_runtest_logfinish", ] for rep in reps: assert rep.nodeid == "test_logstart_logfinish_hooks.py::test_func" assert rep.location == ("test_logstart_logfinish_hooks.py", 1, "test_func") def test_exact_teardown_issue90(self, pytester: Pytester) -> None: rec = pytester.inline_runsource( """ import pytest class TestClass(object): def test_method(self): pass def teardown_class(cls): raise Exception() def test_func(): import sys # on python2 exc_info is kept till a function exits # so we would end up calling test functions while # sys.exc_info would return the indexerror # from guessing the lastitem excinfo = sys.exc_info() import traceback assert excinfo[0] is None, \ traceback.format_exception(*excinfo) def teardown_function(func): raise ValueError(42) """ ) reps = rec.getreports("pytest_runtest_logreport") print(reps) for i in range(2): assert reps[i].nodeid.endswith("test_method") assert reps[i].passed assert reps[2].when == "teardown" assert reps[2].failed assert len(reps) == 6 for i in range(3, 5): assert reps[i].nodeid.endswith("test_func") assert reps[i].passed assert reps[5].when == "teardown" assert reps[5].nodeid.endswith("test_func") assert reps[5].failed def test_exact_teardown_issue1206(self, pytester: Pytester) -> None: """Issue shadowing error with wrong number of arguments on teardown_method.""" rec = pytester.inline_runsource( """ import pytest class TestClass(object): def teardown_method(self, x, y, z): pass def test_method(self): assert True """ ) reps = rec.getreports("pytest_runtest_logreport") print(reps) assert len(reps) == 3 # assert reps[0].nodeid.endswith("test_method") assert reps[0].passed assert reps[0].when == "setup" # assert reps[1].nodeid.endswith("test_method") assert reps[1].passed assert reps[1].when == "call" # assert reps[2].nodeid.endswith("test_method") assert reps[2].failed assert reps[2].when == "teardown" longrepr = reps[2].longrepr assert isinstance(longrepr, ExceptionChainRepr) assert longrepr.reprcrash assert longrepr.reprcrash.message in ( "TypeError: teardown_method() missing 2 required positional arguments: 'y' and 'z'", # Python >= 3.10 "TypeError: TestClass.teardown_method() missing 2 required positional arguments: 'y' and 'z'", ) def test_failure_in_setup_function_ignores_custom_repr( self, pytester: Pytester ) -> None: pytester.makepyfile( conftest=""" import pytest class Function(pytest.Function): def repr_failure(self, excinfo): assert 0 """ ) reports = pytester.runitem( """ def setup_function(func): raise ValueError(42) def test_func(): pass """ ) assert len(reports) == 2 rep = reports[0] print(rep) assert not rep.skipped assert not rep.passed assert rep.failed # assert rep.outcome.when == "setup" # assert rep.outcome.where.lineno == 3 # assert rep.outcome.where.path.basename == "test_func.py" # assert isinstance(rep.failed.failurerepr, PythonFailureRepr) def test_systemexit_does_not_bail_out(self, pytester: Pytester) -> None: try: reports = pytester.runitem( """ def test_func(): raise SystemExit(42) """ ) except SystemExit: assert False, "runner did not catch SystemExit" rep = reports[1] assert rep.failed assert rep.when == "call" def test_exit_propagates(self, pytester: Pytester) -> None: try: pytester.runitem( """ import pytest def test_func(): raise pytest.exit.Exception() """ ) except pytest.exit.Exception: pass else: assert False, "did not raise"
BaseFunctionalTests
python
sqlalchemy__sqlalchemy
test/typing/plain_files/ext/association_proxy/association_proxy_three.py
{ "start": 869, "end": 1118 }
class ____(Base): __tablename__ = "user" id: Mapped[int] = mapped_column(primary_key=True) branch_id: Mapped[int] = mapped_column(ForeignKey("branch_milestones.id")) bm = BranchMilestone() x1 = bm.user_ids assert_type(x1, list[int])
User
python
bokeh__bokeh
src/bokeh/models/axes.py
{ "start": 13221, "end": 14687 }
class ____(LinearAxis): ''' An axis that picks nice numbers for tick locations on a Mercator scale. Configured with a ``MercatorTickFormatter`` by default. Args: dimension ('lat' or 'lon', optional) : Whether this axis will display latitude or longitude values. (default: 'lat') ''' def __init__(self, dimension='lat', *args, **kwargs) -> None: super().__init__(*args, **kwargs) # Just being careful. It would be defeat the purpose for anyone to actually # configure this axis with different kinds of tickers or formatters. if isinstance(self.ticker, MercatorTicker): self.ticker.dimension = dimension if isinstance(self.formatter, MercatorTickFormatter): self.formatter.dimension = dimension ticker = Override(default=InstanceDefault(MercatorTicker)) formatter = Override(default=InstanceDefault(MercatorTickFormatter)) #----------------------------------------------------------------------------- # Dev API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Private API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Code #-----------------------------------------------------------------------------
MercatorAxis
python
great-expectations__great_expectations
contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_weekday.py
{ "start": 1921, "end": 4442 }
class ____(ColumnMapExpectation): """Expect column values to be weekdays.""" # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "all_weekday": [ "2022-03-28", "2022.03.29", "30/03/2022", "2022/03/31", "2022-04-01", ], "some_other": [ "2022-03-27", "2022.03.29", "30/03/2022", "2022/03/31", "2022-04-02", ], }, "tests": [ { "title": "basic_positive_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "all_weekday"}, "out": { "success": True, }, }, { "title": "basic_negative_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "some_other", "mostly": 0.8}, "out": { "success": False, }, }, ], } ] # This is the id string of the Metric used by this Expectation. # For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above. map_metric = "column_values.weekday" # This is a list of parameter names that can affect whether the Expectation evaluates to True or False success_keys = ("mostly",) # This dictionary contains default values for any parameters that should have default values default_kwarg_values = {} # This object contains metadata for display in the public Gallery library_metadata = { "maturity": "experimental", "tags": [ "hackathon-22", "experimental", "typed-entities", ], # Tags for this Expectation in the Gallery "contributors": [ # Github handles for all contributors to this Expectation. "@szecsip", # Don't forget to add your github handle here! ], } if __name__ == "__main__": ExpectColumnValuesToBeWeekday().print_diagnostic_checklist()
ExpectColumnValuesToBeWeekday
python
dagster-io__dagster
python_modules/dagster/dagster/_grpc/server.py
{ "start": 58658, "end": 64613 }
class ____(Exception): def __init__(self, port=None, socket=None): super().__init__( "Could not start server with " + (f"port {port}" if port is not None else f"socket {socket}") ) def wait_for_grpc_server( server_process: subprocess.Popen, client: "DagsterGrpcClient", subprocess_args: Sequence[str], timeout: int = 60, additional_timeout_msg: Optional[str] = None, ) -> None: start_time = time.time() last_error = None while True: try: client.ping("") return except DagsterUserCodeUnreachableError: last_error = serializable_error_info_from_exc_info(sys.exc_info()) if timeout > 0 and (time.time() - start_time > timeout): raise Exception( f"Timed out waiting for gRPC server to start after {timeout}s. {additional_timeout_msg}Launched with arguments:" f' "{" ".join(subprocess_args)}". Most recent connection error: {last_error}' ) if server_process.poll() is not None: raise Exception( f"gRPC server exited with return code {server_process.returncode} while starting up" f' with the command: "{" ".join(subprocess_args)}"' ) sleep(0.1) def open_server_process( instance_ref: Optional[InstanceRef], port: Optional[int], socket: Optional[str], server_command: GrpcServerCommand, location_name: Optional[str] = None, loadable_target_origin: Optional[LoadableTargetOrigin] = None, max_workers: Optional[int] = None, heartbeat: bool = False, heartbeat_timeout: int = 30, fixed_server_id: Optional[str] = None, startup_timeout: int = 20, cwd: Optional[str] = None, log_level: str = "INFO", inject_env_vars_from_instance: bool = True, container_image: Optional[str] = None, container_context: Optional[dict[str, Any]] = None, enable_metrics: bool = False, additional_timeout_msg: Optional[str] = None, defs_state_info: Optional[DefsStateInfo] = None, ): check.invariant((port or socket) and not (port and socket), "Set only port or socket") check.opt_inst_param(loadable_target_origin, "loadable_target_origin", LoadableTargetOrigin) check.opt_int_param(max_workers, "max_workers") executable_path = loadable_target_origin.executable_path if loadable_target_origin else None entrypoint = get_python_environment_entry_point(executable_path or sys.executable) subprocess_args = [ *entrypoint, *server_command.server_command, *(["--port", str(port)] if port else []), *(["--socket", socket] if socket else []), *(["-n", str(max_workers)] if max_workers else []), *(["--heartbeat"] if heartbeat else []), *(["--heartbeat-timeout", str(heartbeat_timeout)] if heartbeat_timeout else []), *(["--fixed-server-id", fixed_server_id] if fixed_server_id else []), *(["--log-level", log_level]), # only use the Python environment if it has been explicitly set in the workspace, *(["--use-python-environment-entry-point"] if executable_path else []), *(["--inject-env-vars-from-instance"] if inject_env_vars_from_instance else []), *(["--instance-ref", serialize_value(instance_ref)] if instance_ref else []), *(["--location-name", location_name] if location_name else []), *(["--container-image", container_image] if container_image else []), *(["--container-context", json.dumps(container_context)] if container_context else []), *(["--enable-metrics"] if enable_metrics else []), *(["--defs-state-info", serialize_value(defs_state_info)] if defs_state_info else []), ] if loadable_target_origin: subprocess_args += loadable_target_origin.get_cli_args() env = { **os.environ, } if ( executable_path and is_likely_venv_executable(executable_path) and executable_path != sys.executable ): # ensure that if a venv is being used as an executable path that the same PATH # that would be set if the venv was activated is also set in the launched # subprocess current_path = os.environ.get("PATH") added_path = os.path.dirname(executable_path) env["PATH"] = f"{added_path}{os.pathsep}{current_path}" if current_path else added_path # Unset click environment variables in the current environment # that might conflict with arguments that we're using if port and "DAGSTER_GRPC_SOCKET" in env: del env["DAGSTER_GRPC_SOCKET"] if socket and "DAGSTER_GRPC_PORT" in env: del env["DAGSTER_GRPC_PORT"] server_process = open_ipc_subprocess(subprocess_args, cwd=cwd, env=env) from dagster._grpc.client import DagsterGrpcClient client = DagsterGrpcClient( port=port, socket=socket, host="localhost", ) try: wait_for_grpc_server( server_process, client, subprocess_args, timeout=startup_timeout, additional_timeout_msg=additional_timeout_msg, ) except: if server_process.poll() is None: server_process.terminate() raise return server_process def _open_server_process_on_dynamic_port( max_retries: int, instance_ref: Optional[InstanceRef], **kwargs, ) -> tuple[Optional["Popen[str]"], Optional[int]]: server_process = None retries = 0 port = None while server_process is None and retries < max_retries: port = find_free_port() try: server_process = open_server_process( instance_ref=instance_ref, port=port, socket=None, **kwargs ) except CouldNotBindGrpcServerToAddress: pass retries += 1 return server_process, port
CouldNotStartServerProcess
python
Lightning-AI__lightning
src/lightning/pytorch/accelerators/accelerator.py
{ "start": 793, "end": 1517 }
class ____(_Accelerator, ABC): """The Accelerator base class for Lightning PyTorch. .. warning:: Writing your own accelerator is an :ref:`experimental <versioning:Experimental API>` feature. """ def setup(self, trainer: "pl.Trainer") -> None: """Called by the Trainer to set up the accelerator before the model starts running on the device. Args: trainer: the trainer instance """ def get_device_stats(self, device: _DEVICE) -> dict[str, Any]: """Get stats for a given device. Args: device: device for which to get stats Returns: Dictionary of device stats """ raise NotImplementedError
Accelerator
python
huggingface__transformers
src/transformers/models/table_transformer/modeling_table_transformer.py
{ "start": 31335, "end": 32571 }
class ____(PreTrainedModel): config: TableTransformerConfig base_model_prefix = "model" main_input_name = "pixel_values" input_modalities = ("image",) _no_split_modules = [ r"TableTransformerConvEncoder", r"TableTransformerEncoderLayer", r"TableTransformerDecoderLayer", ] @torch.no_grad() def _init_weights(self, module): std = self.config.init_std if isinstance(module, TableTransformerLearnedPositionEmbedding): init.uniform_(module.row_embeddings.weight) init.uniform_(module.column_embeddings.weight) if isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)): init.normal_(module.weight, mean=0.0, std=std) if module.bias is not None: init.zeros_(module.bias) elif isinstance(module, nn.Embedding): init.normal_(module.weight, mean=0.0, std=std) # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False): init.zeros_(module.weight[module.padding_idx])
TableTransformerPreTrainedModel
python
chroma-core__chroma
chromadb/auth/basic_authn/__init__.py
{ "start": 1441, "end": 5092 }
class ____(ServerAuthenticationProvider): """ Server auth provider for basic auth. The credentials are read from `chroma_server_authn_credentials_file` and each line must be in the format <username>:<bcrypt passwd>. Expects tokens to be passed as a base64-encoded string in the Authorization header prepended with "Basic". """ def __init__(self, system: System) -> None: super().__init__(system) self._settings = system.settings self._creds: Dict[str, SecretStr] = {} creds = self.read_creds_or_creds_file() for line in creds: if not line.strip(): continue _raw_creds = [v for v in line.strip().split(":")] if ( _raw_creds and _raw_creds[0] and len(_raw_creds) != 2 or not all(_raw_creds) ): raise ValueError( f"Invalid htpasswd credentials found: {_raw_creds}. " "Lines must be exactly <username>:<bcrypt passwd>." ) username = _raw_creds[0] password = _raw_creds[1] if username in self._creds: raise ValueError( "Duplicate username found in " "[chroma_server_authn_credentials]. " "Usernames must be unique." ) self._creds[username] = SecretStr(password) @trace_method( "BasicAuthenticationServerProvider.authenticate", OpenTelemetryGranularity.ALL ) @override def authenticate_or_raise(self, headers: Dict[str, str]) -> UserIdentity: try: if AUTHORIZATION_HEADER.lower() not in headers.keys(): raise AuthError(AUTHORIZATION_HEADER + " header not found") _auth_header = headers[AUTHORIZATION_HEADER.lower()] _auth_header = re.sub(r"^Basic ", "", _auth_header) _auth_header = _auth_header.strip() base64_decoded = base64.b64decode(_auth_header).decode("utf-8") if ":" not in base64_decoded: raise AuthError("Invalid Authorization header format") username, password = base64_decoded.split(":", 1) username = str(username) # convert to string to prevent header injection password = str(password) # convert to string to prevent header injection if username not in self._creds: raise AuthError("Invalid username or password") _pwd_check = bcrypt.checkpw( password.encode("utf-8"), self._creds[username].get_secret_value().encode("utf-8"), ) if not _pwd_check: raise AuthError("Invalid username or password") return UserIdentity(user_id=username) except AuthError as e: logger.error( f"BasicAuthenticationServerProvider.authenticate failed: {repr(e)}" ) except Exception as e: tb = traceback.extract_tb(e.__traceback__) # Get the last call stack last_call_stack = tb[-1] line_number = last_call_stack.lineno filename = last_call_stack.filename logger.error( "BasicAuthenticationServerProvider.authenticate failed: " f"Failed to authenticate {type(e).__name__} at {filename}:{line_number}" ) time.sleep( random.uniform(0.001, 0.005) ) # add some jitter to avoid timing attacks raise ChromaAuthError()
BasicAuthenticationServerProvider
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance4.py
{ "start": 474, "end": 2079 }
class ____(Protocol): def __call__(self, arg: str) -> None: raise NotImplementedError def check_callable1(val: Union[Callable[[int, str], None], Callable[[int], None]]): if isinstance(val, ClassA): reveal_type(val, expected_text="ClassA") else: # This doesn't get narrowed because `ClassA` is not a runtime checkable protocol. reveal_type(val, expected_text="((int, str) -> None) | ((int) -> None)") def check_callable2(val: Union[Callable[[int, str], None], Callable[[int], None]]): if isinstance(val, ClassB): reveal_type(val, expected_text="((int, str) -> None) | ((int) -> None)") else: reveal_type(val, expected_text="Never") def check_callable3(val: Union[Callable[[int, str], None], Callable[[int], None]]): if isinstance(val, ClassC): reveal_type(val, expected_text="((int, str) -> None) | ((int) -> None)") else: reveal_type(val, expected_text="Never") def check_callable4(val: Union[type, Callable[[int], None]]): if isinstance(val, type): reveal_type(val, expected_text="type") else: reveal_type(val, expected_text="(int) -> None") def check_callable5(fn: Callable[P, None]) -> None: if isinstance(fn, ClassA): reveal_type(fn, expected_text="ClassA") else: reveal_type(fn, expected_text="(**P@check_callable5) -> None") def check_callable6(o: object | Callable[[int], int]): if isinstance(o, Callable): reveal_type(o, expected_text="((...) -> Unknown) | ((int) -> int)") else: reveal_type(o, expected_text="object")
ClassC
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/endpoints-frameworks-v2/echo/main.py
{ "start": 1319, "end": 3689 }
class ____(remote.Service): # [START endpoints_echo_api_method] @endpoints.method( # This method takes a ResourceContainer defined above. ECHO_RESOURCE, # This method returns an Echo message. EchoResponse, path="echo", http_method="POST", name="echo", ) def echo(self, request): output_message = " ".join([request.message] * request.n) return EchoResponse(message=output_message) # [END endpoints_echo_api_method] @endpoints.method( # This method takes a ResourceContainer defined above. ECHO_RESOURCE, # This method returns an Echo message. EchoResponse, path="echo/{n}", http_method="POST", name="echo_path_parameter", ) def echo_path_parameter(self, request): output_message = " ".join([request.message] * request.n) return EchoResponse(message=output_message) @endpoints.method( # This method takes a ResourceContainer defined above. message_types.VoidMessage, # This method returns an Echo message. EchoResponse, path="echo/getApiKey", http_method="GET", name="echo_api_key", api_key_required=True, ) def echo_api_key(self, request): key, key_type = request.get_unrecognized_field_info("key") return EchoResponse(message=key) @endpoints.method( # This method takes an empty request body. message_types.VoidMessage, # This method returns an Echo message. EchoResponse, path="echo/email", http_method="GET", # Require auth tokens to have the following scopes to access this API. scopes=[endpoints.EMAIL_SCOPE], # OAuth2 audiences allowed in incoming tokens. audiences=["your-oauth-client-id.com"], allowed_client_ids=["your-oauth-client-id.com"], ) def get_user_email(self, request): user = endpoints.get_current_user() # If there's no user defined, the request was unauthenticated, so we # raise 401 Unauthorized. if not user: raise endpoints.UnauthorizedException return EchoResponse(message=user.email()) # [END endpoints_echo_api_class] # [START endpoints_api_server] api = endpoints.api_server([EchoApi]) # [END endpoints_api_server]
EchoApi
python
getsentry__sentry
src/sentry/search/events/datasets/profile_functions.py
{ "start": 3943, "end": 30793 }
class ____(DatasetConfig): non_nullable_keys = { "project.id", "project_id", "transaction", "timestamp", "_fingerprint", "function", "package", "is_application", "platform.name", } def __init__(self, builder: BaseQueryBuilder): self.builder = builder @property def search_filter_converter( self, ) -> Mapping[str, Callable[[SearchFilter], WhereType | None]]: return { "fingerprint": self._fingerprint_filter_converter, "message": self._message_filter_converter, PROJECT_ALIAS: self._project_slug_filter_converter, PROJECT_NAME_ALIAS: self._project_slug_filter_converter, } def _fingerprint_filter_converter(self, search_filter: SearchFilter) -> WhereType | None: try: return Condition( self.builder.resolve_column("fingerprint"), Op.EQ if search_filter.operator in EQUALITY_OPERATORS else Op.NEQ, int(search_filter.value.value), ) except ValueError: raise InvalidSearchQuery( "Invalid value for fingerprint condition. Accepted values are numeric." ) def _message_filter_converter(self, search_filter: SearchFilter) -> WhereType | None: return filter_aliases.message_filter_converter(self.builder, search_filter) def _project_slug_filter_converter(self, search_filter: SearchFilter) -> WhereType | None: return filter_aliases.project_slug_converter(self.builder, search_filter) @property def field_alias_converter(self) -> Mapping[str, Callable[[str], SelectType]]: return { "fingerprint": self._resolve_fingerprint_alias, PROJECT_ALIAS: self._resolve_project_slug_alias, PROJECT_NAME_ALIAS: self._resolve_project_slug_alias, } def _resolve_fingerprint_alias(self, alias: str) -> SelectType: # HACK: temporarily truncate the fingerprint to 32 bits # as snuba cannot handle 64 bit unsigned fingerprints # once we migrate to a 32 bit unsigned fingerprint # we can remove this field alias and directly use the column # # When removing this, make sure to update the test helper to # generate 32 bit function fingerprints as well. return Function("toUInt32", [self.builder.column("_fingerprint")], alias) def _resolve_project_slug_alias(self, alias: str) -> SelectType: return field_aliases.resolve_project_slug_alias(self.builder, alias) @property def function_converter(self) -> Mapping[str, SnQLFunction]: return { function.name: function for function in [ SnQLFunction( "count", snql_aggregate=lambda _, alias: Function( "countMerge", [SnQLColumn("count")], alias, ), default_result_type="integer", ), SnQLFunction( "cpm", # calls per minute snql_aggregate=lambda args, alias: self._resolve_cpm(args, alias), default_result_type="number", ), SnQLFunction( "cpm_before", required_args=[TimestampArg("timestamp")], snql_aggregate=lambda args, alias: self._resolve_cpm_cond(args, alias, "less"), default_result_type="number", ), SnQLFunction( "cpm_after", required_args=[TimestampArg("timestamp")], snql_aggregate=lambda args, alias: self._resolve_cpm_cond( args, alias, "greater" ), default_result_type="number", ), SnQLFunction( "cpm_delta", required_args=[TimestampArg("timestamp")], snql_aggregate=self._resolve_cpm_delta, default_result_type="number", ), SnQLFunction( "count_unique", required_args=[ProfileFunctionColumnArg("column")], snql_aggregate=lambda args, alias: Function("uniq", [args["column"]], alias), default_result_type="integer", ), SnQLFunction( "worst", snql_aggregate=lambda _, alias: Function( "replaceAll", [ Function( "toString", [Function("argMaxMerge", [SnQLColumn("worst")])], ), "-", "", ], alias, ), default_result_type="string", # TODO: support array type ), SnQLFunction( "examples", snql_aggregate=lambda _, alias: Function( # The worst may collide with one of the examples, so make sure to filter it out. "arrayDistinct", [ Function( "arrayFilter", [ # Filter out the profile ids for processed profiles Lambda( ["x"], Function( "notEquals", [Identifier("x"), uuid.UUID(int=0).hex], ), ), Function( "arrayMap", [ # TODO: should this transform be moved to snuba? Lambda( ["x"], Function( "replaceAll", [ Function("toString", [Identifier("x")]), "-", "", ], ), ), Function( "arrayPushFront", [ Function( "groupUniqArrayMerge(5)", [SnQLColumn("examples")], ), Function("argMaxMerge", [SnQLColumn("worst")]), ], ), ], ), ], ), ], alias, ), default_result_type="string", # TODO: support array type ), SnQLFunction( "all_examples", snql_aggregate=lambda _, alias: Function( # The worst may collide with one of the examples, so make sure to filter it out. "arrayDistinct", [ Function( "arrayFilter", [ # Filter out the profile ids for processed profiles Lambda( ["x"], Function( "notEquals", [ Function("tupleElement", [Identifier("x"), 1]), uuid.UUID(int=0).hex, ], ), ), Function( "arrayMap", [ # TODO: should this transform be moved to snuba? Lambda( ["x"], Function( "tuple", [ Function( "replaceAll", [ Function( "toString", [ Function( "tupleElement", [Identifier("x"), 1], ) ], ), "-", "", ], ), Function( "tupleElement", [Identifier("x"), 2] ), Function( "tupleElement", [Identifier("x"), 3] ), Function( "tupleElement", [Identifier("x"), 4] ), ], ), ), Function( "arrayPushFront", [ Function( "groupUniqArrayMerge(5)", [SnQLColumn("examples_v2")], ), Function( "argMaxMerge", [SnQLColumn("worst_v2")] ), ], ), ], ), ], ), ], alias, ), default_result_type="string", # TODO: support array type ), SnQLFunction( "unique_examples", snql_aggregate=lambda args, alias: Function( "arrayFilter", [ # Filter out the profile ids for processed profiles Lambda( ["x"], Function( "notEquals", [Identifier("x"), uuid.UUID(int=0).hex], ), ), Function( "arrayMap", [ # TODO: should this transform be moved to snuba? Lambda( ["x"], Function( "replaceAll", [Function("toString", [Identifier("x")]), "-", ""], ), ), Function("groupUniqArrayMerge(5)", [SnQLColumn("examples")]), ], ), ], alias, ), default_result_type="string", # TODO: support array type ), SnQLFunction( "percentile", required_args=[ ProfileFunctionNumericColumn("column"), NumberRange("percentile", 0, 1), ], snql_aggregate=self._resolve_percentile, result_type_fn=self.reflective_result_type(), default_result_type="duration", redundant_grouping=True, ), SnQLFunction( "p50", optional_args=[ with_default("function.duration", ProfileFunctionNumericColumn("column")), ], snql_aggregate=lambda args, alias: self._resolve_percentile(args, alias, 0.5), result_type_fn=self.reflective_result_type(), default_result_type="duration", redundant_grouping=True, ), SnQLFunction( "p75", optional_args=[ with_default("function.duration", ProfileFunctionNumericColumn("column")), ], snql_aggregate=lambda args, alias: self._resolve_percentile(args, alias, 0.75), result_type_fn=self.reflective_result_type(), default_result_type="duration", redundant_grouping=True, ), SnQLFunction( "p95", optional_args=[ with_default("function.duration", ProfileFunctionNumericColumn("column")), ], snql_aggregate=lambda args, alias: self._resolve_percentile(args, alias, 0.95), result_type_fn=self.reflective_result_type(), default_result_type="duration", redundant_grouping=True, ), SnQLFunction( "p99", optional_args=[ with_default("function.duration", ProfileFunctionNumericColumn("column")), ], snql_aggregate=lambda args, alias: self._resolve_percentile(args, alias, 0.99), result_type_fn=self.reflective_result_type(), default_result_type="duration", redundant_grouping=True, ), SnQLFunction( "avg", optional_args=[ with_default("function.duration", ProfileFunctionNumericColumn("column")), ], snql_aggregate=lambda args, alias: Function( "avgMerge", [SnQLColumn("avg")], alias, ), result_type_fn=self.reflective_result_type(), default_result_type="duration", redundant_grouping=True, ), SnQLFunction( "sum", optional_args=[ with_default("function.duration", ProfileFunctionNumericColumn("column")), ], snql_aggregate=lambda args, alias: Function( "sumMerge", [SnQLColumn("sum")], alias, ), result_type_fn=self.reflective_result_type(), default_result_type="duration", redundant_grouping=True, ), SnQLFunction( "percentile_before", required_args=[ ProfileFunctionNumericColumn("column"), NumberRange("percentile", 0, 1), TimestampArg("timestamp"), ], snql_aggregate=lambda args, alias: self._resolve_percentile_cond( args, alias, "less" ), result_type_fn=self.reflective_result_type(), default_result_type="duration", redundant_grouping=True, ), SnQLFunction( "percentile_after", required_args=[ ProfileFunctionNumericColumn("column"), NumberRange("percentile", 0, 1), TimestampArg("timestamp"), ], snql_aggregate=lambda args, alias: self._resolve_percentile_cond( args, alias, "greater" ), result_type_fn=self.reflective_result_type(), default_result_type="duration", redundant_grouping=True, ), SnQLFunction( "percentile_delta", required_args=[ ProfileFunctionNumericColumn("column"), NumberRange("percentile", 0, 1), TimestampArg("timestamp"), ], snql_aggregate=self._resolve_percentile_delta, result_type_fn=self.reflective_result_type(), default_result_type="duration", redundant_grouping=True, ), SnQLFunction( "regression_score", required_args=[ ProfileFunctionNumericColumn("column"), NumberRange("percentile", 0, 1), TimestampArg("timestamp"), ], snql_aggregate=lambda args, alias: Function( "minus", [ Function( "multiply", [ self._resolve_cpm_cond(args, None, "greater"), self._resolve_percentile_cond(args, None, "greater"), ], ), Function( "multiply", [ self._resolve_cpm_cond(args, None, "less"), self._resolve_percentile_cond(args, None, "less"), ], ), ], alias, ), default_result_type="number", ), ] } @property def orderby_converter(self) -> Mapping[str, OrderBy]: return { PROJECT_ALIAS: self._project_slug_orderby_converter, PROJECT_NAME_ALIAS: self._project_slug_orderby_converter, } def _project_slug_orderby_converter(self, direction: Direction) -> OrderBy: projects = self.builder.params.projects # Try to reduce the size of the transform by using any existing conditions on projects # Do not optimize projects list if conditions contain OR operator if not self.builder.has_or_condition and len(self.builder.projects_to_filter) > 0: projects = [ project for project in projects if project.id in self.builder.projects_to_filter ] return OrderBy( Function( "transform", [ self.builder.column("project.id"), [project.id for project in projects], [project.slug for project in projects], "", ], ), direction, ) def resolve_column(self, column: str) -> str: try: return COLUMN_MAP[column].column except KeyError: raise InvalidSearchQuery(f"Unknown field: {column}") def resolve_column_type(self, column: str, units: bool = False) -> str | None: try: col = COLUMN_MAP[column] if col.unit: # if the column has an associated unit, # prioritize that over the kind return col.unit.value return col.kind.value except KeyError: return None def _resolve_percentile( self, args: Mapping[str, str | Column | SelectType | int | float], alias: str, fixed_percentile: float | None = None, ) -> SelectType: return Function( "arrayElement", [ Function( f'quantilesMerge({fixed_percentile if fixed_percentile is not None else args["percentile"]})', [args["column"]], ), 1, ], alias, ) def _resolve_cpm( self, args: Mapping[str, str | Column | SelectType | int | float], alias: str | None, ) -> SelectType: assert ( self.builder.params.end is not None and self.builder.params.start is not None ), f"params.end: {self.builder.params.end} - params.start: {self.builder.params.start}" interval = (self.builder.params.end - self.builder.params.start).total_seconds() return Function( "divide", [ Function("countMerge", [SnQLColumn("count")]), Function("divide", [interval, 60]), ], alias, ) def _resolve_cpm_cond( self, args: Mapping[str, str | Column | SelectType | int | float], alias: str | None, cond: str, ) -> SelectType: timestamp = args["timestamp"] if cond == "greater": assert isinstance(self.builder.params.end, datetime) and isinstance( timestamp, datetime ), f"params.end: {self.builder.params.end} - timestamp: {timestamp}" interval = (self.builder.params.end - timestamp).total_seconds() elif cond == "less": assert isinstance(self.builder.params.start, datetime) and isinstance( timestamp, datetime ), f"params.start: {self.builder.params.start} - timestamp: {timestamp}" interval = (timestamp - self.builder.params.start).total_seconds() else: raise InvalidSearchQuery(f"Unsupported condition for cpm: {cond}") return Function( "divide", [ Function( "countMergeIf", [ SnQLColumn("count"), Function( cond, [ self.builder.column("timestamp"), args["timestamp"], ], ), ], ), Function("divide", [interval, 60]), ], alias, ) def _resolve_cpm_delta( self, args: Mapping[str, str | Column | SelectType | int | float], alias: str, ) -> SelectType: return Function( "minus", [ self._resolve_cpm_cond(args, None, "greater"), self._resolve_cpm_cond(args, None, "less"), ], alias, ) def _resolve_percentile_cond( self, args: Mapping[str, str | Column | SelectType | int | float], alias: str | None, cond: str, ) -> SelectType: return Function( "arrayElement", [ Function( f'quantilesMergeIf({args["percentile"]})', [ args["column"], Function( cond, [ self.builder.column("timestamp"), args["timestamp"], ], ), ], ), 1, ], alias, ) def _resolve_percentile_delta( self, args: Mapping[str, str | Column | SelectType | int | float], alias: str, ) -> SelectType: return Function( "minus", [ self._resolve_percentile_cond(args, None, "greater"), self._resolve_percentile_cond(args, None, "less"), ], alias, )
ProfileFunctionsDatasetConfig
python
google__pytype
pytype/tests/test_generators1.py
{ "start": 66, "end": 3696 }
class ____(test_base.BaseTest): """Tests for iterators, generators, coroutines, and yield.""" def test_next(self): ty = self.Infer(""" def f(): return next(i for i in [1,2,3]) """) self.assertTypesMatchPytd( ty, """ def f() -> int: ... """, ) def test_list(self): ty = self.Infer(""" y = list(x for x in [1, 2, 3]) """) self.assertTypesMatchPytd( ty, """ from typing import List y = ... # type: List[int] """, ) def test_reuse(self): ty = self.Infer(""" y = list(x for x in [1, 2, 3]) z = list(x for x in [1, 2, 3]) """) self.assertTypesMatchPytd( ty, """ from typing import List y = ... # type: List[int] z = ... # type: List[int] """, ) def test_next_with_default(self): ty = self.Infer(""" def f(): return next((i for i in [1,2,3]), None) """) self.assertTypesMatchPytd( ty, """ from typing import Union def f() -> Union[int, NoneType]: ... """, ) def test_iter_match(self): ty = self.Infer(""" class Foo: def bar(self): for x in __any_object__: return x def __iter__(self): return (i for i in range(5)) """) self.assertTypesMatchPytd( ty, """ from typing import Any, Generator class Foo: def bar(self) -> Any: ... def __iter__(self) -> Generator[int, Any, None]: ... """, ) def test_coroutine_type(self): ty = self.Infer(""" def foo(self): yield 3 """) self.assertTypesMatchPytd( ty, """ from typing import Any, Generator def foo(self) -> Generator[int, Any, None]: ... """, ) def test_iteration_of_getitem(self): ty = self.Infer(""" class Foo: def __getitem__(self, key): return "hello" def foo(self): for x in Foo(): return x """) self.assertTypesMatchPytd( ty, """ from typing import Union class Foo: def __getitem__(self, key) -> str: ... def foo(self) -> Union[None, str]: ... """, ) def test_unpacking_of_getitem(self): ty = self.Infer(""" class Foo: def __getitem__(self, pos): if pos < 3: return pos else: raise StopIteration x, y, z = Foo() """) self.assertTypesMatchPytd( ty, """ from typing import Any, TypeVar _T0 = TypeVar("_T0") class Foo: def __getitem__(self, pos: _T0) -> _T0: ... x = ... # type: int y = ... # type: int z = ... # type: int """, ) def test_none_check(self): ty = self.Infer(""" def f(): x = None if __random__ else 42 if x: yield x """) self.assertTypesMatchPytd( ty, """ from typing import Any, Generator def f() -> Generator[int, Any, None]: ... """, ) def test_yield_type(self): ty = self.Infer(""" from typing import Generator def f(x): if x == 1: yield 1 else: yield "1" x = f(2) y = f(1) """) self.assertTypesMatchPytd( ty, """ from typing import Any, Generator, Union def f(x) -> Generator[Union[int, str], Any, None]: ... x = ... # type: Generator[str, Any, None] y = ... # type: Generator[int, Any, None] """, ) if __name__ == "__main__": test_base.main()
GeneratorTest
python
getsentry__sentry
tests/sentry/monitors/endpoints/test_organization_monitor_stats.py
{ "start": 91, "end": 226 }
class ____(BaseMonitorStatsTest): endpoint = "sentry-api-0-organization-monitor-stats" __test__ = True
OrganizationMonitorStatsTest
python
scrapy__scrapy
tests/test_crawler.py
{ "start": 16258, "end": 19178 }
class ____: def test_no_root_handler_installed(self): handler = get_scrapy_root_handler() if handler is not None: logging.root.removeHandler(handler) class MySpider(scrapy.Spider): name = "spider" get_crawler(MySpider) assert get_scrapy_root_handler() is None @deferred_f_from_coro_f async def test_spider_custom_settings_log_level(self, tmp_path): log_file = Path(tmp_path, "log.txt") log_file.write_text("previous message\n", encoding="utf-8") info_count = None class MySpider(scrapy.Spider): name = "spider" custom_settings = { "LOG_LEVEL": "INFO", "LOG_FILE": str(log_file), } async def start(self): info_count_start = crawler.stats.get_value("log_count/INFO") logging.debug("debug message") # noqa: LOG015 logging.info("info message") # noqa: LOG015 logging.warning("warning message") # noqa: LOG015 logging.error("error message") # noqa: LOG015 nonlocal info_count info_count = ( crawler.stats.get_value("log_count/INFO") - info_count_start ) return yield try: configure_logging() assert get_scrapy_root_handler().level == logging.DEBUG crawler = get_crawler(MySpider) assert get_scrapy_root_handler().level == logging.INFO await maybe_deferred_to_future(crawler.crawl()) finally: _uninstall_scrapy_root_handler() logged = log_file.read_text(encoding="utf-8") assert "previous message" in logged assert "debug message" not in logged assert "info message" in logged assert "warning message" in logged assert "error message" in logged assert crawler.stats.get_value("log_count/ERROR") == 1 assert crawler.stats.get_value("log_count/WARNING") == 1 assert info_count == 1 assert crawler.stats.get_value("log_count/DEBUG", 0) == 0 def test_spider_custom_settings_log_append(self, tmp_path): log_file = Path(tmp_path, "log.txt") log_file.write_text("previous message\n", encoding="utf-8") class MySpider(scrapy.Spider): name = "spider" custom_settings = { "LOG_FILE": str(log_file), "LOG_FILE_APPEND": False, } try: configure_logging() get_crawler(MySpider) logging.debug("debug message") # noqa: LOG015 finally: _uninstall_scrapy_root_handler() logged = log_file.read_text(encoding="utf-8") assert "previous message" not in logged assert "debug message" in logged
TestCrawlerLogging
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_compute.py
{ "start": 64074, "end": 67194 }
class ____: @mock.patch(COMPUTE_ENGINE_HOOK_PATH) def test_delete_igm_should_execute_successfully(self, mock_hook): op = ComputeEngineDeleteInstanceGroupManagerOperator( project_id=GCP_PROJECT_ID, resource_id=GCE_INSTANCE_GROUP_MANAGER_NAME, zone=GCE_ZONE, task_id=TASK_ID, retry=RETRY, timeout=TIMEOUT, metadata=METADATA, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) op.execute(context=mock.MagicMock()) mock_hook.assert_called_once_with( api_version=API_VERSION, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.delete_instance_group_manager.assert_called_once_with( zone=GCE_ZONE, request_id=None, resource_id=GCE_INSTANCE_GROUP_MANAGER_NAME, project_id=GCP_PROJECT_ID, ) def test_delete_igm_should_throw_ex_when_missing_project_id(self): with pytest.raises(AirflowException, match=r"The required parameter 'project_id' is missing"): ComputeEngineDeleteInstanceGroupManagerOperator( project_id="", resource_id=GCE_INSTANCE_GROUP_MANAGER_NAME, zone=GCE_ZONE, task_id=TASK_ID, retry=RETRY, timeout=TIMEOUT, metadata=METADATA, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) @mock.patch(COMPUTE_ENGINE_HOOK_PATH) def test_delete_igm_should_not_throw_ex_when_project_id_none(self, mock_hook): op = ComputeEngineDeleteInstanceGroupManagerOperator( resource_id=GCE_INSTANCE_GROUP_MANAGER_NAME, zone=GCE_ZONE, task_id=TASK_ID, retry=RETRY, timeout=TIMEOUT, metadata=METADATA, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) op.execute(context=mock.MagicMock()) mock_hook.assert_called_once_with( api_version=API_VERSION, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, ) mock_hook.return_value.delete_instance_group_manager.assert_called_once_with( zone=GCE_ZONE, request_id=None, resource_id=GCE_INSTANCE_GROUP_MANAGER_NAME, project_id=None, ) def test_delete_igm_should_throw_ex_when_missing_resource_id(self): with pytest.raises(AirflowException, match=r"The required parameter 'resource_id' is missing"): ComputeEngineDeleteInstanceGroupManagerOperator( resource_id="", zone=GCE_ZONE, task_id=TASK_ID, retry=RETRY, timeout=TIMEOUT, metadata=METADATA, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, )
TestGceInstanceGroupManagerDelete
python
walkccc__LeetCode
solutions/3537. Fill a Special Grid/3537.py
{ "start": 0, "end": 545 }
class ____: def specialGrid(self, n: int) -> list[list[int]]: sz = 1 << n grid = [[0] * sz for _ in range(sz)] count = 0 def fill(x1: int, x2: int, y1: int, y2: int) -> None: nonlocal count if x2 - x1 == 1: grid[x1][y1] = count count += 1 return midRow = (x1 + x2) // 2 midCol = (y1 + y2) // 2 fill(x1, midRow, midCol, y2) fill(midRow, x2, midCol, y2) fill(midRow, x2, y1, midCol) fill(x1, midRow, y1, midCol) fill(0, sz, 0, sz) return grid
Solution
python
django__django
tests/serializers/models/base.py
{ "start": 1521, "end": 1945 }
class ____(models.Model): author = models.ForeignKey(Author, models.CASCADE) headline = models.CharField(max_length=50) pub_date = models.DateTimeField() categories = models.ManyToManyField(Category) meta_data = models.ManyToManyField(CategoryMetaData) topics = models.ManyToManyField(Topic) class Meta: ordering = ("pub_date",) def __str__(self): return self.headline
Article
python
pallets__werkzeug
src/werkzeug/exceptions.py
{ "start": 16841, "end": 17127 }
class ____(HTTPException): """*417* `Expectation Failed` The server cannot meet the requirements of the Expect request-header. .. versionadded:: 0.7 """ code = 417 description = "The server could not meet the requirements of the Expect header"
ExpectationFailed
python
python-openxml__python-docx
src/docx/image/jpeg.py
{ "start": 3912, "end": 4950 }
class ____: """Service class that knows how to parse a JFIF stream and iterate over its markers.""" def __init__(self, stream_reader): super(_MarkerParser, self).__init__() self._stream = stream_reader @classmethod def from_stream(cls, stream): """Return a |_MarkerParser| instance to parse JFIF markers from `stream`.""" stream_reader = StreamReader(stream, BIG_ENDIAN) return cls(stream_reader) def iter_markers(self): """Generate a (marker_code, segment_offset) 2-tuple for each marker in the JPEG `stream`, in the order they occur in the stream.""" marker_finder = _MarkerFinder.from_stream(self._stream) start = 0 marker_code = None while marker_code != JPEG_MARKER_CODE.EOI: marker_code, segment_offset = marker_finder.next(start) marker = _MarkerFactory(marker_code, self._stream, segment_offset) yield marker start = segment_offset + marker.segment_length
_MarkerParser
python
pytorch__pytorch
torchgen/_autoheuristic/train_decision.py
{ "start": 22664, "end": 23129 }
class ____: # Number of correct predictions num_correct: int # Number of wrong predictions num_wrong: int # Number of predictions where model is unsure num_unsure: int # Total number of predictions total: int def to_map(self): return { "correct": self.num_correct, "wrong": self.num_wrong, "unsure": self.num_unsure, "total": self.total, } @dataclass
AccuracyMetrics
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/from_tensors_test.py
{ "start": 14060, "end": 16549 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate(test_base.default_test_combinations()) def testInvalidIndex(self): dataset = dataset_ops.Dataset.from_tensors([1, 2, 3]) with self.assertRaises(errors.OutOfRangeError): self.evaluate(random_access.at(dataset, -1)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(random_access.at(dataset, 1)) @combinations.generate( combinations.times(test_base.default_test_combinations())) def testBasic(self): dataset = dataset_ops.Dataset.from_tensors(range(4)) self.assertAllEqual(self.evaluate(random_access.at(dataset, 0)), range(4)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(random_access.at(dataset, 1)) @combinations.generate( combinations.times(test_base.default_test_combinations())) def testWithOptions(self): dataset = dataset_ops.Dataset.from_tensors(range(4)) options = options_lib.Options() options.experimental_optimization.map_and_batch_fusion = True dataset = dataset.with_options(options) self.assertAllEqual(self.evaluate(random_access.at(dataset, 0)), range(4)) with self.assertRaises(errors.OutOfRangeError): self.evaluate(random_access.at(dataset, 1)) @combinations.generate( combinations.times(test_base.default_test_combinations())) def testEmptyDataset(self): dataset = dataset_ops.Dataset.from_tensors([]) self.assertAllEqual(self.evaluate(random_access.at(dataset, 0)), []) with self.assertRaises(errors.OutOfRangeError): self.evaluate(random_access.at(dataset, 1)) @combinations.generate( combinations.times(test_base.default_test_combinations())) def testNumpyArray(self): components = (np.array(1), np.array([1, 2, 3]), np.array(37.0)) dataset = dataset_ops.Dataset.from_tensors(components) result = self.evaluate(random_access.at(dataset, 0)) for i in range(3): self.assertAllEqual(result[i], components[i]) with self.assertRaises(errors.OutOfRangeError): self.evaluate(random_access.at(dataset, 1)) @combinations.generate(test_base.default_test_combinations()) def testFromTensorsNestedDataset(self): dataset = dataset_ops.Dataset.from_tensors(dataset_ops.Dataset.range(10)) result = random_access.at(dataset, 0) for i in range(10): self.assertEqual(self.evaluate(random_access.at(result, i)), i)
FromTensorsRandomAccessTest
python
ray-project__ray
rllib/policy/tests/test_policy_map.py
{ "start": 309, "end": 4829 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls) -> None: ray.init() @classmethod def tearDownClass(cls) -> None: ray.shutdown() def test_policy_map(self): # This is testing policy map which is something that will be deprecated in # favor of MultiAgentRLModules in the future. So we'll disable the RLModule API # for this test for now. config = ( PPOConfig() .api_stack( enable_env_runner_and_connector_v2=False, enable_rl_module_and_learner=False, ) .framework("tf2") ) obs_space = gym.spaces.Box(-1.0, 1.0, (4,), dtype=np.float32) dummy_obs = obs_space.sample() act_space = gym.spaces.Discrete(10000) num_policies = 6 capacity = 2 cls = get_tf_eager_cls_if_necessary(PPOTF2Policy, config) # Create empty PolicyMap. for use_swapping in [False, True]: policy_map = PolicyMap( capacity=capacity, policy_states_are_swappable=use_swapping ) # Create and add some TF2 policies. for i in range(num_policies): config.training(lr=(i + 1) * 0.00001) policy = cls( observation_space=obs_space, action_space=act_space, config=config.to_dict(), ) policy_map[f"pol{i}"] = policy expected = [f"pol{j}" for j in range(max(i - 1, 0), i + 1)] self.assertEqual(list(policy_map._deque), expected) self.assertEqual(list(policy_map.cache.keys()), expected) self.assertEqual( policy_map._valid_keys, {f"pol{j}" for j in range(i + 1)} ) actions = { pid: p.compute_single_action(dummy_obs, explore=False)[0] for pid, p in policy_map.items() } # Time the random access performance of our map. start = time.time() for i in range(50): pid = f"pol{i % num_policies}" # Actually compute one action to trigger tracing operations of the # graph. These may be performed lazily by the DL framework. print( f"{i}) Testing `compute_single_action()` resulting in same outputs " f"for stashed/recovered policy ({pid}) ..." ) pol = policy_map[pid] # After accessing `pid`, assume it's the most recently accessed item # now. self.assertTrue(policy_map._deque[-1] == pid) self.assertTrue(len(policy_map._deque) == 2) self.assertTrue(len(policy_map.cache) == 2) self.assertTrue(pid in policy_map.cache) check( pol.compute_single_action(dummy_obs, explore=False)[0], actions[pid] ) time_total = time.time() - start print(f"Random access (swapping={use_swapping} took {time_total}sec.") # Delete some policy entirely that is in the deque policy_id = next(iter(policy_map._deque)) del policy_map[policy_id] self.assertEqual(len(policy_map._deque), capacity - 1) self.assertTrue(policy_id not in policy_map._deque) self.assertEqual(len(policy_map.cache), capacity - 1) self.assertTrue(policy_id not in policy_map._deque) self.assertEqual(len(policy_map._valid_keys), num_policies - 1) self.assertTrue(policy_id not in policy_map._deque) # Add another policy and see if data structures behave as expected config.training(lr=(i + 1) * 0.00001) policy = cls( observation_space=obs_space, action_space=act_space, config=config.to_dict(), ) policy_id = f"pol{num_policies + 1}" policy_map[policy_id] = policy self.assertEqual(len(policy_map._deque), capacity) self.assertTrue(policy_id in policy_map._deque) self.assertEqual(len(policy_map.cache), capacity) self.assertTrue(policy_id in policy_map._deque) self.assertEqual(len(policy_map._valid_keys), num_policies) self.assertTrue(policy_id in policy_map._deque) if __name__ == "__main__": import sys import pytest sys.exit(pytest.main(["-v", __file__]))
TestPolicyMap
python
mlflow__mlflow
mlflow/gateway/config.py
{ "start": 958, "end": 1659 }
class ____(str, Enum): OPENAI = "openai" ANTHROPIC = "anthropic" COHERE = "cohere" AI21LABS = "ai21labs" MLFLOW_MODEL_SERVING = "mlflow-model-serving" MOSAICML = "mosaicml" HUGGINGFACE_TEXT_GENERATION_INFERENCE = "huggingface-text-generation-inference" PALM = "palm" GEMINI = "gemini" BEDROCK = "bedrock" AMAZON_BEDROCK = "amazon-bedrock" # an alias for bedrock # Note: The following providers are only supported on Databricks DATABRICKS_MODEL_SERVING = "databricks-model-serving" DATABRICKS = "databricks" MISTRAL = "mistral" TOGETHERAI = "togetherai" @classmethod def values(cls): return {p.value for p in cls}
Provider
python
pypa__pip
src/pip/_internal/index/sources.py
{ "start": 788, "end": 1365 }
class ____: @property def link(self) -> Link | None: """Returns the underlying link, if there's one.""" raise NotImplementedError() def page_candidates(self) -> FoundCandidates: """Candidates found by parsing an archive listing HTML file.""" raise NotImplementedError() def file_links(self) -> FoundLinks: """Links found by specifying archives directly.""" raise NotImplementedError() def _is_html_file(file_url: str) -> bool: return mimetypes.guess_type(file_url, strict=False)[0] == "text/html"
LinkSource
python
django-haystack__django-haystack
test_haystack/solr_tests/test_solr_query.py
{ "start": 273, "end": 9812 }
class ____(TestCase): fixtures = ["base_data"] def setUp(self): super().setUp() self.sq = connections["solr"].get_query() def test_build_query_all(self): self.assertEqual(self.sq.build_query(), "*:*") def test_build_query_single_word(self): self.sq.add_filter(SQ(content="hello")) self.assertEqual(self.sq.build_query(), "(hello)") def test_build_query_boolean(self): self.sq.add_filter(SQ(content=True)) self.assertEqual(self.sq.build_query(), "(true)") def test_build_query_datetime(self): self.sq.add_filter(SQ(content=datetime.datetime(2009, 5, 8, 11, 28))) self.assertEqual(self.sq.build_query(), "(2009-05-08T11:28:00Z)") def test_build_query_multiple_words_and(self): self.sq.add_filter(SQ(content="hello")) self.sq.add_filter(SQ(content="world")) self.assertEqual(self.sq.build_query(), "((hello) AND (world))") def test_build_query_multiple_words_not(self): self.sq.add_filter(~SQ(content="hello")) self.sq.add_filter(~SQ(content="world")) self.assertEqual(self.sq.build_query(), "(NOT ((hello)) AND NOT ((world)))") def test_build_query_multiple_words_or(self): self.sq.add_filter(~SQ(content="hello")) self.sq.add_filter(SQ(content="hello"), use_or=True) self.assertEqual(self.sq.build_query(), "(NOT ((hello)) OR (hello))") def test_build_query_multiple_words_mixed(self): self.sq.add_filter(SQ(content="why")) self.sq.add_filter(SQ(content="hello"), use_or=True) self.sq.add_filter(~SQ(content="world")) self.assertEqual( self.sq.build_query(), "(((why) OR (hello)) AND NOT ((world)))" ) def test_build_query_phrase(self): self.sq.add_filter(SQ(content="hello world")) self.assertEqual(self.sq.build_query(), "(hello AND world)") self.sq.add_filter(SQ(content__exact="hello world")) self.assertEqual( self.sq.build_query(), '((hello AND world) AND ("hello world"))' ) def test_build_query_boost(self): self.sq.add_filter(SQ(content="hello")) self.sq.add_boost("world", 5) self.assertEqual(self.sq.build_query(), "(hello) world^5") def test_correct_exact(self): self.sq.add_filter(SQ(content=Exact("hello world"))) self.assertEqual(self.sq.build_query(), '("hello world")') def test_build_query_multiple_filter_types(self): self.sq.add_filter(SQ(content="why")) self.sq.add_filter(SQ(pub_date__lte=Exact("2009-02-10 01:59:00"))) self.sq.add_filter(SQ(author__gt="daniel")) self.sq.add_filter(SQ(created__lt=Exact("2009-02-12 12:13:00"))) self.sq.add_filter(SQ(title__gte="B")) self.sq.add_filter(SQ(id__in=[1, 2, 3])) self.sq.add_filter(SQ(rating__range=[3, 5])) self.assertEqual( self.sq.build_query(), '((why) AND pub_date:([* TO "2009-02-10 01:59:00"]) AND author:({"daniel" TO *}) AND created:({* TO "2009-02-12 12:13:00"}) AND title:(["B" TO *]) AND id:("1" OR "2" OR "3") AND rating:(["3" TO "5"]))', ) def test_build_complex_altparser_query(self): self.sq.add_filter(SQ(content=AltParser("dismax", "Don't panic", qf="text"))) self.sq.add_filter(SQ(pub_date__lte=Exact("2009-02-10 01:59:00"))) self.sq.add_filter(SQ(author__gt="daniel")) self.sq.add_filter(SQ(created__lt=Exact("2009-02-12 12:13:00"))) self.sq.add_filter(SQ(title__gte="B")) self.sq.add_filter(SQ(id__in=[1, 2, 3])) self.sq.add_filter(SQ(rating__range=[3, 5])) query = self.sq.build_query() self.assertTrue('(_query_:"{!dismax qf=text}Don\'t panic")' in query) self.assertTrue('pub_date:([* TO "2009-02-10 01:59:00"])' in query) self.assertTrue('author:({"daniel" TO *})' in query) self.assertTrue('created:({* TO "2009-02-12 12:13:00"})' in query) self.assertTrue('title:(["B" TO *])' in query) self.assertTrue('id:("1" OR "2" OR "3")' in query) self.assertTrue('rating:(["3" TO "5"])' in query) def test_build_query_multiple_filter_types_with_datetimes(self): self.sq.add_filter(SQ(content="why")) self.sq.add_filter(SQ(pub_date__lte=datetime.datetime(2009, 2, 10, 1, 59, 0))) self.sq.add_filter(SQ(author__gt="daniel")) self.sq.add_filter(SQ(created__lt=datetime.datetime(2009, 2, 12, 12, 13, 0))) self.sq.add_filter(SQ(title__gte="B")) self.sq.add_filter(SQ(id__in=[1, 2, 3])) self.sq.add_filter(SQ(rating__range=[3, 5])) self.assertEqual( self.sq.build_query(), '((why) AND pub_date:([* TO "2009-02-10T01:59:00Z"]) AND author:({"daniel" TO *}) AND created:({* TO "2009-02-12T12:13:00Z"}) AND title:(["B" TO *]) AND id:("1" OR "2" OR "3") AND rating:(["3" TO "5"]))', ) def test_build_query_in_filter_multiple_words(self): self.sq.add_filter(SQ(content="why")) self.sq.add_filter(SQ(title__in=["A Famous Paper", "An Infamous Article"])) self.assertEqual( self.sq.build_query(), '((why) AND title:("A Famous Paper" OR "An Infamous Article"))', ) def test_build_query_in_filter_datetime(self): self.sq.add_filter(SQ(content="why")) self.sq.add_filter(SQ(pub_date__in=[datetime.datetime(2009, 7, 6, 1, 56, 21)])) self.assertEqual( self.sq.build_query(), '((why) AND pub_date:("2009-07-06T01:56:21Z"))' ) def test_build_query_in_with_set(self): self.sq.add_filter(SQ(content="why")) self.sq.add_filter(SQ(title__in=set(["A Famous Paper", "An Infamous Article"]))) query = self.sq.build_query() self.assertTrue("(why)" in query) # Because ordering in Py3 is now random. if 'title:("A ' in query: self.assertTrue( 'title:("A Famous Paper" OR "An Infamous Article")' in query ) else: self.assertTrue( 'title:("An Infamous Article" OR "A Famous Paper")' in query ) def test_build_query_with_contains(self): self.sq.add_filter(SQ(content="circular")) self.sq.add_filter(SQ(title__contains="haystack")) self.assertEqual(self.sq.build_query(), "((circular) AND title:(*haystack*))") def test_build_query_with_endswith(self): self.sq.add_filter(SQ(content="circular")) self.sq.add_filter(SQ(title__endswith="haystack")) self.assertEqual(self.sq.build_query(), "((circular) AND title:(*haystack))") def test_build_query_wildcard_filter_types(self): self.sq.add_filter(SQ(content="why")) self.sq.add_filter(SQ(title__startswith="haystack")) self.assertEqual(self.sq.build_query(), "((why) AND title:(haystack*))") def test_build_query_fuzzy_filter_types(self): self.sq.add_filter(SQ(content="why")) self.sq.add_filter(SQ(title__fuzzy="haystack")) self.assertEqual(self.sq.build_query(), "((why) AND title:(haystack~))") def test_clean(self): self.assertEqual(self.sq.clean("hello world"), "hello world") self.assertEqual(self.sq.clean("hello AND world"), "hello and world") self.assertEqual( self.sq.clean( 'hello AND OR NOT TO + - && || ! ( ) { } [ ] ^ " ~ * ? : \ / world' ), 'hello and or not to \\+ \\- \\&& \\|| \\! \\( \\) \\{ \\} \\[ \\] \\^ \\" \\~ \\* \\? \\: \\\\ \\/ world', ) self.assertEqual( self.sq.clean("so please NOTe i am in a bAND and bORed"), "so please NOTe i am in a bAND and bORed", ) def test_build_query_with_models(self): self.sq.add_filter(SQ(content="hello")) self.sq.add_model(MockModel) self.assertEqual(self.sq.build_query(), "(hello)") self.sq.add_model(AnotherMockModel) self.assertEqual(self.sq.build_query(), "(hello)") def test_set_result_class(self): # Assert that we're defaulting to ``SearchResult``. self.assertTrue(issubclass(self.sq.result_class, SearchResult)) # Custom class. class IttyBittyResult: pass self.sq.set_result_class(IttyBittyResult) self.assertTrue(issubclass(self.sq.result_class, IttyBittyResult)) # Reset to default. self.sq.set_result_class(None) self.assertTrue(issubclass(self.sq.result_class, SearchResult)) def test_in_filter_values_list(self): self.sq.add_filter(SQ(content="why")) self.sq.add_filter(SQ(title__in=MockModel.objects.values_list("id", flat=True))) self.assertEqual(self.sq.build_query(), '((why) AND title:("1" OR "2" OR "3"))') def test_narrow_sq(self): sqs = SearchQuerySet(using="solr").narrow(SQ(foo="moof")) self.assertTrue(isinstance(sqs, SearchQuerySet)) self.assertEqual(len(sqs.query.narrow_queries), 1) self.assertEqual(sqs.query.narrow_queries.pop(), "foo:(moof)") def test_query__in(self): sqs = SearchQuerySet(using="solr").filter(id__in=[1, 2, 3]) self.assertEqual(sqs.query.build_query(), 'id:("1" OR "2" OR "3")') def test_query__in_empty_list(self): """Confirm that an empty list avoids a Solr exception""" sqs = SearchQuerySet(using="solr").filter(id__in=[]) self.assertEqual(sqs.query.build_query(), "id:(!*:*)")
SolrSearchQueryTestCase
python
python-openxml__python-docx
src/docx/document.py
{ "start": 854, "end": 10618 }
class ____(ElementProxy): """WordprocessingML (WML) document. Not intended to be constructed directly. Use :func:`docx.Document` to open or create a document. """ def __init__(self, element: CT_Document, part: DocumentPart): super(Document, self).__init__(element) self._element = element self._part = part self.__body = None def add_comment( self, runs: Run | Sequence[Run], text: str | None = "", author: str = "", initials: str | None = "", ) -> Comment: """Add a comment to the document, anchored to the specified runs. `runs` can be a single `Run` object or a non-empty sequence of `Run` objects. Only the first and last run of a sequence are used, it's just more convenient to pass a whole sequence when that's what you have handy, like `paragraph.runs` for example. When `runs` contains a single `Run` object, that run serves as both the first and last run. A comment can be anchored only on an even run boundary, meaning the text the comment "references" must be a non-zero integer number of consecutive runs. The runs need not be _contiguous_ per se, like the first can be in one paragraph and the last in the next paragraph, but all runs between the first and the last will be included in the reference. The comment reference range is delimited by placing a `w:commentRangeStart` element before the first run and a `w:commentRangeEnd` element after the last run. This is why only the first and last run are required and why a single run can serve as both first and last. Word works out which text to highlight in the UI based on these range markers. `text` allows the contents of a simple comment to be provided in the call, providing for the common case where a comment is a single phrase or sentence without special formatting such as bold or italics. More complex comments can be added using the returned `Comment` object in much the same way as a `Document` or (table) `Cell` object, using methods like `.add_paragraph()`, .add_run()`, etc. The `author` and `initials` parameters allow that metadata to be set for the comment. `author` is a required attribute on a comment and is the empty string by default. `initials` is optional on a comment and may be omitted by passing |None|, but Word adds an `initials` attribute by default and we follow that convention by using the empty string when no `initials` argument is provided. """ # -- normalize `runs` to a sequence of runs -- runs = [runs] if isinstance(runs, Run) else runs first_run = runs[0] last_run = runs[-1] # -- Note that comments can only appear in the document part -- comment = self.comments.add_comment(text=text, author=author, initials=initials) # -- let the first run orchestrate placement of the comment range start and end -- first_run.mark_comment_range(last_run, comment.comment_id) return comment def add_heading(self, text: str = "", level: int = 1): """Return a heading paragraph newly added to the end of the document. The heading paragraph will contain `text` and have its paragraph style determined by `level`. If `level` is 0, the style is set to `Title`. If `level` is 1 (or omitted), `Heading 1` is used. Otherwise the style is set to `Heading {level}`. Raises |ValueError| if `level` is outside the range 0-9. """ if not 0 <= level <= 9: raise ValueError("level must be in range 0-9, got %d" % level) style = "Title" if level == 0 else "Heading %d" % level return self.add_paragraph(text, style) def add_page_break(self): """Return newly |Paragraph| object containing only a page break.""" paragraph = self.add_paragraph() paragraph.add_run().add_break(WD_BREAK.PAGE) return paragraph def add_paragraph(self, text: str = "", style: str | ParagraphStyle | None = None) -> Paragraph: """Return paragraph newly added to the end of the document. The paragraph is populated with `text` and having paragraph style `style`. `text` can contain tab (``\\t``) characters, which are converted to the appropriate XML form for a tab. `text` can also include newline (``\\n``) or carriage return (``\\r``) characters, each of which is converted to a line break. """ return self._body.add_paragraph(text, style) def add_picture( self, image_path_or_stream: str | IO[bytes], width: int | Length | None = None, height: int | Length | None = None, ): """Return new picture shape added in its own paragraph at end of the document. The picture contains the image at `image_path_or_stream`, scaled based on `width` and `height`. If neither width nor height is specified, the picture appears at its native size. If only one is specified, it is used to compute a scaling factor that is then applied to the unspecified dimension, preserving the aspect ratio of the image. The native size of the picture is calculated using the dots-per-inch (dpi) value specified in the image file, defaulting to 72 dpi if no value is specified, as is often the case. """ run = self.add_paragraph().add_run() return run.add_picture(image_path_or_stream, width, height) def add_section(self, start_type: WD_SECTION = WD_SECTION.NEW_PAGE): """Return a |Section| object newly added at the end of the document. The optional `start_type` argument must be a member of the :ref:`WdSectionStart` enumeration, and defaults to ``WD_SECTION.NEW_PAGE`` if not provided. """ new_sectPr = self._element.body.add_section_break() new_sectPr.start_type = start_type return Section(new_sectPr, self._part) def add_table(self, rows: int, cols: int, style: str | _TableStyle | None = None): """Add a table having row and column counts of `rows` and `cols` respectively. `style` may be a table style object or a table style name. If `style` is |None|, the table inherits the default table style of the document. """ table = self._body.add_table(rows, cols, self._block_width) table.style = style return table @property def comments(self) -> Comments: """A |Comments| object providing access to comments added to the document.""" return self._part.comments @property def core_properties(self): """A |CoreProperties| object providing Dublin Core properties of document.""" return self._part.core_properties @property def inline_shapes(self): """The |InlineShapes| collection for this document. An inline shape is a graphical object, such as a picture, contained in a run of text and behaving like a character glyph, being flowed like other text in a paragraph. """ return self._part.inline_shapes def iter_inner_content(self) -> Iterator[Paragraph | Table]: """Generate each `Paragraph` or `Table` in this document in document order.""" return self._body.iter_inner_content() @property def paragraphs(self) -> List[Paragraph]: """The |Paragraph| instances in the document, in document order. Note that paragraphs within revision marks such as ``<w:ins>`` or ``<w:del>`` do not appear in this list. """ return self._body.paragraphs @property def part(self) -> DocumentPart: """The |DocumentPart| object of this document.""" return self._part def save(self, path_or_stream: str | IO[bytes]): """Save this document to `path_or_stream`. `path_or_stream` can be either a path to a filesystem location (a string) or a file-like object. """ self._part.save(path_or_stream) @property def sections(self) -> Sections: """|Sections| object providing access to each section in this document.""" return Sections(self._element, self._part) @property def settings(self) -> Settings: """A |Settings| object providing access to the document-level settings.""" return self._part.settings @property def styles(self): """A |Styles| object providing access to the styles in this document.""" return self._part.styles @property def tables(self) -> List[Table]: """All |Table| instances in the document, in document order. Note that only tables appearing at the top level of the document appear in this list; a table nested inside a table cell does not appear. A table within revision marks such as ``<w:ins>`` or ``<w:del>`` will also not appear in the list. """ return self._body.tables @property def _block_width(self) -> Length: """A |Length| object specifying the space between margins in last section.""" section = self.sections[-1] page_width = section.page_width or Inches(8.5) left_margin = section.left_margin or Inches(1) right_margin = section.right_margin or Inches(1) return Emu(page_width - left_margin - right_margin) @property def _body(self) -> _Body: """The |_Body| instance containing the content for this document.""" if self.__body is None: self.__body = _Body(self._element.body, self) return self.__body
Document
python
getsentry__sentry
tests/sentry/notifications/api/endpoints/test_user_notification_email.py
{ "start": 632, "end": 1503 }
class ____(UserNotificationEmailTestBase): def test_populates_useroptions_for_email(self) -> None: UserEmail.objects.create(user=self.user, email="alias@example.com", is_verified=True).save() UserEmail.objects.create( user=self.user, email="alias2@example.com", is_verified=True ).save() UserOption.objects.set_value( user=self.user, project=self.project, key="mail:email", value="alias@example.com" ) UserOption.objects.set_value( user=self.user, project=self.project2, key="mail:email", value="alias2@example.com" ) response = self.get_success_response("me") assert response.data == { str(self.project.id): "alias@example.com", str(self.project2.id): "alias2@example.com", } @control_silo_test()
UserNotificationEmailGetTest
python
google__pytype
pytype/pyi/parser_test.py
{ "start": 24888, "end": 36318 }
class ____(parser_test_base.ParserTestBase): def test_params(self): self.check("def foo() -> int: ...") self.check("def foo(x) -> int: ...") self.check("def foo(x: int) -> int: ...") self.check("def foo(x: int, y: str) -> int: ...") # Default values can add type information. self.check( "def foo(x = 123) -> int: ...", "def foo(x: int = ...) -> int: ..." ) self.check( "def foo(x = 12.3) -> int: ...", "def foo(x: float = ...) -> int: ..." ) self.check("def foo(x = None) -> int: ...", "def foo(x = ...) -> int: ...") self.check("def foo(x = xyz) -> int: ...", "def foo(x = ...) -> int: ...") self.check("def foo(x = ...) -> int: ...", "def foo(x = ...) -> int: ...") # Defaults are ignored if a declared type is present. self.check( "def foo(x: str = 123) -> int: ...", "def foo(x: str = ...) -> int: ..." ) self.check( "def foo(x: str = None) -> int: ...", "def foo(x: str = ...) -> int: ...", ) # Allow but do not preserve a trailing comma in the param list. self.check( "def foo(x: int, y: str, z: bool,) -> int: ...", "def foo(x: int, y: str, z: bool) -> int: ...", ) def test_defaults(self): self.check( """ def f(x: int = 3, y: str = " ") -> None: ... """, """ def f(x: int = ..., y: str = ...) -> None: ... """, ) def test_star_params(self): self.check("def foo(*, x) -> str: ...") self.check("def foo(x: int, *args) -> str: ...") self.check("def foo(x: int, *args, key: int = ...) -> str: ...") self.check("def foo(x: int, *args: float) -> str: ...") self.check("def foo(x: int, **kwargs) -> str: ...") self.check("def foo(x: int, **kwargs: float) -> str: ...") self.check("def foo(x: int, *args, **kwargs) -> str: ...") # Various illegal uses of * args. self.check_error( "def foo(*) -> int: ...", 1, "named arguments must follow bare *" ) if self.python_version >= (3, 11): expected_error = "ParseError" else: expected_error = "invalid syntax" self.check_error("def foo(*x, *y) -> int: ...", 1, expected_error) self.check_error("def foo(**x, *y) -> int: ...", 1, expected_error) def test_typeignore(self): self.check( "def foo() -> int: # type: ignore\n ...", "def foo() -> int: ..." ) self.check("def foo() -> int: ... # type: ignore", "def foo() -> int: ...") self.check( "def foo() -> int: pass # type: ignore", "def foo() -> int: ..." ) self.check( "def foo(x) -> int: # type: ignore\n x=List[int]", "def foo(x) -> int:\n x = List[int]", ) self.check( """ def foo(x: int, # type: ignore y: str) -> bool: ...""", "def foo(x: int, y: str) -> bool: ...", ) self.check( """ class Foo: bar: str # type: ignore """, """ class Foo: bar: str """, ) self.check( """ class Foo: bar = ... # type: str # type: ignore """, """ class Foo: bar: str """, ) self.check( """ class Foo: bar: str = ... # type: ignore """, """ class Foo: bar: str = ... """, ) self.check( """ def f( # type: ignore x: int) -> None: ... """, """ def f(x: int) -> None: ... """, ) def test_typeignore_alias(self): self.check( """ class Foo: def f(self) -> None: ... g = f # type: ignore """, """ class Foo: def f(self) -> None: ... def g(self) -> None: ... """, ) def test_typeignore_slots(self): self.check( """ class Foo: __slots__ = ["a", "b"] # type: ignore """, """ class Foo: __slots__ = ["a", "b"] """, ) def test_typeignore_errorcode(self): self.check( """ def f() -> None: ... # type: ignore[override] def g() -> None: ... # type: ignore[var-annotated] def h() -> None: ... # type: ignore[abstract, no-untyped-def] """, """ def f() -> None: ... def g() -> None: ... def h() -> None: ... """, ) def test_decorators(self): # These tests are a bit questionable because most of the decorators only # make sense for methods of classes. But this at least gives us some # coverage of the decorator logic. More sensible tests can be created once # classes are implemented. self.check( """ @overload def foo() -> int: ...""", """ def foo() -> int: ...""", ) # Accept and disregard type: ignore comments on a decorator self.check( """ @overload def foo() -> int: ... @overload # type: ignore # unsupported signature def foo(bool) -> int: ...""", """ from typing import overload @overload def foo() -> int: ... @overload def foo(bool) -> int: ...""", ) self.check( """ @abstractmethod def foo() -> int: ...""", """ @abstractmethod def foo() -> int: ...""", ) self.check( """ @abc.abstractmethod def foo() -> int: ...""", """ @abstractmethod def foo() -> int: ...""", ) self.check(""" @staticmethod def foo() -> int: ...""") self.check(""" @classmethod def foo() -> int: ...""") self.check(""" @coroutine def foo() -> int: ...""") self.check( """ @asyncio.coroutine def foo() -> int: ...""", """ @coroutine def foo() -> int: ...""", ) self.check( """ @asyncio.coroutine def foo() -> int: ... @coroutines.coroutine def foo() -> int: ... @coroutine def foo() -> str: ...""", """ from typing import overload @coroutine @overload def foo() -> int: ... @coroutine @overload def foo() -> int: ... @coroutine @overload def foo() -> str: ...""", ) self.check_error( """ def foo() -> str: ... @coroutine def foo() -> int: ...""", None, "Overloaded signatures for 'foo' disagree on coroutine decorators", ) self.check_error( """ @property def foo(self) -> int: ...""", None, "Module-level functions with property decorators: foo", ) self.check_error( """ @foo.setter def foo(self, x) -> int: ...""", None, "Module-level functions with property decorators: foo", ) self.check_error( """ @classmethod @staticmethod def foo() -> int: ...""", 3, "'foo' can be decorated with at most one of", ) def test_override_decorator(self): # We ignore typing.override in pyi files. self.check(""" from typing import Any from typing_extensions import override class A: def f(self) -> Any: ... class B(A): @override def f(self) -> Any: ... """) def test_module_getattr(self): self.check(""" def __getattr__(name) -> int: ... """) self.check_error( """ def __getattr__(name) -> int: ... def __getattr__(name) -> str: ... """, None, "Multiple signatures for module __getattr__", ) def test_type_check_only(self): self.check(""" from typing import type_check_only @type_check_only def f() -> None: ... """) def test_type_check_only_class(self): self.check(""" from typing import type_check_only @type_check_only class Foo: ... """) def test_decorated_class(self): self.check(""" @decorator class Foo: ... """) def test_multiple_class_decorators(self): self.check(""" @decorator1 @decorator2 class Foo: ... """) def test_bad_decorated_class(self): self.check_error( """ @classmethod class Foo: ... """, 2, "Unsupported class decorator: classmethod", ) self.check_error( """ from typing import overload @overload class Foo: ... """, 3, "Unsupported class decorator: overload", ) self.check_error( """ import typing @typing.overload class Foo: ... """, 3, "Unsupported class decorator: typing.overload", ) def test_dataclass_decorator(self): self.check(""" from dataclasses import dataclass @dataclass class Foo: x: int y: str = ... """) def test_dataclass_default_error(self): self.check_error( """ from dataclasses import dataclass @dataclass class Foo: x: int = ... y: str """, None, "non-default argument y follows default argument x", ) def test_empty_body(self): self.check("def foo() -> int: ...") self.check("def foo() -> int: ...", "def foo() -> int: ...") self.check("def foo() -> int: pass", "def foo() -> int: ...") self.check( """ def foo() -> int: ...""", """ def foo() -> int: ...""", ) self.check( """ def foo() -> int: pass""", """ def foo() -> int: ...""", ) self.check( """ def foo() -> int: '''doc string'''""", """ def foo() -> int: ...""", ) def test_mutators(self): # Mutators. self.check(""" def foo(x) -> int: x = int""") self.check_error( """ def foo(x) -> int: y = int""", 1, "No parameter named 'y'", ) def test_mutator_from_annotation(self): self.check( """ from typing import Generic, TypeVar T = TypeVar('T') class Foo(Generic[T]): def __init__(self: Foo[str]) -> None: ... """, """ from typing import Generic, TypeVar T = TypeVar('T') class Foo(Generic[T]): def __init__(self) -> None: self = Foo[str] """, ) def test_exceptions(self): self.check( """ def foo(x) -> int: raise Error""", """ def foo(x) -> int: raise Error()""", ) self.check(""" def foo(x) -> int: raise Error()""") self.check(""" def foo() -> int: raise RuntimeError() raise TypeError()""") self.check( """ def foo() -> int: raise Bar.Error()""", prologue="import Bar", ) def test_invalid_body(self): self.check_error( """ def foo(x) -> int: a: str""", 1, "Unexpected statement in function body", ) def test_return(self): self.check("def foo() -> int: ...") self.check( "def foo(): ...", "def foo() -> Any: ...", prologue="from typing import Any", ) def test_async(self): self.check( "async def foo() -> int: ...", "def foo() -> Coroutine[Any, Any, int]: ...", prologue="from typing import Any, Coroutine", )
FunctionTest
python
doocs__leetcode
solution/2300-2399/2352.Equal Row and Column Pairs/Solution.py
{ "start": 0, "end": 258 }
class ____: def equalPairs(self, grid: List[List[int]]) -> int: n = len(grid) ans = 0 for i in range(n): for j in range(n): ans += all(grid[i][k] == grid[k][j] for k in range(n)) return ans
Solution
python
pyinstaller__pyinstaller
tests/unit/test_modulegraph/testpkg-compatmodule/pkg/api3.py
{ "start": 154, "end": 203 }
class ____ (object, metaclass=type): pass
MyClass
python
huggingface__transformers
src/transformers/models/video_llama_3/video_processing_video_llama_3.py
{ "start": 1804, "end": 3105 }
class ____(VideosKwargs, total=False): min_pixels: int max_pixels: int patch_size: int temporal_patch_size: int merge_size: int min_frames: int max_frames: int use_token_compression: Optional[bool] @add_start_docstrings( "Constructs a fast Qwen2-VL image processor that dynamically resizes videos based on the original videos.", BASE_VIDEO_PROCESSOR_DOCSTRING, """ min_pixels (`int`, *optional*, defaults to `56 * 56`): The min pixels of the image to resize the image. max_pixels (`int`, *optional*, defaults to `28 * 28 * 1280`): The max pixels of the image to resize the image. patch_size (`int`, *optional*, defaults to 14): The spacial patch size of the vision encoder. temporal_patch_size (`int`, *optional*, defaults to 2): The temporal patch size of the vision encoder. merge_size (`int`, *optional*, defaults to 2): The merge size of the vision encoder to llm encoder. min_frames (`int`, *optional*, defaults to 4): The minimum number of frames that can be sampled. max_frames (`int`, *optional*, defaults to 768): The maximum number of frames that can be sampled. """, )
VideoLlama3VideoProcessorInitKwargs
python
PyCQA__bandit
bandit/core/meta_ast.py
{ "start": 172, "end": 1136 }
class ____: nodes = collections.OrderedDict() def __init__(self): pass def add_node(self, node, parent_id, depth): """Add a node to the AST node collection :param node: The AST node to add :param parent_id: The ID of the node's parent :param depth: The depth of the node :return: - """ node_id = hex(id(node)) LOG.debug("adding node : %s [%s]", node_id, depth) self.nodes[node_id] = { "raw": node, "parent_id": parent_id, "depth": depth, } def __str__(self): """Dumps a listing of all of the nodes Dumps a listing of all of the nodes for debugging purposes :return: - """ tmpstr = "" for k, v in self.nodes.items(): tmpstr += f"Node: {k}\n" tmpstr += f"\t{str(v)}\n" tmpstr += f"Length: {len(self.nodes)}\n" return tmpstr
BanditMetaAst
python
plotly__plotly.py
plotly/graph_objs/scatter/marker/colorbar/_tickfont.py
{ "start": 233, "end": 9954 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scatter.marker.colorbar" _path_str = "scatter.marker.colorbar.tickfont" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", "weight", } @property def color(self): """ The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def family(self): """ HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. The 'family' property is a string and must be specified as: - A non-empty string Returns ------- str """ return self["family"] @family.setter def family(self, val): self["family"] = val @property def lineposition(self): """ Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. The 'lineposition' property is a flaglist and may be specified as a string containing: - Any combination of ['under', 'over', 'through'] joined with '+' characters (e.g. 'under+over') OR exactly one of ['none'] (e.g. 'none') Returns ------- Any """ return self["lineposition"] @lineposition.setter def lineposition(self, val): self["lineposition"] = val @property def shadow(self): """ Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow for additional options. The 'shadow' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["shadow"] @shadow.setter def shadow(self, val): self["shadow"] = val @property def size(self): """ The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] Returns ------- int|float """ return self["size"] @size.setter def size(self, val): self["size"] = val @property def style(self): """ Sets whether a font should be styled with a normal or italic face from its family. The 'style' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'italic'] Returns ------- Any """ return self["style"] @style.setter def style(self, val): self["style"] = val @property def textcase(self): """ Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. The 'textcase' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'word caps', 'upper', 'lower'] Returns ------- Any """ return self["textcase"] @textcase.setter def textcase(self, val): self["textcase"] = val @property def variant(self): """ Sets the variant of the font. The 'variant' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'small-caps', 'all-small-caps', 'all-petite-caps', 'petite-caps', 'unicase'] Returns ------- Any """ return self["variant"] @variant.setter def variant(self, val): self["variant"] = val @property def weight(self): """ Sets the weight (or boldness) of the font. The 'weight' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 1000] OR exactly one of ['normal', 'bold'] (e.g. 'bold') Returns ------- int """ return self["weight"] @weight.setter def weight(self, val): self["weight"] = val @property def _prop_descriptions(self): return """\ color family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. size style Sets whether a font should be styled with a normal or italic face from its family. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. variant Sets the variant of the font. weight Sets the weight (or boldness) of the font. """ def __init__( self, arg=None, color=None, family=None, lineposition=None, shadow=None, size=None, style=None, textcase=None, variant=None, weight=None, **kwargs, ): """ Construct a new Tickfont object Sets the color bar's tick label font Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.scatter.marker .colorbar.Tickfont` color family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. size style Sets whether a font should be styled with a normal or italic face from its family. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. variant Sets the variant of the font. weight Sets the weight (or boldness) of the font. Returns ------- Tickfont """ super().__init__("tickfont") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.scatter.marker.colorbar.Tickfont constructor must be a dict or an instance of :class:`plotly.graph_objs.scatter.marker.colorbar.Tickfont`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("family", arg, family) self._set_property("lineposition", arg, lineposition) self._set_property("shadow", arg, shadow) self._set_property("size", arg, size) self._set_property("style", arg, style) self._set_property("textcase", arg, textcase) self._set_property("variant", arg, variant) self._set_property("weight", arg, weight) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Tickfont
python
getsentry__sentry
src/sentry_plugins/victorops/client.py
{ "start": 46, "end": 1409 }
class ____(ApiClient): monitoring_tool = "sentry" routing_key = "everyone" plugin_name = "victorops" allow_redirects = False def __init__(self, api_key, routing_key=None): self.api_key = api_key if routing_key: self.routing_key = routing_key super().__init__() def build_url(self, path): # http://victorops.force.com/knowledgebase/articles/Integration/Alert-Ingestion-API-Documentation/ return f"https://alert.victorops.com/integrations/generic/20131114/alert/{self.api_key}/{self.routing_key}" def request(self, data): return self._request(path="", method="post", data=data) def trigger_incident( self, message_type, entity_id, timestamp, state_message, entity_display_name=None, monitoring_tool=None, issue_url=None, **kwargs, ): kwargs.update( { "message_type": message_type, "entity_id": entity_id, "entity_display_name": entity_display_name, "timestamp": timestamp, "state_message": state_message, "monitoring_tool": monitoring_tool or self.monitoring_tool, "issue_url": issue_url, } ) return self.request(kwargs)
VictorOpsClient
python
modin-project__modin
modin/config/envvars.py
{ "start": 38164, "end": 38331 }
class ____(EnvironmentVariable, type=bool): """Set to true to use Modin's implementation of NumPy API.""" varname = "MODIN_NUMPY" default = False
ModinNumpy
python
pallets__quart
src/quart/wrappers/response.py
{ "start": 1810, "end": 2555 }
class ____(ResponseBody): def __init__(self, data: bytes) -> None: self.data = data self.begin = 0 self.end = len(self.data) async def __aenter__(self) -> DataBody: return self async def __aexit__( self, exc_type: type, exc_value: BaseException, tb: TracebackType ) -> None: pass def __aiter__(self) -> AsyncIterator[bytes]: return _DataBodyGen(self) async def make_conditional(self, begin: int, end: int | None) -> int: self.begin = begin self.end = len(self.data) if end is None else end self.end = min(len(self.data), self.end) _raise_if_invalid_range(self.begin, self.end, len(self.data)) return len(self.data)
DataBody
python
ApeWorX__ape
src/ape/api/providers.py
{ "start": 32211, "end": 34763 }
class ____(ProviderAPI): """ An API for providers that have development functionality, such as snapshotting. """ @cached_property def test_config(self) -> "PluginConfig": return self.config_manager.get_config("test") @abstractmethod def snapshot(self) -> "SnapshotID": """ Record the current state of the blockchain with intent to later call the method :meth:`~ape.managers.chain.ChainManager.revert` to go back to this point. This method is for local networks only. Returns: :class:`~ape.types.SnapshotID`: The snapshot ID. """ @abstractmethod def restore(self, snapshot_id: "SnapshotID"): """ Regress the current call using the given snapshot ID. Allows developers to go back to a previous state. Args: snapshot_id (str): The snapshot ID. """ @abstractmethod def set_timestamp(self, new_timestamp: int): """ Change the pending timestamp. Args: new_timestamp (int): The timestamp to set. Returns: int: The new timestamp. """ @abstractmethod def mine(self, num_blocks: int = 1): """ Advance by the given number of blocks. Args: num_blocks (int): The number of blocks allotted to mine. Defaults to ``1``. """ @property @abstractmethod def auto_mine(self) -> bool: """ Whether automine is enabled. """ @auto_mine.setter @abstractmethod def auto_mine(self, value) -> bool: """ Enable or disable automine. """ def _increment_call_func_coverage_hit_count(self, txn: TransactionAPI): """ A helper method for incrementing a method call function hit count in a non-orthodox way. This is because Hardhat does not support call traces yet. """ if ( not txn.receiver or not self._test_runner or not self._test_runner.config_wrapper.track_coverage ): return if not (contract_type := self.chain_manager.contracts.get(txn.receiver)) or not ( contract_src := self.local_project._create_contract_source(contract_type) ): return method_id = txn.data[:4] if method_id in contract_type.view_methods: method = contract_type.methods[method_id] self._test_runner.coverage_tracker.hit_function(contract_src, method)
TestProviderAPI
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_multiarray.py
{ "start": 239921, "end": 240464 }
class ____(TestCase): @xpassIfTorchDynamo_np # (reason="TODO") def test_0d(self): a = np.array(np.pi) assert_equal(f"{a:0.3g}", "3.14") assert_equal(f"{a[()]:0.3g}", "3.14") def test_1d_no_format(self): a = np.array([np.pi]) assert_equal(f"{a}", str(a)) def test_1d_format(self): # until gh-5543, ensure that the behaviour matches what it used to be a = np.array([np.pi]) assert_raises(TypeError, "{:30}".format, a) from numpy.testing import IS_PYPY
TestFormat
python
realpython__materials
python-protocol/adder_v6.py
{ "start": 287, "end": 478 }
class ____: def add(self, x: str, y: str) -> str: return x + y def add(adder: Adder) -> None: print(adder.add(2, 3)) add(IntAdder()) add(FloatAdder()) add(StrAdder())
StrAdder
python
django__django
tests/forms_tests/tests/test_forms.py
{ "start": 227873, "end": 231904 }
class ____(SimpleTestCase): @override_settings(FORM_RENDERER="forms_tests.tests.test_forms.CustomRenderer") def test_custom_renderer_template_name(self): class Person(Form): first_name = CharField() t = Template("{{ form }}") html = t.render(Context({"form": Person()})) expected = """ <div class="fieldWrapper"><label for="id_first_name">First name:</label> <input type="text" name="first_name" required id="id_first_name"></div> """ self.assertHTMLEqual(html, expected) @override_settings(FORM_RENDERER="forms_tests.tests.test_forms.CustomRenderer") def test_custom_renderer_field_template_name(self): class Person(Form): first_name = CharField() t = Template("{{ form.first_name.as_field_group }}") html = t.render(Context({"form": Person()})) expected = """ <label for="id_first_name">First name:</label> <p>Custom Field</p> <input type="text" name="first_name" required id="id_first_name"> """ self.assertHTMLEqual(html, expected) def test_per_form_template_name(self): class Person(Form): first_name = CharField() template_name = "forms_tests/form_snippet.html" t = Template("{{ form }}") html = t.render(Context({"form": Person()})) expected = """ <div class="fieldWrapper"><label for="id_first_name">First name:</label> <input type="text" name="first_name" required id="id_first_name"></div> """ self.assertHTMLEqual(html, expected) def test_errorlist_override(self): class CustomErrorList(ErrorList): template_name = "forms_tests/error.html" class CommentForm(Form): name = CharField(max_length=50, required=False) email = EmailField() comment = CharField() data = {"email": "invalid"} f = CommentForm(data, auto_id=False, error_class=CustomErrorList) self.assertHTMLEqual( f.as_p(), '<p>Name: <input type="text" name="name" maxlength="50"></p>' '<div class="errorlist">' '<div class="error">Enter a valid email address.</div></div>' "<p>Email: " '<input type="email" name="email" value="invalid" maxlength="320" ' 'aria-invalid="true" required></p><div class="errorlist">' '<div class="error">This field is required.</div></div>' '<p>Comment: <input type="text" name="comment" aria-invalid="true" ' "required></p>", ) def test_custom_renderer_error_dict(self): class CustomRenderer(DjangoTemplates): def render(self, template_name, context, request=None): if template_name == "django/forms/errors/dict/default.html": return "<strong>So many errors!</strong>" return super().render(template_name, context, request) form = Form({}, renderer=CustomRenderer()) form.full_clean() form.add_error(None, "Test error") self.assertHTMLEqual( form.errors.render(), "<strong>So many errors!</strong>", ) def test_cyclic_context_boundfield_render(self): class FirstNameForm(Form): first_name = CharField() template_name_label = "forms_tests/cyclic_context_boundfield_render.html" f = FirstNameForm() try: f.render() except RecursionError: self.fail("Cyclic reference in BoundField.render().") def test_legend_tag(self): class CustomFrameworkForm(FrameworkForm): template_name = "forms_tests/legend_test.html" required_css_class = "required" f = CustomFrameworkForm() self.assertHTMLEqual( str(f), '<label for="id_name" class="required">Name:</label>' '<legend class="required">Language:</legend>', )
OverrideTests
python
django__django
tests/generic_relations/models.py
{ "start": 2436, "end": 2472 }
class ____(Vegetable): pass
Carrot
python
readthedocs__readthedocs.org
readthedocs/embed/tests/test_api.py
{ "start": 1457, "end": 1661 }
class ____(BaseTestEmbedAPI): host = "project.readthedocs.io" def get(self, client, *args, **kwargs): r = client.get(*args, HTTP_HOST=self.host, **kwargs) return r
TestProxiedEmbedAPI
python
realpython__materials
django-view-auth/Blog/core/apps.py
{ "start": 36, "end": 83 }
class ____(AppConfig): name = "core"
CoreConfig
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/inconsistentConstructor1.py
{ "start": 165, "end": 311 }
class ____(Parent1): # This should generate an error if reportInconsistentConstructor is enabled. def __new__(cls, a: int | str): ...
Child1
python
getsentry__sentry
tests/sentry/issues/endpoints/test_group.py
{ "start": 3015, "end": 3433 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.endpoint = GroupAiEndpoint() self.project = self.create_project() self.group = self.create_group(project=self.project) def test_permission_classes(self) -> None: assert hasattr(self.endpoint, "permission_classes") assert self.endpoint.permission_classes == (GroupAiPermission,)
GroupAiEndpointTest
python
neetcode-gh__leetcode
python/0208-implement-trie-prefix-tree.py
{ "start": 0, "end": 103 }
class ____: def __init__(self): self.children = [None] * 26 self.end = False
TrieNode
python
ansible__ansible
lib/ansible/utils/collection_loader/_collection_finder.py
{ "start": 4092, "end": 6852 }
class ____(TraversableResources): """Implements ``importlib.resources.abc.TraversableResources`` for the collection Python loaders. The result of ``files`` will depend on whether a particular collection, or a sub package of a collection was referenced, as opposed to ``ansible_collections`` or a particular namespace. For a collection and its subpackages, a ``pathlib.Path`` instance will be returned, whereas for the higher level namespace packages, ``_AnsibleNSTraversable`` will be returned. """ def __init__(self, package, loader): self._package = package self._loader = loader def _get_name(self, package): try: # spec return package.name except AttributeError: # module return package.__name__ def _get_package(self, package): try: # spec return package.__parent__ except AttributeError: # module return package.__package__ def _get_path(self, package): try: # spec return package.origin except AttributeError: # module return package.__file__ def _is_ansible_ns_package(self, package): origin = getattr(package, 'origin', None) if not origin: return False if origin == SYNTHETIC_PACKAGE_NAME: return True module_filename = os.path.basename(origin) return module_filename in {'__synthetic__', '__init__.py'} def _ensure_package(self, package): if self._is_ansible_ns_package(package): # Short circuit our loaders return if self._get_package(package) != package.__name__: raise TypeError('%r is not a package' % package.__name__) def files(self): package = self._package parts = package.split('.') is_ns = parts[0] == 'ansible_collections' and len(parts) < 3 if isinstance(package, str): if is_ns: # Don't use ``spec_from_loader`` here, because that will point # to exactly 1 location for a namespace. Use ``find_spec`` # to get a list of all locations for the namespace package = find_spec(package) else: package = spec_from_loader(package, self._loader) elif not isinstance(package, ModuleType): raise TypeError('Expected string or module, got %r' % package.__class__.__name__) self._ensure_package(package) if is_ns: return _AnsibleNSTraversable(*package.submodule_search_locations) return pathlib.Path(self._get_path(package)).parent
_AnsibleTraversableResources
python
pydantic__pydantic
pydantic/v1/errors.py
{ "start": 15975, "end": 16080 }
class ____(PydanticValueError): msg_template = 'value is not a valid IPv6 interface'
IPv6InterfaceError
python
readthedocs__readthedocs.org
readthedocs/config/exceptions.py
{ "start": 64, "end": 1623 }
class ____(BuildUserError): GENERIC = "config:generic" DEFAULT_PATH_NOT_FOUND = "config:path:default-not-found" CONFIG_PATH_NOT_FOUND = "config:path:not-found" KEY_NOT_SUPPORTED_IN_VERSION = "config:key:not-supported-in-version" PYTHON_SYSTEM_PACKAGES_REMOVED = "config:python:system-packages-removed" PYTHON_USE_SYSTEM_SITE_PACKAGES_REMOVED = "config:python:use-system-site-packages-removed" INVALID_VERSION = "config:base:invalid-version" NOT_BUILD_TOOLS_OR_COMMANDS = "config:build:missing-build-tools-commands" BUILD_JOBS_AND_COMMANDS = "config:build:jobs-and-commands" BUILD_JOBS_BUILD_TYPE_MISSING_IN_FORMATS = "config:build:jobs:build:missing-in-formats" APT_INVALID_PACKAGE_NAME_PREFIX = "config:apt:invalid-package-name-prefix" APT_INVALID_PACKAGE_NAME = "config:apt:invalid-package-name" USE_PIP_FOR_EXTRA_REQUIREMENTS = "config:python:pip-required" PIP_PATH_OR_REQUIREMENT_REQUIRED = "config:python:pip-path-requirement-required" SPHINX_MKDOCS_CONFIG_TOGETHER = "config:base:sphinx-mkdocs-together" SUBMODULES_INCLUDE_EXCLUDE_TOGETHER = "config:submodules:include-exclude-together" INVALID_KEY_NAME = "config:base:invalid-key-name" SYNTAX_INVALID = "config:base:invalid-syntax" CONDA_KEY_REQUIRED = "config:conda:required" SPHINX_CONFIG_MISSING = "config:sphinx:missing-config" MKDOCS_CONFIG_MISSING = "config:mkdocs:missing-config" # TODO: improve these error messages shown to the user # See https://github.com/readthedocs/readthedocs.org/issues/10502
ConfigError
python
mlflow__mlflow
mlflow/server/graphql/autogenerated_graphql_schema.py
{ "start": 6250, "end": 6464 }
class ____(graphene.ObjectType): info = graphene.Field(MlflowRunInfo) data = graphene.Field(MlflowRunData) inputs = graphene.Field(MlflowRunInputs) outputs = graphene.Field(MlflowRunOutputs)
MlflowRun
python
tensorflow__tensorflow
tensorflow/python/compiler/xla/experimental/xla_sharding_test.py
{ "start": 1217, "end": 2749 }
class ____(test_util.TensorFlowTestCase): """Tests for member functions of the class xla_sharding.Sharding.""" def test_sharding_is_default_constructable(self): sharding = xla_sharding.Sharding() self.assertIsNotNone(sharding) def test_sharding_factory_functions_can_return_sharding_objects(self): """Tests the various recommended ways to construct a Sharding object. This is the most minimal of tests, doesn't assert anything about the Sharding object produced by a given factory methods other than that it has the correct type. """ self.assertIsInstance(xla_sharding.Sharding.replicate(), xla_sharding.Sharding) self.assertIsInstance(xla_sharding.Sharding.manual(), xla_sharding.Sharding) self.assertIsInstance( xla_sharding.Sharding.assign_device(0), xla_sharding.Sharding) self.assertIsInstance( xla_sharding.Sharding.tile(np.ones([3], dtype=int)), xla_sharding.Sharding) self.assertIsInstance( xla_sharding.Sharding.partial_tile(np.ones([3], dtype=int)), xla_sharding.Sharding) self.assertIsInstance( xla_sharding.Sharding.split( array_ops.ones([3, 8, 7], dtype=dtypes.int32), 1, 2), xla_sharding.Sharding) self.assertIsInstance( xla_sharding.Sharding.subgroup_tile( np.ones([2, 3, 3], dtype=int), [ xla_data_pb2.OpSharding.REPLICATED, xla_data_pb2.OpSharding.MANUAL ]), xla_sharding.Sharding)
ShardingTest
python
PrefectHQ__prefect
src/integrations/prefect-dbt/prefect_dbt/cloud/utils.py
{ "start": 1264, "end": 5099 }
class ____(Exception): """Raised when a call to dbt Cloud administrative API fails.""" @task( name="Call dbt Cloud administrative API endpoint", description="Calls a dbt Cloud administrative API endpoint", retries=3, retry_delay_seconds=10, ) async def call_dbt_cloud_administrative_api_endpoint( dbt_cloud_credentials: DbtCloudCredentials, path: str, http_method: str, params: Optional[Dict[str, Any]] = None, json: Optional[Dict[str, Any]] = None, ) -> Any: """ Task that calls a specified endpoint in the dbt Cloud administrative API. Use this task if a prebuilt one is not yet available. Args: dbt_cloud_credentials: Credentials for authenticating with dbt Cloud. path: The partial path for the request (e.g. /projects/). Will be appended onto the base URL as determined by the client configuration. http_method: HTTP method to call on the endpoint. params: Query parameters to include in the request. json: JSON serializable body to send in the request. Returns: The body of the response. If the body is JSON serializable, then the result of `json.loads` with the body as the input will be returned. Otherwise, the body will be returned directly. Examples: List projects for an account: ```python from prefect import flow from prefect_dbt.cloud import DbtCloudCredentials from prefect_dbt.cloud.utils import call_dbt_cloud_administrative_api_endpoint @flow def get_projects_flow(): credentials = DbtCloudCredentials(api_key="my_api_key", account_id=123456789) result = call_dbt_cloud_administrative_api_endpoint( dbt_cloud_credentials=credentials, path="/projects/", http_method="GET", ) return result["data"] get_projects_flow() ``` Create a new job: ```python from prefect import flow from prefect_dbt.cloud import DbtCloudCredentials from prefect_dbt.cloud.utils import call_dbt_cloud_administrative_api_endpoint @flow def create_job_flow(): credentials = DbtCloudCredentials(api_key="my_api_key", account_id=123456789) result = call_dbt_cloud_administrative_api_endpoint( dbt_cloud_credentials=credentials, path="/jobs/", http_method="POST", json={ "id": None, "account_id": 123456789, "project_id": 100, "environment_id": 10, "name": "Nightly run", "dbt_version": None, "triggers": {"github_webhook": True, "schedule": True}, "execute_steps": ["dbt run", "dbt test", "dbt source snapshot-freshness"], "settings": {"threads": 4, "target_name": "prod"}, "state": 1, "schedule": { "date": {"type": "every_day"}, "time": {"type": "every_hour", "interval": 1}, }, }, ) return result["data"] create_job_flow() ``` """ # noqa try: async with dbt_cloud_credentials.get_administrative_client() as client: response = await client.call_endpoint( http_method=http_method, path=path, params=params, json=json ) except HTTPStatusError as ex: raise DbtCloudAdministrativeApiCallFailed(extract_developer_message(ex)) from ex try: return response.json() except JSONDecodeError: return response.text
DbtCloudAdministrativeApiCallFailed
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/memberAccess15.py
{ "start": 192, "end": 248 }
class ____: async def get(self): return self
A
python
astropy__astropy
astropy/modeling/functional_models.py
{ "start": 30079, "end": 32338 }
class ____(_Trigonometric1D): """ One dimensional Cosine model. Parameters ---------- amplitude : float Oscillation amplitude frequency : float Oscillation frequency phase : float Oscillation phase See Also -------- ArcCosine1D, Sine1D, Tangent1D, Const1D, Linear1D Notes ----- Model formula: .. math:: f(x) = A \\cos(2 \\pi f x + 2 \\pi p) Examples -------- .. plot:: :include-source: import numpy as np import matplotlib.pyplot as plt from astropy.modeling.models import Cosine1D plt.figure() s1 = Cosine1D(amplitude=1, frequency=.25) r=np.arange(0, 10, .01) for amplitude in range(1,4): s1.amplitude = amplitude plt.plot(r, s1(r), color=str(0.25 * amplitude), lw=2) plt.axis([0, 10, -5, 5]) plt.show() """ @staticmethod def evaluate(x, amplitude, frequency, phase): """One dimensional Cosine model function.""" # Note: If frequency and x are quantities, they should normally have # inverse units, so that argument ends up being dimensionless. However, # np.sin of a dimensionless quantity will crash, so we remove the # quantity-ness from argument in this case (another option would be to # multiply by * u.rad but this would be slower overall). argument = TWOPI * (frequency * x + phase) if isinstance(argument, Quantity): argument = argument.value return amplitude * np.cos(argument) @staticmethod def fit_deriv(x, amplitude, frequency, phase): """One dimensional Cosine model derivative.""" d_amplitude = np.cos(TWOPI * frequency * x + TWOPI * phase) d_frequency = -( TWOPI * x * amplitude * np.sin(TWOPI * frequency * x + TWOPI * phase) ) d_phase = -(TWOPI * amplitude * np.sin(TWOPI * frequency * x + TWOPI * phase)) return [d_amplitude, d_frequency, d_phase] @property def inverse(self): """One dimensional inverse of Cosine.""" return ArcCosine1D( amplitude=self.amplitude, frequency=self.frequency, phase=self.phase )
Cosine1D
python
pytorch__pytorch
test/dynamo/test_subclasses.py
{ "start": 91621, "end": 93440 }
class ____(torch.nn.Module): def forward( self, primals_1: "Sym(s47)", # PlainAOTInput(idx=0) primals_2: "Sym(s16)", # PlainAOTInput(idx=1) primals_3: "f32[s47, s16]", # SubclassGetAttrAOTInput(base=PlainAOTInput(idx=2), attr='a') primals_4: "f32[s47, s16]", # SubclassGetAttrAOTInput(base=PlainAOTInput(idx=2), attr='b') primals_5: "Sym(s47)", # SubclassSizeAOTInput(base=PlainAOTInput(idx=2), idx=0) primals_6: "Sym(s16)", # SubclassSizeAOTInput(base=PlainAOTInput(idx=2), idx=1) primals_7: "Sym(s16)", # SubclassStrideAOTInput(base=PlainAOTInput(idx=2), idx=0) ): clone: "f32[s47, s16]" = torch.ops.aten.clone.default(primals_3); primals_3 = None clone_1: "f32[s47, s16]" = torch.ops.aten.clone.default(primals_4); primals_4 = None view: "f32[s47, s16]" = torch.ops.aten.view.default(clone, [primals_1, primals_2]); clone = None view_1: "f32[s47, s16]" = torch.ops.aten.view.default(clone_1, [primals_1, primals_2]); clone_1 = primals_1 = primals_2 = None return ( view, # SubclassGetAttrAOTOutput(base=PlainAOTOutput(idx=0), attr='a') view_1, # SubclassGetAttrAOTOutput(base=PlainAOTOutput(idx=0), attr='b') primals_5, # SubclassSizeAOTOutput(base=PlainAOTOutput(idx=0), idx=0) primals_7, # SubclassSizeAOTOutput(base=PlainAOTOutput(idx=0), idx=1) primals_7, # SubclassStrideAOTOutput(base=PlainAOTOutput(idx=0), idx=0) primals_5, # SavedForBackwardsAOTOutput(idx=0) primals_7, # SavedForBackwardsAOTOutput(idx=1) ) """, # noqa: B950 ) self.assertExpectedInline( normalize_gm(bw[0].print_readable(print_output=False, expanded_def=True)), """\
GraphModule
python
doocs__leetcode
solution/2200-2299/2272.Substring With Largest Variance/Solution.py
{ "start": 0, "end": 499 }
class ____: def largestVariance(self, s: str) -> int: ans = 0 for a, b in permutations(ascii_lowercase, 2): if a == b: continue f = [0, -inf] for c in s: if c == a: f[0], f[1] = f[0] + 1, f[1] + 1 elif c == b: f[1] = max(f[1] - 1, f[0] - 1) f[0] = 0 if ans < f[1]: ans = f[1] return ans
Solution
python
pytorch__pytorch
test/mobile/lightweight_dispatch/tests_setup.py
{ "start": 1438, "end": 1960 }
class ____(torch.nn.Module): def forward(self, a: int): values = torch.tensor( [4.0, 1.0, 1.0, 16.0], ) if a == 0: return torch.gradient( values, spacing=torch.scalar_tensor(2.0, dtype=torch.float64) ) elif a == 1: return torch.gradient(values, spacing=[torch.tensor(1.0).item()]) # upsample_linear1d.vec(Tensor input, int[]? output_size, bool align_corners, float[]? scale_factors) -> Tensor @save_model
ModelWithScalarList
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_type_lookup.py
{ "start": 8834, "end": 8928 }
class ____(Generic[T]): def __init__(self, arg: T) -> None: self.arg = arg
MyGeneric
python
oauthlib__oauthlib
tests/oauth2/rfc6749/endpoints/test_base_endpoint.py
{ "start": 247, "end": 2486 }
class ____(TestCase): def test_default_config(self): endpoint = BaseEndpoint() self.assertFalse(endpoint.catch_errors) self.assertTrue(endpoint.available) endpoint.catch_errors = True self.assertTrue(endpoint.catch_errors) endpoint.available = False self.assertFalse(endpoint.available) def test_error_catching(self): validator = RequestValidator() server = Server(validator) server.catch_errors = True h, b, s = server.create_token_response( 'https://example.com', body='grant_type=authorization_code&code=abc' ) self.assertIn("server_error", b) self.assertEqual(s, 500) def test_unavailability(self): validator = RequestValidator() server = Server(validator) server.available = False h, b, s = server.create_authorization_response('https://example.com') self.assertIn("temporarily_unavailable", b) self.assertEqual(s, 503) def test_wrapper(self): class TestServer(Server): @catch_errors_and_unavailability def throw_error(self, uri): raise ValueError() @catch_errors_and_unavailability def throw_oauth_error(self, uri): raise OAuth2Error() @catch_errors_and_unavailability def throw_fatal_oauth_error(self, uri): raise FatalClientError() validator = RequestValidator() server = TestServer(validator) server.catch_errors = True h, b, s = server.throw_error('a') self.assertIn("server_error", b) self.assertEqual(s, 500) server.available = False h, b, s = server.throw_error('a') self.assertIn("temporarily_unavailable", b) self.assertEqual(s, 503) server.available = True self.assertRaises(OAuth2Error, server.throw_oauth_error, 'a') self.assertRaises(FatalClientError, server.throw_fatal_oauth_error, 'a') server.catch_errors = False self.assertRaises(OAuth2Error, server.throw_oauth_error, 'a') self.assertRaises(FatalClientError, server.throw_fatal_oauth_error, 'a')
BaseEndpointTest
python
ray-project__ray
rllib/offline/shuffled_input.py
{ "start": 253, "end": 1355 }
class ____(InputReader): """Randomizes data over a sliding window buffer of N batches. This increases the randomization of the data, which is useful if the batches were not in random order to start with. """ @DeveloperAPI def __init__(self, child: InputReader, n: int = 0): """Initializes a ShuffledInput instance. Args: child: child input reader to shuffle. n: If positive, shuffle input over this many batches. """ self.n = n self.child = child self.buffer = [] @override(InputReader) def next(self) -> SampleBatchType: if self.n <= 1: return self.child.next() if len(self.buffer) < self.n: logger.info("Filling shuffle buffer to {} batches".format(self.n)) while len(self.buffer) < self.n: self.buffer.append(self.child.next()) logger.info("Shuffle buffer filled") i = random.randint(0, len(self.buffer) - 1) self.buffer[i] = self.child.next() return random.choice(self.buffer)
ShuffledInput
python
pyqtgraph__pyqtgraph
pyqtgraph/dockarea/DockArea.py
{ "start": 168, "end": 14234 }
class ____(Container, QtWidgets.QWidget): def __init__(self, parent=None, temporary=False, home=None): Container.__init__(self, self) QtWidgets.QWidget.__init__(self, parent=parent) self.dockdrop = DockDrop(self) self.dockdrop.removeAllowedArea('center') self.layout = QtWidgets.QVBoxLayout() self.layout.setContentsMargins(0,0,0,0) self.layout.setSpacing(0) self.setLayout(self.layout) self.docks = weakref.WeakValueDictionary() self.topContainer = None self.dockdrop.raiseOverlay() self.temporary = temporary self.tempAreas = [] self.home = home def type(self): return "top" def addDock(self, dock=None, position='bottom', relativeTo=None, **kwds): """Adds a dock to this area. ============== ================================================================= **Arguments:** dock The new Dock object to add. If None, then a new Dock will be created. position 'bottom', 'top', 'left', 'right', 'above', or 'below' relativeTo If relativeTo is None, then the new Dock is added to fill an entire edge of the window. If relativeTo is another Dock, then the new Dock is placed adjacent to it (or in a tabbed configuration for 'above' and 'below'). ============== ================================================================= All extra keyword arguments are passed to Dock.__init__() if *dock* is None. """ if dock is None: dock = Dock(**kwds) # store original area that the dock will return to when un-floated if not self.temporary: dock.orig_area = self ## Determine the container to insert this dock into. ## If there is no neighbor, then the container is the top. if relativeTo is None or relativeTo is self: if self.topContainer is None: container = self neighbor = None else: container = self.topContainer neighbor = None else: if isinstance(relativeTo, str): relativeTo = self.docks[relativeTo] container = self.getContainer(relativeTo) if container is None: raise TypeError("Dock %s is not contained in a DockArea; cannot add another dock relative to it." % relativeTo) neighbor = relativeTo ## what container type do we need? neededContainer = { 'bottom': 'vertical', 'top': 'vertical', 'left': 'horizontal', 'right': 'horizontal', 'above': 'tab', 'below': 'tab' }[position] ## Can't insert new containers into a tab container; insert outside instead. if neededContainer != container.type() and container.type() == 'tab': neighbor = container container = container.container() ## Decide if the container we have is suitable. ## If not, insert a new container inside. if neededContainer != container.type(): if neighbor is None: container = self.addContainer(neededContainer, self.topContainer) else: container = self.addContainer(neededContainer, neighbor) ## Insert the new dock before/after its neighbor insertPos = { 'bottom': 'after', 'top': 'before', 'left': 'before', 'right': 'after', 'above': 'before', 'below': 'after' }[position] #print "request insert", dock, insertPos, neighbor old = dock.container() container.insert(dock, insertPos, neighbor) self.docks[dock.name()] = dock if old is not None: old.apoptose() return dock def moveDock(self, dock, position, neighbor): """ Move an existing Dock to a new location. """ ## Moving to the edge of a tabbed dock causes a drop outside the tab box if position in ['left', 'right', 'top', 'bottom'] and neighbor is not None and neighbor.container() is not None and neighbor.container().type() == 'tab': neighbor = neighbor.container() self.addDock(dock, position, neighbor) def getContainer(self, obj): if obj is None: return self return obj.container() def makeContainer(self, typ): if typ == 'vertical': new = VContainer(self) elif typ == 'horizontal': new = HContainer(self) elif typ == 'tab': new = TContainer(self) else: raise ValueError("typ must be one of 'vertical', 'horizontal', or 'tab'") return new def addContainer(self, typ, obj): """Add a new container around obj""" new = self.makeContainer(typ) container = self.getContainer(obj) container.insert(new, 'before', obj) #print "Add container:", new, " -> ", container if obj is not None: new.insert(obj) self.dockdrop.raiseOverlay() return new def insert(self, new, pos=None, neighbor=None): if self.topContainer is not None: # Adding new top-level container; addContainer() should # take care of giving the old top container a new home. self.topContainer.containerChanged(None) self.layout.addWidget(new) new.containerChanged(self) self.topContainer = new self.dockdrop.raiseOverlay() def count(self): if self.topContainer is None: return 0 return 1 def resizeEvent(self, ev): self.dockdrop.resizeOverlay(self.size()) def addTempArea(self): if self.home is None: area = DockArea(temporary=True, home=self) self.tempAreas.append(area) win = TempAreaWindow(area) area.win = win win.show() else: area = self.home.addTempArea() #print "added temp area", area, area.window() return area def floatDock(self, dock): """Removes *dock* from this DockArea and places it in a new window.""" area = self.addTempArea() area.win.resize(dock.size()) area.moveDock(dock, 'top', None) def removeTempArea(self, area): self.tempAreas.remove(area) #print "close window", area.window() area.window().close() def saveState(self): """ Return a serialized (storable) representation of the state of all Docks in this DockArea.""" if self.topContainer is None: main = None else: main = self.childState(self.topContainer) state = {'main': main, 'float': []} for a in self.tempAreas: geo = a.win.geometry() geo = (geo.x(), geo.y(), geo.width(), geo.height()) state['float'].append((a.saveState(), geo)) return state def childState(self, obj): if isinstance(obj, Dock): return ('dock', obj.name(), {}) else: childs = [] for i in range(obj.count()): childs.append(self.childState(obj.widget(i))) return (obj.type(), childs, obj.saveState()) def restoreState(self, state, missing='error', extra='bottom'): """ Restore Dock configuration as generated by saveState. This function does not create any Docks--it will only restore the arrangement of an existing set of Docks. By default, docks that are described in *state* but do not exist in the dock area will cause an exception to be raised. This behavior can be changed by setting *missing* to 'ignore' or 'create'. Extra docks that are in the dockarea but that are not mentioned in *state* will be added to the bottom of the dockarea, unless otherwise specified by the *extra* argument. """ ## 1) make dict of all docks and list of existing containers containers, docks = self.findAll() oldTemps = self.tempAreas[:] #print "found docks:", docks ## 2) create container structure, move docks into new containers if state['main'] is not None: self.buildFromState(state['main'], docks, self, missing=missing) ## 3) create floating areas, populate for s in state['float']: a = self.addTempArea() a.buildFromState(s[0]['main'], docks, a, missing=missing) a.win.setGeometry(*s[1]) a.apoptose() # ask temp area to close itself if it is empty ## 4) Add any remaining docks to a float for d in docks.values(): if extra == 'float': a = self.addTempArea() a.addDock(d, 'below') else: self.moveDock(d, extra, None) #print "\nKill old containers:" ## 5) kill old containers for c in containers: c.close() for a in oldTemps: a.apoptose() def buildFromState(self, state, docks, root, depth=0, missing='error'): typ, contents, state = state if typ == 'dock': try: obj = docks[contents] del docks[contents] except KeyError: if missing == 'error': raise Exception('Cannot restore dock state; no dock with name "%s"' % contents) elif missing == 'create': obj = Dock(name=contents) elif missing == 'ignore': return else: raise ValueError('"missing" argument must be one of "error", "create", or "ignore".') else: obj = self.makeContainer(typ) root.insert(obj, 'after') if typ != 'dock': for o in contents: self.buildFromState(o, docks, obj, depth+1, missing=missing) # remove this container if possible. (there are valid situations when a restore will # generate empty containers, such as when using missing='ignore') # There are 2 cases where this container should be removed: # 1. There are no child items which might happen in missing is set to 'ignore' # 2. To remove a superfluous container (Another container as the sole children of this container) if obj.count() == 0 or (obj.count() == 1 and isinstance(obj.widget(0), Container)): obj.apoptose(propagate=False) obj.restoreState(state) ## this has to be done later? def findAll(self, obj=None, c=None, d=None): if obj is None: obj = self.topContainer ## check all temp areas first if c is None: c = [] d = {} for a in self.tempAreas: c1, d1 = a.findAll() c.extend(c1) d.update(d1) if isinstance(obj, Dock): d[obj.name()] = obj elif obj is not None: c.append(obj) for i in range(obj.count()): o2 = obj.widget(i) c2, d2 = self.findAll(o2) c.extend(c2) d.update(d2) return (c, d) def apoptose(self, propagate=True): # remove top container if possible, close this area if it is temporary. #print "apoptose area:", self.temporary, self.topContainer, self.topContainer.count() if self.topContainer is None or self.topContainer.count() == 0: self.topContainer = None if self.temporary and self.home is not None: originDockArea = self.home self.home = None # apoptose might be called again by dock, if temporary floating window is closed by # calling restoreState, see the call to apoptose() in TempAreaWindow.closeEvent(). # This would lead to a ValueError because this temp area was already removed # Since we are in the process of closing this temporary dock area # prevent calling removeTempArea by removing the reference to the original dock area. originDockArea.removeTempArea(self) #self.close() def clear(self): docks = self.findAll()[1] for dock in docks.values(): dock.close() def dragEnterEvent(self, *args): self.dockdrop.dragEnterEvent(*args) def dragMoveEvent(self, *args): self.dockdrop.dragMoveEvent(*args) def dragLeaveEvent(self, *args): self.dockdrop.dragLeaveEvent(*args) def dropEvent(self, *args): self.dockdrop.dropEvent(*args) def printState(self, state=None, name='Main'): # for debugging if state is None: state = self.saveState() print("=== %s dock area ===" % name) if state['main'] is None: print(" (empty)") else: self._printAreaState(state['main']) for i, float in enumerate(state['float']): self.printState(float[0], name='float %d' % i) def _printAreaState(self, area, indent=0): if area[0] == 'dock': print(" " * indent + area[0] + " " + str(area[1:])) return else: print(" " * indent + area[0]) for ch in area[1]: self._printAreaState(ch, indent+1)
DockArea
python
numpy__numpy
numpy/_core/tests/test_scalarmath.py
{ "start": 27302, "end": 29380 }
class ____: def test_seq_repeat(self): # Test that basic sequences get repeated when multiplied with # numpy integers. And errors are raised when multiplied with others. # Some of this behaviour may be controversial and could be open for # change. accepted_types = set(np.typecodes["AllInteger"]) deprecated_types = {'?'} forbidden_types = ( set(np.typecodes["All"]) - accepted_types - deprecated_types) forbidden_types -= {'V'} # can't default-construct void scalars for seq_type in (list, tuple): seq = seq_type([1, 2, 3]) for numpy_type in accepted_types: i = np.dtype(numpy_type).type(2) assert_equal(seq * i, seq * int(i)) assert_equal(i * seq, int(i) * seq) for numpy_type in deprecated_types: i = np.dtype(numpy_type).type() with assert_raises(TypeError): operator.mul(seq, i) for numpy_type in forbidden_types: i = np.dtype(numpy_type).type() assert_raises(TypeError, operator.mul, seq, i) assert_raises(TypeError, operator.mul, i, seq) def test_no_seq_repeat_basic_array_like(self): # Test that an array-like which does not know how to be multiplied # does not attempt sequence repeat (raise TypeError). # See also gh-7428. class ArrayLike: def __init__(self, arr): self.arr = arr def __array__(self, dtype=None, copy=None): return self.arr # Test for simple ArrayLike above and memoryviews (original report) for arr_like in (ArrayLike(np.ones(3)), memoryview(np.ones(3))): assert_array_equal(arr_like * np.float32(3.), np.full(3, 3.)) assert_array_equal(np.float32(3.) * arr_like, np.full(3, 3.)) assert_array_equal(arr_like * np.int_(3), np.full(3, 3)) assert_array_equal(np.int_(3) * arr_like, np.full(3, 3))
TestMultiply
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/constant_op_test.py
{ "start": 15340, "end": 15806 }
class ____(test.TestCase): def testIdTensor(self): with ops.Graph().as_default(): x = constant_op.constant(2.0, shape=[6], name="input") id_op = array_ops.identity(x, name="id") self.assertTrue(isinstance(id_op.op.inputs[0], tensor.Tensor)) self.assertProtoEquals("name: 'id' op: 'Identity' input: 'input' " "attr { key: 'T' value { type: DT_FLOAT } }", id_op.op.node_def)
IdentityOpTest
python
gevent__gevent
src/greentest/3.10/test_subprocess.py
{ "start": 156116, "end": 157687 }
class ____ (BaseTestCase): def setUp(self): super().setUp() f, fname = tempfile.mkstemp(".py", "te st") self.fname = fname.lower () os.write(f, b"import sys;" b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))" ) os.close(f) def tearDown(self): os.remove(self.fname) super().tearDown() def with_spaces(self, *args, **kwargs): kwargs['stdout'] = subprocess.PIPE p = subprocess.Popen(*args, **kwargs) with p: self.assertEqual( p.stdout.read ().decode("mbcs"), "2 [%r, 'ab cd']" % self.fname ) def test_shell_string_with_spaces(self): # call() function with string argument with spaces on Windows self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, "ab cd"), shell=1) def test_shell_sequence_with_spaces(self): # call() function with sequence argument with spaces on Windows self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1) def test_noshell_string_with_spaces(self): # call() function with string argument with spaces on Windows self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname, "ab cd")) def test_noshell_sequence_with_spaces(self): # call() function with sequence argument with spaces on Windows self.with_spaces([sys.executable, self.fname, "ab cd"])
CommandsWithSpaces
python
redis__redis-py
tests/test_multidb/test_config.py
{ "start": 686, "end": 5198 }
class ____: def test_default_config(self): db_configs = [ DatabaseConfig( client_kwargs={"host": "host1", "port": "port1"}, weight=1.0 ), DatabaseConfig( client_kwargs={"host": "host2", "port": "port2"}, weight=0.9 ), DatabaseConfig( client_kwargs={"host": "host3", "port": "port3"}, weight=0.8 ), ] config = MultiDbConfig(databases_config=db_configs) assert config.databases_config == db_configs databases = config.databases() assert len(databases) == 3 i = 0 for db, weight in databases: assert isinstance(db, Database) assert weight == db_configs[i].weight assert db.circuit.grace_period == DEFAULT_GRACE_PERIOD assert db.client.get_retry() is not config.command_retry i += 1 assert len(config.default_failure_detectors()) == 1 assert isinstance(config.default_failure_detectors()[0], CommandFailureDetector) assert len(config.default_health_checks()) == 1 assert isinstance(config.default_health_checks()[0], PingHealthCheck) assert config.health_check_interval == DEFAULT_HEALTH_CHECK_INTERVAL assert isinstance( config.default_failover_strategy(), WeightBasedFailoverStrategy ) assert config.auto_fallback_interval == DEFAULT_AUTO_FALLBACK_INTERVAL assert isinstance(config.command_retry, Retry) def test_overridden_config(self): grace_period = 2 mock_connection_pools = [ Mock(spec=ConnectionPool), Mock(spec=ConnectionPool), Mock(spec=ConnectionPool), ] mock_connection_pools[0].connection_kwargs = {} mock_connection_pools[1].connection_kwargs = {} mock_connection_pools[2].connection_kwargs = {} mock_cb1 = Mock(spec=CircuitBreaker) mock_cb1.grace_period = grace_period mock_cb2 = Mock(spec=CircuitBreaker) mock_cb2.grace_period = grace_period mock_cb3 = Mock(spec=CircuitBreaker) mock_cb3.grace_period = grace_period mock_failure_detectors = [ Mock(spec=FailureDetector), Mock(spec=FailureDetector), ] mock_health_checks = [Mock(spec=HealthCheck), Mock(spec=HealthCheck)] health_check_interval = 10 mock_failover_strategy = Mock(spec=FailoverStrategy) auto_fallback_interval = 10 db_configs = [ DatabaseConfig( client_kwargs={"connection_pool": mock_connection_pools[0]}, weight=1.0, circuit=mock_cb1, ), DatabaseConfig( client_kwargs={"connection_pool": mock_connection_pools[1]}, weight=0.9, circuit=mock_cb2, ), DatabaseConfig( client_kwargs={"connection_pool": mock_connection_pools[2]}, weight=0.8, circuit=mock_cb3, ), ] config = MultiDbConfig( databases_config=db_configs, failure_detectors=mock_failure_detectors, health_checks=mock_health_checks, health_check_interval=health_check_interval, failover_strategy=mock_failover_strategy, auto_fallback_interval=auto_fallback_interval, ) assert config.databases_config == db_configs databases = config.databases() assert len(databases) == 3 i = 0 for db, weight in databases: assert isinstance(db, Database) assert weight == db_configs[i].weight assert db.client.connection_pool == mock_connection_pools[i] assert db.circuit.grace_period == grace_period i += 1 assert len(config.failure_detectors) == 2 assert config.failure_detectors[0] == mock_failure_detectors[0] assert config.failure_detectors[1] == mock_failure_detectors[1] assert len(config.health_checks) == 2 assert config.health_checks[0] == mock_health_checks[0] assert config.health_checks[1] == mock_health_checks[1] assert config.health_check_interval == health_check_interval assert config.failover_strategy == mock_failover_strategy assert config.auto_fallback_interval == auto_fallback_interval @pytest.mark.onlynoncluster
TestMultiDbConfig
python
doocs__leetcode
solution/2000-2099/2029.Stone Game IX/Solution.py
{ "start": 0, "end": 528 }
class ____: def stoneGameIX(self, stones: List[int]) -> bool: def check(cnt: List[int]) -> bool: if cnt[1] == 0: return False cnt[1] -= 1 r = 1 + min(cnt[1], cnt[2]) * 2 + cnt[0] if cnt[1] > cnt[2]: cnt[1] -= 1 r += 1 return r % 2 == 1 and cnt[1] != cnt[2] c1 = [0] * 3 for x in stones: c1[x % 3] += 1 c2 = [c1[0], c1[2], c1[1]] return check(c1) or check(c2)
Solution
python
airbytehq__airbyte
airbyte-ci/connectors/metadata_service/lib/metadata_service/models/generated/ConnectorRegistryDestinationDefinition.py
{ "start": 10357, "end": 10877 }
class ____(BaseModel): class Config: extra = Extra.forbid releaseCandidates: Optional[ConnectorReleaseCandidates] = None rolloutConfiguration: Optional[RolloutConfiguration] = None breakingChanges: Optional[ConnectorBreakingChanges] = None migrationDocumentationUrl: Optional[AnyUrl] = Field( None, description="URL to documentation on how to migrate from the previous version to the current version. Defaults to ${documentationUrl}-migrations", )
ConnectorRegistryReleases
python
doocs__leetcode
solution/2500-2599/2503.Maximum Number of Points From Grid Queries/Solution.py
{ "start": 0, "end": 772 }
class ____: def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]: m, n = len(grid), len(grid[0]) qs = sorted((v, i) for i, v in enumerate(queries)) ans = [0] * len(qs) q = [(grid[0][0], 0, 0)] cnt = 0 vis = [[False] * n for _ in range(m)] vis[0][0] = True for v, k in qs: while q and q[0][0] < v: _, i, j = heappop(q) cnt += 1 for a, b in pairwise((-1, 0, 1, 0, -1)): x, y = i + a, j + b if 0 <= x < m and 0 <= y < n and not vis[x][y]: heappush(q, (grid[x][y], x, y)) vis[x][y] = True ans[k] = cnt return ans
Solution
python
huggingface__transformers
src/transformers/models/luke/modeling_luke.py
{ "start": 18537, "end": 24071 }
class ____(nn.Module): def __init__(self, config): super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size {config.hidden_size} is not a multiple of the number of attention " f"heads {config.num_attention_heads}." ) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.use_entity_aware_attention = config.use_entity_aware_attention self.query = nn.Linear(config.hidden_size, self.all_head_size) self.key = nn.Linear(config.hidden_size, self.all_head_size) self.value = nn.Linear(config.hidden_size, self.all_head_size) if self.use_entity_aware_attention: self.w2e_query = nn.Linear(config.hidden_size, self.all_head_size) self.e2w_query = nn.Linear(config.hidden_size, self.all_head_size) self.e2e_query = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) x = x.view(*new_x_shape) return x.permute(0, 2, 1, 3) def forward( self, word_hidden_states, entity_hidden_states, attention_mask=None, output_attentions=False, ): word_size = word_hidden_states.size(1) if entity_hidden_states is None: concat_hidden_states = word_hidden_states else: concat_hidden_states = torch.cat([word_hidden_states, entity_hidden_states], dim=1) key_layer = self.transpose_for_scores(self.key(concat_hidden_states)) value_layer = self.transpose_for_scores(self.value(concat_hidden_states)) if self.use_entity_aware_attention and entity_hidden_states is not None: # compute query vectors using word-word (w2w), word-entity (w2e), entity-word (e2w), entity-entity (e2e) # query layers w2w_query_layer = self.transpose_for_scores(self.query(word_hidden_states)) w2e_query_layer = self.transpose_for_scores(self.w2e_query(word_hidden_states)) e2w_query_layer = self.transpose_for_scores(self.e2w_query(entity_hidden_states)) e2e_query_layer = self.transpose_for_scores(self.e2e_query(entity_hidden_states)) # compute w2w, w2e, e2w, and e2e key vectors used with the query vectors computed above w2w_key_layer = key_layer[:, :, :word_size, :] e2w_key_layer = key_layer[:, :, :word_size, :] w2e_key_layer = key_layer[:, :, word_size:, :] e2e_key_layer = key_layer[:, :, word_size:, :] # compute attention scores based on the dot product between the query and key vectors w2w_attention_scores = torch.matmul(w2w_query_layer, w2w_key_layer.transpose(-1, -2)) w2e_attention_scores = torch.matmul(w2e_query_layer, w2e_key_layer.transpose(-1, -2)) e2w_attention_scores = torch.matmul(e2w_query_layer, e2w_key_layer.transpose(-1, -2)) e2e_attention_scores = torch.matmul(e2e_query_layer, e2e_key_layer.transpose(-1, -2)) # combine attention scores to create the final attention score matrix word_attention_scores = torch.cat([w2w_attention_scores, w2e_attention_scores], dim=3) entity_attention_scores = torch.cat([e2w_attention_scores, e2e_attention_scores], dim=3) attention_scores = torch.cat([word_attention_scores, entity_attention_scores], dim=2) else: query_layer = self.transpose_for_scores(self.query(concat_hidden_states)) attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) attention_scores = attention_scores / math.sqrt(self.attention_head_size) if attention_mask is not None: # Apply the attention mask is (precomputed for all layers in LukeModel forward() function) attention_scores = attention_scores + attention_mask # Normalize the attention scores to probabilities. attention_probs = nn.functional.softmax(attention_scores, dim=-1) # This is actually dropping out entire tokens to attend to, which might # seem a bit unusual, but is taken from the original Transformer paper. attention_probs = self.dropout(attention_probs) context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) context_layer = context_layer.view(*new_context_layer_shape) output_word_hidden_states = context_layer[:, :word_size, :] if entity_hidden_states is None: output_entity_hidden_states = None else: output_entity_hidden_states = context_layer[:, word_size:, :] if output_attentions: outputs = (output_word_hidden_states, output_entity_hidden_states, attention_probs) else: outputs = (output_word_hidden_states, output_entity_hidden_states) return outputs # Copied from transformers.models.bert.modeling_bert.BertSelfOutput
LukeSelfAttention
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1296940, "end": 1297402 }
class ____(sgqlc.types.Type, Node): """A version tag contains the mapping between a tag name and a version. """ __schema__ = github_schema __field_names__ = ("name", "version") name = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="name") """Identifies the tag name of the version.""" version = sgqlc.types.Field("PackageVersion", graphql_name="version") """Version that the tag is associated with."""
PackageTag
python
sqlalchemy__sqlalchemy
test/orm/dml/test_bulk_statements.py
{ "start": 87442, "end": 90239 }
class ____(testing.AssertsCompiledSQL, fixtures.TestBase): __dialect__ = "default_enhanced" # for UPDATE..FROM @testing.variation("style", ["insert", "upsert"]) def test_insert_values_from_primary_table_only(self, decl_base, style): """test for #12692""" class A(decl_base): __tablename__ = "a" id: Mapped[int] = mapped_column(Identity(), primary_key=True) data: Mapped[int] class B(decl_base): __tablename__ = "b" id: Mapped[int] = mapped_column(Identity(), primary_key=True) data: Mapped[str] stmt = insert(A.__table__) # we're trying to exercise codepaths in orm/bulk_persistence.py that # would only apply to an insert() statement against the ORM entity, # e.g. insert(A). In the update() case, the WHERE clause can also # pull in the ORM entity, which is how we found the issue here, but # for INSERT there's no current method that does this; returning() # could do this in theory but currently doesnt. So for now, cheat, # and pretend there's some conversion that's going to propagate # from an ORM expression coercions.expect( roles.WhereHavingRole, B.id == 5, apply_propagate_attrs=stmt ) if style.insert: stmt = stmt.values(data=123) # assert that the ORM did not get involved, putting B.data as the # key in the dictionary is_(stmt._values["data"].type._type_affinity, NullType) elif style.upsert: stmt = stmt.values([{"data": 123}, {"data": 456}]) # assert that the ORM did not get involved, putting B.data as the # keys in the dictionaries eq_(stmt._multi_values, ([{"data": 123}, {"data": 456}],)) else: style.fail() def test_update_values_from_primary_table_only(self, decl_base): """test for #12692""" class A(decl_base): __tablename__ = "a" id: Mapped[int] = mapped_column(Identity(), primary_key=True) data: Mapped[str] updated_at: Mapped[datetime.datetime] = mapped_column( onupdate=func.now() ) class B(decl_base): __tablename__ = "b" id: Mapped[int] = mapped_column(Identity(), primary_key=True) data: Mapped[str] updated_at: Mapped[datetime.datetime] = mapped_column( onupdate=func.now() ) stmt = update(A.__table__).where(B.id == 1).values(data="some data") self.assert_compile( stmt, "UPDATE a SET data=:data, updated_at=now() " "FROM b WHERE b.id = :id_1", )
DMLCompileScenariosTest
python
huggingface__transformers
examples/modular-transformers/modeling_test_detr.py
{ "start": 36104, "end": 38673 }
class ____(PreTrainedModel): config: TestDetrConfig base_model_prefix = "model" main_input_name = "pixel_values" supports_gradient_checkpointing = True _no_split_modules = [ r"TestDetrConvEncoder", r"TestDetrEncoderLayer", r"TestDetrDecoderLayer", ] def _init_weights(self, module): std = self.config.init_std if isinstance(module, TestDetrLearnedPositionEmbedding): nn.init.uniform_(module.row_embeddings.weight) nn.init.uniform_(module.column_embeddings.weight) elif isinstance(module, TestDetrMultiscaleDeformableAttention): nn.init.constant_(module.sampling_offsets.weight.data, 0.0) default_dtype = torch.get_default_dtype() thetas = torch.arange(module.n_heads, dtype=torch.int64).to(default_dtype) * ( 2.0 * math.pi / module.n_heads ) grid_init = torch.stack([thetas.cos(), thetas.sin()], -1) grid_init = ( (grid_init / grid_init.abs().max(-1, keepdim=True)[0]) .view(module.n_heads, 1, 1, 2) .repeat(1, module.n_levels, module.n_points, 1) ) for i in range(module.n_points): grid_init[:, :, i, :] *= i + 1 with torch.no_grad(): module.sampling_offsets.bias = nn.Parameter(grid_init.view(-1)) nn.init.constant_(module.attention_weights.weight.data, 0.0) nn.init.constant_(module.attention_weights.bias.data, 0.0) nn.init.xavier_uniform_(module.value_proj.weight.data) nn.init.constant_(module.value_proj.bias.data, 0.0) nn.init.xavier_uniform_(module.output_proj.weight.data) nn.init.constant_(module.output_proj.bias.data, 0.0) elif isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)): module.weight.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.zero_() elif isinstance(module, nn.Embedding): module.weight.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() if hasattr(module, "reference_points") and not self.config.two_stage: nn.init.xavier_uniform_(module.reference_points.weight.data, gain=1.0) nn.init.constant_(module.reference_points.bias.data, 0.0) if hasattr(module, "level_embed"): nn.init.normal_(module.level_embed)
TestDetrPreTrainedModel
python
walkccc__LeetCode
solutions/1903. Largest Odd Number in String/1903.py
{ "start": 0, "end": 178 }
class ____: def largestOddNumber(self, num: str) -> str: for i, n in reversed(list(enumerate(num))): if int(n) % 2 == 1: return num[:i + 1] return ''
Solution
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/nested_fr.py
{ "start": 120, "end": 857 }
class ____(App): """The innermost container should push its parents outwards, to fill the screen.""" CSS = """ #outer { background: blue; height: auto; border: solid white; } #inner { background: green; height: auto; border: solid yellow; } #innermost { background: cyan; height: 1fr; color: auto; } """ def compose(self) -> ComposeResult: with Vertical(id="outer"): with Vertical(id="inner"): with Vertical(id="innermost"): yield Static("Hello\nWorld!\nfoo", id="helloworld") if __name__ == "__main__": app = AutoApp() app.run()
AutoApp
python
doocs__leetcode
solution/0100-0199/0165.Compare Version Numbers/Solution.py
{ "start": 0, "end": 545 }
class ____: def compareVersion(self, version1: str, version2: str) -> int: m, n = len(version1), len(version2) i = j = 0 while i < m or j < n: a = b = 0 while i < m and version1[i] != '.': a = a * 10 + int(version1[i]) i += 1 while j < n and version2[j] != '.': b = b * 10 + int(version2[j]) j += 1 if a != b: return -1 if a < b else 1 i, j = i + 1, j + 1 return 0
Solution
python
huggingface__transformers
src/transformers/models/lightglue/modular_lightglue.py
{ "start": 10743, "end": 10822 }
class ____(SuperGlueImageProcessorKwargs): pass
LightGlueImageProcessorKwargs
python
python-openxml__python-docx
tests/opc/test_pkgreader.py
{ "start": 662, "end": 10095 }
class ____: def it_can_construct_from_pkg_file( self, _init_, PhysPkgReader_, from_xml, _srels_for, _load_serialized_parts ): phys_reader = PhysPkgReader_.return_value content_types = from_xml.return_value pkg_srels = _srels_for.return_value sparts = _load_serialized_parts.return_value pkg_file = Mock(name="pkg_file") pkg_reader = PackageReader.from_file(pkg_file) PhysPkgReader_.assert_called_once_with(pkg_file) from_xml.assert_called_once_with(phys_reader.content_types_xml) _srels_for.assert_called_once_with(phys_reader, "/") _load_serialized_parts.assert_called_once_with(phys_reader, pkg_srels, content_types) phys_reader.close.assert_called_once_with() _init_.assert_called_once_with(ANY, content_types, pkg_srels, sparts) assert isinstance(pkg_reader, PackageReader) def it_can_iterate_over_the_serialized_parts(self, iter_sparts_fixture): pkg_reader, expected_iter_spart_items = iter_sparts_fixture iter_spart_items = list(pkg_reader.iter_sparts()) assert iter_spart_items == expected_iter_spart_items def it_can_iterate_over_all_the_srels(self): # mockery ---------------------- pkg_srels = ["srel1", "srel2"] sparts = [ Mock(name="spart1", partname="pn1", srels=["srel3", "srel4"]), Mock(name="spart2", partname="pn2", srels=["srel5", "srel6"]), ] pkg_reader = PackageReader(None, pkg_srels, sparts) # exercise --------------------- generated_tuples = list(pkg_reader.iter_srels()) # verify ----------------------- expected_tuples = [ ("/", "srel1"), ("/", "srel2"), ("pn1", "srel3"), ("pn1", "srel4"), ("pn2", "srel5"), ("pn2", "srel6"), ] assert generated_tuples == expected_tuples def it_can_load_serialized_parts(self, _SerializedPart_, _walk_phys_parts): # test data -------------------- test_data = ( ("/part/name1.xml", "app/vnd.type_1", "reltype1", "<Part_1/>", "srels_1"), ("/part/name2.xml", "app/vnd.type_2", "reltype2", "<Part_2/>", "srels_2"), ) iter_vals = [(t[0], t[2], t[3], t[4]) for t in test_data] content_types = {t[0]: t[1] for t in test_data} # mockery ---------------------- phys_reader = Mock(name="phys_reader") pkg_srels = Mock(name="pkg_srels") _walk_phys_parts.return_value = iter_vals _SerializedPart_.side_effect = expected_sparts = ( Mock(name="spart_1"), Mock(name="spart_2"), ) # exercise --------------------- retval = PackageReader._load_serialized_parts(phys_reader, pkg_srels, content_types) # verify ----------------------- expected_calls = [ call("/part/name1.xml", "app/vnd.type_1", "<Part_1/>", "reltype1", "srels_1"), call("/part/name2.xml", "app/vnd.type_2", "<Part_2/>", "reltype2", "srels_2"), ] assert _SerializedPart_.call_args_list == expected_calls assert retval == expected_sparts def it_can_walk_phys_pkg_parts(self, _srels_for): # test data -------------------- # +----------+ +--------+ # | pkg_rels |-----> | part_1 | # +----------+ +--------+ # | | ^ # v v | # external +--------+ +--------+ # | part_2 |---> | part_3 | # +--------+ +--------+ partname_1, partname_2, partname_3 = ( "/part/name1.xml", "/part/name2.xml", "/part/name3.xml", ) part_1_blob, part_2_blob, part_3_blob = ("<Part_1/>", "<Part_2/>", "<Part_3/>") reltype1, reltype2, reltype3 = ("reltype1", "reltype2", "reltype3") srels = [ Mock(name="rId1", is_external=True), Mock( name="rId2", is_external=False, reltype=reltype1, target_partname=partname_1, ), Mock( name="rId3", is_external=False, reltype=reltype2, target_partname=partname_2, ), Mock( name="rId4", is_external=False, reltype=reltype1, target_partname=partname_1, ), Mock( name="rId5", is_external=False, reltype=reltype3, target_partname=partname_3, ), ] pkg_srels = srels[:2] part_1_srels = srels[2:3] part_2_srels = srels[3:5] part_3_srels = [] # mockery ---------------------- phys_reader = Mock(name="phys_reader") _srels_for.side_effect = [part_1_srels, part_2_srels, part_3_srels] phys_reader.blob_for.side_effect = [part_1_blob, part_2_blob, part_3_blob] # exercise --------------------- generated_tuples = list(PackageReader._walk_phys_parts(phys_reader, pkg_srels)) # verify ----------------------- expected_tuples = [ (partname_1, part_1_blob, reltype1, part_1_srels), (partname_2, part_2_blob, reltype2, part_2_srels), (partname_3, part_3_blob, reltype3, part_3_srels), ] assert generated_tuples == expected_tuples def it_can_retrieve_srels_for_a_source_uri(self, _SerializedRelationships_): # mockery ---------------------- phys_reader = Mock(name="phys_reader") source_uri = Mock(name="source_uri") rels_xml = phys_reader.rels_xml_for.return_value load_from_xml = _SerializedRelationships_.load_from_xml srels = load_from_xml.return_value # exercise --------------------- retval = PackageReader._srels_for(phys_reader, source_uri) # verify ----------------------- phys_reader.rels_xml_for.assert_called_once_with(source_uri) load_from_xml.assert_called_once_with(source_uri.baseURI, rels_xml) assert retval == srels # fixtures ------------------------------------------------------- @pytest.fixture def blobs_(self, request): blob_ = loose_mock(request, spec=str, name="blob_") blob_2_ = loose_mock(request, spec=str, name="blob_2_") return blob_, blob_2_ @pytest.fixture def content_types_(self, request): content_type_ = loose_mock(request, spec=str, name="content_type_") content_type_2_ = loose_mock(request, spec=str, name="content_type_2_") return content_type_, content_type_2_ @pytest.fixture def from_xml(self, request): return method_mock(request, _ContentTypeMap, "from_xml", autospec=False) @pytest.fixture def _init_(self, request): return initializer_mock(request, PackageReader) @pytest.fixture def iter_sparts_fixture(self, sparts_, partnames_, content_types_, reltypes_, blobs_): pkg_reader = PackageReader(None, None, sparts_) expected_iter_spart_items = [ (partnames_[0], content_types_[0], reltypes_[0], blobs_[0]), (partnames_[1], content_types_[1], reltypes_[1], blobs_[1]), ] return pkg_reader, expected_iter_spart_items @pytest.fixture def _load_serialized_parts(self, request): return method_mock(request, PackageReader, "_load_serialized_parts", autospec=False) @pytest.fixture def partnames_(self, request): partname_ = loose_mock(request, spec=str, name="partname_") partname_2_ = loose_mock(request, spec=str, name="partname_2_") return partname_, partname_2_ @pytest.fixture def PhysPkgReader_(self): p = patch("docx.opc.pkgreader.PhysPkgReader", spec_set=_ZipPkgReader) yield p.start() p.stop() @pytest.fixture def reltypes_(self, request): reltype_ = instance_mock(request, str, name="reltype_") reltype_2_ = instance_mock(request, str, name="reltype_2") return reltype_, reltype_2_ @pytest.fixture def _SerializedPart_(self, request): return class_mock(request, "docx.opc.pkgreader._SerializedPart") @pytest.fixture def _SerializedRelationships_(self, request): return class_mock(request, "docx.opc.pkgreader._SerializedRelationships") @pytest.fixture def sparts_(self, request, partnames_, content_types_, reltypes_, blobs_): sparts_ = [] for idx in range(2): name = "spart_%s" % (("%d_" % (idx + 1)) if idx else "") spart_ = instance_mock( request, _SerializedPart, name=name, partname=partnames_[idx], content_type=content_types_[idx], reltype=reltypes_[idx], blob=blobs_[idx], ) sparts_.append(spart_) return sparts_ @pytest.fixture def _srels_for(self, request): return method_mock(request, PackageReader, "_srels_for", autospec=False) @pytest.fixture def _walk_phys_parts(self, request): return method_mock(request, PackageReader, "_walk_phys_parts", autospec=False)
DescribePackageReader
python
python__mypy
mypy/nodes.py
{ "start": 59335, "end": 59852 }
class ____(Statement): __slots__ = ("expr", "body", "else_body") __match_args__ = ("expr", "body", "else_body") expr: list[Expression] body: list[Block] else_body: Block | None def __init__(self, expr: list[Expression], body: list[Block], else_body: Block | None) -> None: super().__init__() self.expr = expr self.body = body self.else_body = else_body def accept(self, visitor: StatementVisitor[T]) -> T: return visitor.visit_if_stmt(self)
IfStmt
python
davidhalter__jedi
jedi/inference/filters.py
{ "start": 799, "end": 1180 }
class ____: _until_position = None def _filter(self, names): if self._until_position is not None: return [n for n in names if n.start_pos < self._until_position] return names @abstractmethod def get(self, name): raise NotImplementedError @abstractmethod def values(self): raise NotImplementedError
AbstractFilter
python
tensorflow__tensorflow
tensorflow/python/eager/benchmarks/resnet50/resnet50_graph_test.py
{ "start": 2168, "end": 4616 }
class ____(tf.test.Benchmark): def _report(self, label, start, num_iters, batch_size): avg_time = (time.time() - start) / num_iters dev = 'gpu' if tf.test.is_gpu_available() else 'cpu' name = 'graph_%s_%s_batch_%d_%s' % (label, dev, batch_size, data_format()) extras = {'examples_per_sec': batch_size / avg_time} self.report_benchmark( iters=num_iters, wall_time=avg_time, name=name, extras=extras) def benchmark_graph_apply(self): with tf.Graph().as_default(): images = tf.placeholder(tf.float32, image_shape(None)) model = resnet50.ResNet50(data_format()) predictions = model(images, training=False) init = tf.global_variables_initializer() batch_size = 64 with tf.Session() as sess: sess.run(init) np_images, _ = random_batch(batch_size) num_burn, num_iters = (3, 30) for _ in range(num_burn): sess.run(predictions, feed_dict={images: np_images}) start = time.time() for _ in range(num_iters): # Comparison with the eager execution benchmark in resnet50_test.py # isn't entirely fair as the time here includes the cost of copying # the feeds from CPU memory to GPU. sess.run(predictions, feed_dict={images: np_images}) self._report('apply', start, num_iters, batch_size) def benchmark_graph_train(self): for batch_size in [16, 32, 64]: with tf.Graph().as_default(): np_images, np_labels = random_batch(batch_size) dataset = tf.data.Dataset.from_tensors((np_images, np_labels)).repeat() images, labels = tf.data.make_one_shot_iterator( dataset).get_next() model = resnet50.ResNet50(data_format()) logits = model(images, training=True) loss = tf.compat.v1.losses.softmax_cross_entropy( logits=logits, onehot_labels=labels) optimizer = tf.train.GradientDescentOptimizer(learning_rate=1.0) train_op = optimizer.minimize(loss) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) (num_burn, num_iters) = (5, 10) for _ in range(num_burn): sess.run(train_op) start = time.time() for _ in range(num_iters): sess.run(train_op) self._report('train', start, num_iters, batch_size) if __name__ == '__main__': tf.test.main()
ResNet50Benchmarks
python
bokeh__bokeh
src/bokeh/document/events.py
{ "start": 4646, "end": 4748 }
class ____: def _columns_streamed(self, event: ColumnsStreamedEvent) -> None: ...
ColumnsStreamedMixin
python
walkccc__LeetCode
solutions/1670. Design Front Middle Back Queue/1670.py
{ "start": 0, "end": 1440 }
class ____: def __init__(self): self.frontQueue = collections.deque() self.backQueue = collections.deque() def pushFront(self, val: int) -> None: self.frontQueue.appendleft(val) self._moveFrontToBackIfNeeded() def pushMiddle(self, val: int) -> None: if len(self.frontQueue) == len(self.backQueue): self.backQueue.appendleft(val) else: self.frontQueue.append(val) def pushBack(self, val: int) -> None: self.backQueue.append(val) self._moveBackToFrontIfNeeded() def popFront(self) -> int: if self.frontQueue: x = self.frontQueue.popleft() self._moveBackToFrontIfNeeded() return x if self.backQueue: return self.backQueue.popleft() return -1 def popMiddle(self) -> int: if not self.frontQueue and not self.backQueue: return -1 if len(self.frontQueue) + 1 == len(self.backQueue): return self.backQueue.popleft() return self.frontQueue.pop() def popBack(self) -> int: if self.backQueue: x = self.backQueue.pop() self._moveFrontToBackIfNeeded() return x return -1 def _moveFrontToBackIfNeeded(self) -> None: if len(self.frontQueue) - 1 == len(self.backQueue): self.backQueue.appendleft(self.frontQueue.pop()) def _moveBackToFrontIfNeeded(self) -> None: if len(self.frontQueue) + 2 == len(self.backQueue): self.frontQueue.append(self.backQueue.popleft())
FrontMiddleBackQueue
python
RaRe-Technologies__gensim
gensim/models/phrases.py
{ "start": 7275, "end": 17014 }
class ____(interfaces.TransformationABC): """ Abstract base class for :class:`~gensim.models.phrases.Phrases` and :class:`~gensim.models.phrases.FrozenPhrases`. """ def __init__(self, connector_words): self.connector_words = frozenset(connector_words) def score_candidate(self, word_a, word_b, in_between): """Score a single phrase candidate. Returns ------- (str, float) 2-tuple of ``(delimiter-joined phrase, phrase score)`` for a phrase, or ``(None, None)`` if not a phrase. """ raise NotImplementedError("ABC: override this method in child classes") def analyze_sentence(self, sentence): """Analyze a sentence, concatenating any detected phrases into a single token. Parameters ---------- sentence : iterable of str Token sequence representing the sentence to be analyzed. Yields ------ (str, {float, None}) Iterate through the input sentence tokens and yield 2-tuples of: - ``(concatenated_phrase_tokens, score)`` for token sequences that form a phrase. - ``(word, None)`` if the token is not a part of a phrase. """ start_token, in_between = None, [] for word in sentence: if word not in self.connector_words: # The current word is a normal token, not a connector word, which means it's a potential # beginning (or end) of a phrase. if start_token: # We're inside a potential phrase, of which this word is the end. phrase, score = self.score_candidate(start_token, word, in_between) if score is not None: # Phrase detected! yield phrase, score start_token, in_between = None, [] else: # Not a phrase after all. Dissolve the candidate's constituent tokens as individual words. yield start_token, None for w in in_between: yield w, None start_token, in_between = word, [] # new potential phrase starts here else: # Not inside a phrase yet; start a new phrase candidate here. start_token, in_between = word, [] else: # We're a connector word. if start_token: # We're inside a potential phrase: add the connector word and keep growing the phrase. in_between.append(word) else: # Not inside a phrase: emit the connector word and move on. yield word, None # Emit any non-phrase tokens at the end. if start_token: yield start_token, None for w in in_between: yield w, None def __getitem__(self, sentence): """Convert the input sequence of tokens ``sentence`` into a sequence of tokens where adjacent tokens are replaced by a single token if they form a bigram collocation. If `sentence` is an entire corpus (iterable of sentences rather than a single sentence), return an iterable that converts each of the corpus' sentences into phrases on the fly, one after another. Parameters ---------- sentence : {list of str, iterable of list of str} Input sentence or a stream of sentences. Return ------ {list of str, iterable of list of str} Sentence with phrase tokens joined by ``self.delimiter``, if input was a single sentence. A generator of such sentences if input was a corpus. s """ is_single, sentence = _is_single(sentence) if not is_single: # If the input is an entire corpus (rather than a single sentence), # return an iterable stream. return self._apply(sentence) return [token for token, _ in self.analyze_sentence(sentence)] def find_phrases(self, sentences): """Get all unique phrases (multi-word expressions) that appear in ``sentences``, and their scores. Parameters ---------- sentences : iterable of list of str Text corpus. Returns ------- dict(str, float) Unique phrases found in ``sentences``, mapped to their scores. Example ------- .. sourcecode:: pycon >>> from gensim.test.utils import datapath >>> from gensim.models.word2vec import Text8Corpus >>> from gensim.models.phrases import Phrases, ENGLISH_CONNECTOR_WORDS >>> >>> sentences = Text8Corpus(datapath('testcorpus.txt')) >>> phrases = Phrases(sentences, min_count=1, threshold=0.1, connector_words=ENGLISH_CONNECTOR_WORDS) >>> >>> for phrase, score in phrases.find_phrases(sentences).items(): ... print(phrase, score) """ result = {} for sentence in sentences: for phrase, score in self.analyze_sentence(sentence): if score is not None: result[phrase] = score return result @classmethod def load(cls, *args, **kwargs): """Load a previously saved :class:`~gensim.models.phrases.Phrases` / :class:`~gensim.models.phrases.FrozenPhrases` model. Handles backwards compatibility from older versions which did not support pluggable scoring functions. Parameters ---------- args : object See :class:`~gensim.utils.SaveLoad.load`. kwargs : object See :class:`~gensim.utils.SaveLoad.load`. """ model = super(_PhrasesTransformation, cls).load(*args, **kwargs) # Upgrade FrozenPhrases try: phrasegrams = getattr(model, "phrasegrams", {}) component, score = next(iter(phrasegrams.items())) if isinstance(score, tuple): # Value in phrasegrams used to be a tuple; keep only the 2nd tuple component = score. model.phrasegrams = { str(model.delimiter.join(key), encoding='utf8'): val[1] for key, val in phrasegrams.items() } elif isinstance(component, tuple): # 3.8 => 4.0: phrasegram keys are strings, not tuples with bytestrings model.phrasegrams = { str(model.delimiter.join(key), encoding='utf8'): val for key, val in phrasegrams.items() } except StopIteration: # no phrasegrams, nothing to upgrade pass # If no scoring parameter, use default scoring. if not hasattr(model, 'scoring'): logger.warning('older version of %s loaded without scoring function', cls.__name__) logger.warning('setting pluggable scoring method to original_scorer for compatibility') model.scoring = original_scorer # If there is a scoring parameter, and it's a text value, load the proper scoring function. if hasattr(model, 'scoring'): if isinstance(model.scoring, str): if model.scoring == 'default': logger.warning('older version of %s loaded with "default" scoring parameter', cls.__name__) logger.warning('setting scoring method to original_scorer for compatibility') model.scoring = original_scorer elif model.scoring == 'npmi': logger.warning('older version of %s loaded with "npmi" scoring parameter', cls.__name__) logger.warning('setting scoring method to npmi_scorer for compatibility') model.scoring = npmi_scorer else: raise ValueError(f'failed to load {cls.__name__} model, unknown scoring "{model.scoring}"') # common_terms didn't exist pre-3.?, and was renamed to connector in 4.0.0. if not hasattr(model, "connector_words"): if hasattr(model, "common_terms"): model.connector_words = model.common_terms del model.common_terms else: logger.warning('loaded older version of %s, setting connector_words to an empty set', cls.__name__) model.connector_words = frozenset() if not hasattr(model, 'corpus_word_count'): logger.warning('older version of %s loaded without corpus_word_count', cls.__name__) logger.warning('setting corpus_word_count to 0, do not use it in your scoring function') model.corpus_word_count = 0 # Before 4.0.0, we stored strings as UTF8 bytes internally, to save RAM. Since 4.0.0, we use strings. if getattr(model, 'vocab', None): word = next(iter(model.vocab)) # get a random key – any key will do if not isinstance(word, str): logger.info("old version of %s loaded, upgrading %i words in memory", cls.__name__, len(model.vocab)) logger.info("re-save the loaded model to avoid this upgrade in the future") vocab = {} for key, value in model.vocab.items(): # needs lots of extra RAM temporarily! vocab[str(key, encoding='utf8')] = value model.vocab = vocab if not isinstance(model.delimiter, str): model.delimiter = str(model.delimiter, encoding='utf8') return model
_PhrasesTransformation
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_cond_format08.py
{ "start": 315, "end": 1316 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("cond_format08.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with conditional formatting.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() format1 = workbook.add_format( { "font_color": "#9C6500", "bg_color": "#FFEB9C", "font_condense": 1, "font_extend": 1, } ) worksheet.write("A1", 10) worksheet.write("A2", 20) worksheet.write("A3", 30) worksheet.write("A4", 40) worksheet.conditional_format( "A1", {"type": "cell", "format": format1, "criteria": "greater than", "value": 5}, ) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
kamyu104__LeetCode-Solutions
Python/restore-finishing-order.py
{ "start": 62, "end": 323 }
class ____(object): def recoverOrder(self, order, friends): """ :type order: List[int] :type friends: List[int] :rtype: List[int] """ lookup = set(friends) return [x for x in order if x in lookup]
Solution