code
stringlengths
1
25.8M
language
stringclasses
18 values
source
stringclasses
4 values
repo
stringclasses
78 values
path
stringlengths
0
268
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import print_function import filecmp import gyp.common import gyp.xcodeproj_file import gyp.xcode_ninja import errno import os import sys import posixpath import re import shutil import subprocess import tempfile # Project files generated by this module will use _intermediate_var as a # custom Xcode setting whose value is a DerivedSources-like directory that's # project-specific and configuration-specific. The normal choice, # DERIVED_FILE_DIR, is target-specific, which is thought to be too restrictive # as it is likely that multiple targets within a single project file will want # to access the same set of generated files. The other option, # PROJECT_DERIVED_FILE_DIR, is unsuitable because while it is project-specific, # it is not configuration-specific. INTERMEDIATE_DIR is defined as # $(PROJECT_DERIVED_FILE_DIR)/$(CONFIGURATION). _intermediate_var = 'INTERMEDIATE_DIR' # SHARED_INTERMEDIATE_DIR is the same, except that it is shared among all # targets that share the same BUILT_PRODUCTS_DIR. _shared_intermediate_var = 'SHARED_INTERMEDIATE_DIR' _library_search_paths_var = 'LIBRARY_SEARCH_PATHS' generator_default_variables = { 'EXECUTABLE_PREFIX': '', 'EXECUTABLE_SUFFIX': '', 'STATIC_LIB_PREFIX': 'lib', 'SHARED_LIB_PREFIX': 'lib', 'STATIC_LIB_SUFFIX': '.a', 'SHARED_LIB_SUFFIX': '.dylib', # INTERMEDIATE_DIR is a place for targets to build up intermediate products. # It is specific to each build environment. It is only guaranteed to exist # and be constant within the context of a project, corresponding to a single # input file. Some build environments may allow their intermediate directory # to be shared on a wider scale, but this is not guaranteed. 'INTERMEDIATE_DIR': '$(%s)' % _intermediate_var, 'OS': 'mac', 'PRODUCT_DIR': '$(BUILT_PRODUCTS_DIR)', 'LIB_DIR': '$(BUILT_PRODUCTS_DIR)', 'RULE_INPUT_ROOT': '$(INPUT_FILE_BASE)', 'RULE_INPUT_EXT': '$(INPUT_FILE_SUFFIX)', 'RULE_INPUT_NAME': '$(INPUT_FILE_NAME)', 'RULE_INPUT_PATH': '$(INPUT_FILE_PATH)', 'RULE_INPUT_DIRNAME': '$(INPUT_FILE_DIRNAME)', 'SHARED_INTERMEDIATE_DIR': '$(%s)' % _shared_intermediate_var, 'CONFIGURATION_NAME': '$(CONFIGURATION)', } # The Xcode-specific sections that hold paths. generator_additional_path_sections = [ 'mac_bundle_resources', 'mac_framework_headers', 'mac_framework_private_headers', # 'mac_framework_dirs', input already handles _dirs endings. ] # The Xcode-specific keys that exist on targets and aren't moved down to # configurations. generator_additional_non_configuration_keys = [ 'ios_app_extension', 'ios_watch_app', 'ios_watchkit_extension', 'mac_bundle', 'mac_bundle_resources', 'mac_framework_headers', 'mac_framework_private_headers', 'mac_xctest_bundle', 'mac_xcuitest_bundle', 'xcode_create_dependents_test_runner', ] # We want to let any rules apply to files that are resources also. generator_extra_sources_for_rules = [ 'mac_bundle_resources', 'mac_framework_headers', 'mac_framework_private_headers', ] generator_filelist_paths = None # Xcode's standard set of library directories, which don't need to be duplicated # in LIBRARY_SEARCH_PATHS. This list is not exhaustive, but that's okay. xcode_standard_library_dirs = frozenset([ '$(SDKROOT)/usr/lib', '$(SDKROOT)/usr/local/lib', ]) def CreateXCConfigurationList(configuration_names): xccl = gyp.xcodeproj_file.XCConfigurationList({'buildConfigurations': []}) if len(configuration_names) == 0: configuration_names = ['Default'] for configuration_name in configuration_names: xcbc = gyp.xcodeproj_file.XCBuildConfiguration({ 'name': configuration_name}) xccl.AppendProperty('buildConfigurations', xcbc) xccl.SetProperty('defaultConfigurationName', configuration_names[0]) return xccl class XcodeProject(object): def __init__(self, gyp_path, path, build_file_dict): self.gyp_path = gyp_path self.path = path self.project = gyp.xcodeproj_file.PBXProject(path=path) projectDirPath = gyp.common.RelativePath( os.path.dirname(os.path.abspath(self.gyp_path)), os.path.dirname(path) or '.') self.project.SetProperty('projectDirPath', projectDirPath) self.project_file = \ gyp.xcodeproj_file.XCProjectFile({'rootObject': self.project}) self.build_file_dict = build_file_dict # TODO(mark): add destructor that cleans up self.path if created_dir is # True and things didn't complete successfully. Or do something even # better with "try"? self.created_dir = False try: os.makedirs(self.path) self.created_dir = True except OSError as e: if e.errno != errno.EEXIST: raise def Finalize1(self, xcode_targets, serialize_all_tests): # Collect a list of all of the build configuration names used by the # various targets in the file. It is very heavily advised to keep each # target in an entire project (even across multiple project files) using # the same set of configuration names. configurations = [] for xct in self.project.GetProperty('targets'): xccl = xct.GetProperty('buildConfigurationList') xcbcs = xccl.GetProperty('buildConfigurations') for xcbc in xcbcs: name = xcbc.GetProperty('name') if name not in configurations: configurations.append(name) # Replace the XCConfigurationList attached to the PBXProject object with # a new one specifying all of the configuration names used by the various # targets. try: xccl = CreateXCConfigurationList(configurations) self.project.SetProperty('buildConfigurationList', xccl) except: sys.stderr.write("Problem with gyp file %s\n" % self.gyp_path) raise # The need for this setting is explained above where _intermediate_var is # defined. The comments below about wanting to avoid project-wide build # settings apply here too, but this needs to be set on a project-wide basis # so that files relative to the _intermediate_var setting can be displayed # properly in the Xcode UI. # # Note that for configuration-relative files such as anything relative to # _intermediate_var, for the purposes of UI tree view display, Xcode will # only resolve the configuration name once, when the project file is # opened. If the active build configuration is changed, the project file # must be closed and reopened if it is desired for the tree view to update. # This is filed as Apple radar 6588391. xccl.SetBuildSetting(_intermediate_var, '$(PROJECT_DERIVED_FILE_DIR)/$(CONFIGURATION)') xccl.SetBuildSetting(_shared_intermediate_var, '$(SYMROOT)/DerivedSources/$(CONFIGURATION)') # Set user-specified project-wide build settings and config files. This # is intended to be used very sparingly. Really, almost everything should # go into target-specific build settings sections. The project-wide # settings are only intended to be used in cases where Xcode attempts to # resolve variable references in a project context as opposed to a target # context, such as when resolving sourceTree references while building up # the tree tree view for UI display. # Any values set globally are applied to all configurations, then any # per-configuration values are applied. for xck, xcv in self.build_file_dict.get('xcode_settings', {}).items(): xccl.SetBuildSetting(xck, xcv) if 'xcode_config_file' in self.build_file_dict: config_ref = self.project.AddOrGetFileInRootGroup( self.build_file_dict['xcode_config_file']) xccl.SetBaseConfiguration(config_ref) build_file_configurations = self.build_file_dict.get('configurations', {}) if build_file_configurations: for config_name in configurations: build_file_configuration_named = \ build_file_configurations.get(config_name, {}) if build_file_configuration_named: xcc = xccl.ConfigurationNamed(config_name) for xck, xcv in build_file_configuration_named.get('xcode_settings', {}).items(): xcc.SetBuildSetting(xck, xcv) if 'xcode_config_file' in build_file_configuration_named: config_ref = self.project.AddOrGetFileInRootGroup( build_file_configurations[config_name]['xcode_config_file']) xcc.SetBaseConfiguration(config_ref) # Sort the targets based on how they appeared in the input. # TODO(mark): Like a lot of other things here, this assumes internal # knowledge of PBXProject - in this case, of its "targets" property. # ordinary_targets are ordinary targets that are already in the project # file. run_test_targets are the targets that run unittests and should be # used for the Run All Tests target. support_targets are the action/rule # targets used by GYP file targets, just kept for the assert check. ordinary_targets = [] run_test_targets = [] support_targets = [] # targets is full list of targets in the project. targets = [] # does the it define it's own "all"? has_custom_all = False # targets_for_all is the list of ordinary_targets that should be listed # in this project's "All" target. It includes each non_runtest_target # that does not have suppress_wildcard set. targets_for_all = [] for target in self.build_file_dict['targets']: target_name = target['target_name'] toolset = target['toolset'] qualified_target = gyp.common.QualifiedTarget(self.gyp_path, target_name, toolset) xcode_target = xcode_targets[qualified_target] # Make sure that the target being added to the sorted list is already in # the unsorted list. assert xcode_target in self.project._properties['targets'] targets.append(xcode_target) ordinary_targets.append(xcode_target) if xcode_target.support_target: support_targets.append(xcode_target.support_target) targets.append(xcode_target.support_target) if not int(target.get('suppress_wildcard', False)): targets_for_all.append(xcode_target) if target_name.lower() == 'all': has_custom_all = True; # If this target has a 'run_as' attribute, add its target to the # targets, and add it to the test targets. if target.get('run_as'): # Make a target to run something. It should have one # dependency, the parent xcode target. xccl = CreateXCConfigurationList(configurations) run_target = gyp.xcodeproj_file.PBXAggregateTarget({ 'name': 'Run ' + target_name, 'productName': xcode_target.GetProperty('productName'), 'buildConfigurationList': xccl, }, parent=self.project) run_target.AddDependency(xcode_target) command = target['run_as'] script = '' if command.get('working_directory'): script = script + 'cd "%s"\n' % \ gyp.xcodeproj_file.ConvertVariablesToShellSyntax( command.get('working_directory')) if command.get('environment'): script = script + "\n".join( ['export %s="%s"' % (key, gyp.xcodeproj_file.ConvertVariablesToShellSyntax(val)) for (key, val) in command.get('environment').items()]) + "\n" # Some test end up using sockets, files on disk, etc. and can get # confused if more then one test runs at a time. The generator # flag 'xcode_serialize_all_test_runs' controls the forcing of all # tests serially. It defaults to True. To get serial runs this # little bit of python does the same as the linux flock utility to # make sure only one runs at a time. command_prefix = '' if serialize_all_tests: command_prefix = \ """python -c "import fcntl, subprocess, sys file = open('$TMPDIR/GYP_serialize_test_runs', 'a') fcntl.flock(file.fileno(), fcntl.LOCK_EX) sys.exit(subprocess.call(sys.argv[1:]))" """ # If we were unable to exec for some reason, we want to exit # with an error, and fixup variable references to be shell # syntax instead of xcode syntax. script = script + 'exec ' + command_prefix + '%s\nexit 1\n' % \ gyp.xcodeproj_file.ConvertVariablesToShellSyntax( gyp.common.EncodePOSIXShellList(command.get('action'))) ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({ 'shellScript': script, 'showEnvVarsInLog': 0, }) run_target.AppendProperty('buildPhases', ssbp) # Add the run target to the project file. targets.append(run_target) run_test_targets.append(run_target) xcode_target.test_runner = run_target # Make sure that the list of targets being replaced is the same length as # the one replacing it, but allow for the added test runner targets. assert len(self.project._properties['targets']) == \ len(ordinary_targets) + len(support_targets) self.project._properties['targets'] = targets # Get rid of unnecessary levels of depth in groups like the Source group. self.project.RootGroupsTakeOverOnlyChildren(True) # Sort the groups nicely. Do this after sorting the targets, because the # Products group is sorted based on the order of the targets. self.project.SortGroups() # Create an "All" target if there's more than one target in this project # file and the project didn't define its own "All" target. Put a generated # "All" target first so that people opening up the project for the first # time will build everything by default. if len(targets_for_all) > 1 and not has_custom_all: xccl = CreateXCConfigurationList(configurations) all_target = gyp.xcodeproj_file.PBXAggregateTarget( { 'buildConfigurationList': xccl, 'name': 'All', }, parent=self.project) for target in targets_for_all: all_target.AddDependency(target) # TODO(mark): This is evil because it relies on internal knowledge of # PBXProject._properties. It's important to get the "All" target first, # though. self.project._properties['targets'].insert(0, all_target) # The same, but for run_test_targets. if len(run_test_targets) > 1: xccl = CreateXCConfigurationList(configurations) run_all_tests_target = gyp.xcodeproj_file.PBXAggregateTarget( { 'buildConfigurationList': xccl, 'name': 'Run All Tests', }, parent=self.project) for run_test_target in run_test_targets: run_all_tests_target.AddDependency(run_test_target) # Insert after the "All" target, which must exist if there is more than # one run_test_target. self.project._properties['targets'].insert(1, run_all_tests_target) def Finalize2(self, xcode_targets, xcode_target_to_target_dict): # Finalize2 needs to happen in a separate step because the process of # updating references to other projects depends on the ordering of targets # within remote project files. Finalize1 is responsible for sorting duty, # and once all project files are sorted, Finalize2 can come in and update # these references. # To support making a "test runner" target that will run all the tests # that are direct dependents of any given target, we look for # xcode_create_dependents_test_runner being set on an Aggregate target, # and generate a second target that will run the tests runners found under # the marked target. for bf_tgt in self.build_file_dict['targets']: if int(bf_tgt.get('xcode_create_dependents_test_runner', 0)): tgt_name = bf_tgt['target_name'] toolset = bf_tgt['toolset'] qualified_target = gyp.common.QualifiedTarget(self.gyp_path, tgt_name, toolset) xcode_target = xcode_targets[qualified_target] if isinstance(xcode_target, gyp.xcodeproj_file.PBXAggregateTarget): # Collect all the run test targets. all_run_tests = [] pbxtds = xcode_target.GetProperty('dependencies') for pbxtd in pbxtds: pbxcip = pbxtd.GetProperty('targetProxy') dependency_xct = pbxcip.GetProperty('remoteGlobalIDString') if hasattr(dependency_xct, 'test_runner'): all_run_tests.append(dependency_xct.test_runner) # Directly depend on all the runners as they depend on the target # that builds them. if len(all_run_tests) > 0: run_all_target = gyp.xcodeproj_file.PBXAggregateTarget({ 'name': 'Run %s Tests' % tgt_name, 'productName': tgt_name, }, parent=self.project) for run_test_target in all_run_tests: run_all_target.AddDependency(run_test_target) # Insert the test runner after the related target. idx = self.project._properties['targets'].index(xcode_target) self.project._properties['targets'].insert(idx + 1, run_all_target) # Update all references to other projects, to make sure that the lists of # remote products are complete. Otherwise, Xcode will fill them in when # it opens the project file, which will result in unnecessary diffs. # TODO(mark): This is evil because it relies on internal knowledge of # PBXProject._other_pbxprojects. for other_pbxproject in self.project._other_pbxprojects.keys(): self.project.AddOrGetProjectReference(other_pbxproject) self.project.SortRemoteProductReferences() # Give everything an ID. self.project_file.ComputeIDs() # Make sure that no two objects in the project file have the same ID. If # multiple objects wind up with the same ID, upon loading the file, Xcode # will only recognize one object (the last one in the file?) and the # results are unpredictable. self.project_file.EnsureNoIDCollisions() def Write(self): # Write the project file to a temporary location first. Xcode watches for # changes to the project file and presents a UI sheet offering to reload # the project when it does change. However, in some cases, especially when # multiple projects are open or when Xcode is busy, things don't work so # seamlessly. Sometimes, Xcode is able to detect that a project file has # changed but can't unload it because something else is referencing it. # To mitigate this problem, and to avoid even having Xcode present the UI # sheet when an open project is rewritten for inconsequential changes, the # project file is written to a temporary file in the xcodeproj directory # first. The new temporary file is then compared to the existing project # file, if any. If they differ, the new file replaces the old; otherwise, # the new project file is simply deleted. Xcode properly detects a file # being renamed over an open project file as a change and so it remains # able to present the "project file changed" sheet under this system. # Writing to a temporary file first also avoids the possible problem of # Xcode rereading an incomplete project file. (output_fd, new_pbxproj_path) = \ tempfile.mkstemp(suffix='.tmp', prefix='project.pbxproj.gyp.', dir=self.path) try: output_file = os.fdopen(output_fd, 'w') self.project_file.Print(output_file) output_file.close() pbxproj_path = os.path.join(self.path, 'project.pbxproj') same = False try: same = filecmp.cmp(pbxproj_path, new_pbxproj_path, False) except OSError as e: if e.errno != errno.ENOENT: raise if same: # The new file is identical to the old one, just get rid of the new # one. os.unlink(new_pbxproj_path) else: # The new file is different from the old one, or there is no old one. # Rename the new file to the permanent name. # # tempfile.mkstemp uses an overly restrictive mode, resulting in a # file that can only be read by the owner, regardless of the umask. # There's no reason to not respect the umask here, which means that # an extra hoop is required to fetch it and reset the new file's mode. # # No way to get the umask without setting a new one? Set a safe one # and then set it back to the old value. umask = os.umask(0o77) os.umask(umask) os.chmod(new_pbxproj_path, 0o666 & ~umask) os.rename(new_pbxproj_path, pbxproj_path) except Exception: # Don't leave turds behind. In fact, if this code was responsible for # creating the xcodeproj directory, get rid of that too. os.unlink(new_pbxproj_path) if self.created_dir: shutil.rmtree(self.path, True) raise def AddSourceToTarget(source, type, pbxp, xct): # TODO(mark): Perhaps source_extensions and library_extensions can be made a # little bit fancier. source_extensions = ['c', 'cc', 'cpp', 'cxx', 'm', 'mm', 's', 'swift'] # .o is conceptually more of a "source" than a "library," but Xcode thinks # of "sources" as things to compile and "libraries" (or "frameworks") as # things to link with. Adding an object file to an Xcode target's frameworks # phase works properly. library_extensions = ['a', 'dylib', 'framework', 'o'] basename = posixpath.basename(source) (root, ext) = posixpath.splitext(basename) if ext: ext = ext[1:].lower() if ext in source_extensions and type != 'none': xct.SourcesPhase().AddFile(source) elif ext in library_extensions and type != 'none': xct.FrameworksPhase().AddFile(source) else: # Files that aren't added to a sources or frameworks build phase can still # go into the project file, just not as part of a build phase. pbxp.AddOrGetFileInRootGroup(source) def AddResourceToTarget(resource, pbxp, xct): # TODO(mark): Combine with AddSourceToTarget above? Or just inline this call # where it's used. xct.ResourcesPhase().AddFile(resource) def AddHeaderToTarget(header, pbxp, xct, is_public): # TODO(mark): Combine with AddSourceToTarget above? Or just inline this call # where it's used. settings = '{ATTRIBUTES = (%s, ); }' % ('Private', 'Public')[is_public] xct.HeadersPhase().AddFile(header, settings) _xcode_variable_re = re.compile(r'(\$\((.*?)\))') def ExpandXcodeVariables(string, expansions): """Expands Xcode-style $(VARIABLES) in string per the expansions dict. In some rare cases, it is appropriate to expand Xcode variables when a project file is generated. For any substring $(VAR) in string, if VAR is a key in the expansions dict, $(VAR) will be replaced with expansions[VAR]. Any $(VAR) substring in string for which VAR is not a key in the expansions dict will remain in the returned string. """ matches = _xcode_variable_re.findall(string) if matches == None: return string matches.reverse() for match in matches: (to_replace, variable) = match if not variable in expansions: continue replacement = expansions[variable] string = re.sub(re.escape(to_replace), replacement, string) return string _xcode_define_re = re.compile(r'([\\\"\' ])') def EscapeXcodeDefine(s): """We must escape the defines that we give to XCode so that it knows not to split on spaces and to respect backslash and quote literals. However, we must not quote the define, or Xcode will incorrectly intepret variables especially $(inherited).""" return re.sub(_xcode_define_re, r'\\\1', s) def PerformBuild(data, configurations, params): options = params['options'] for build_file, build_file_dict in data.items(): (build_file_root, build_file_ext) = os.path.splitext(build_file) if build_file_ext != '.gyp': continue xcodeproj_path = build_file_root + options.suffix + '.xcodeproj' if options.generator_output: xcodeproj_path = os.path.join(options.generator_output, xcodeproj_path) for config in configurations: arguments = ['xcodebuild', '-project', xcodeproj_path] arguments += ['-configuration', config] print("Building [%s]: %s" % (config, arguments)) subprocess.check_call(arguments) def CalculateGeneratorInputInfo(params): toplevel = params['options'].toplevel_dir if params.get('flavor') == 'ninja': generator_dir = os.path.relpath(params['options'].generator_output or '.') output_dir = params.get('generator_flags', {}).get('output_dir', 'out') output_dir = os.path.normpath(os.path.join(generator_dir, output_dir)) qualified_out_dir = os.path.normpath(os.path.join( toplevel, output_dir, 'gypfiles-xcode-ninja')) else: output_dir = os.path.normpath(os.path.join(toplevel, 'xcodebuild')) qualified_out_dir = os.path.normpath(os.path.join( toplevel, output_dir, 'gypfiles')) global generator_filelist_paths generator_filelist_paths = { 'toplevel': toplevel, 'qualified_out_dir': qualified_out_dir, } def GenerateOutput(target_list, target_dicts, data, params): # Optionally configure each spec to use ninja as the external builder. ninja_wrapper = params.get('flavor') == 'ninja' if ninja_wrapper: (target_list, target_dicts, data) = \ gyp.xcode_ninja.CreateWrapper(target_list, target_dicts, data, params) options = params['options'] generator_flags = params.get('generator_flags', {}) parallel_builds = generator_flags.get('xcode_parallel_builds', True) serialize_all_tests = \ generator_flags.get('xcode_serialize_all_test_runs', True) upgrade_check_project_version = \ generator_flags.get('xcode_upgrade_check_project_version', None) # Format upgrade_check_project_version with leading zeros as needed. if upgrade_check_project_version: upgrade_check_project_version = str(upgrade_check_project_version) while len(upgrade_check_project_version) < 4: upgrade_check_project_version = '0' + upgrade_check_project_version skip_excluded_files = \ not generator_flags.get('xcode_list_excluded_files', True) xcode_projects = {} for build_file, build_file_dict in data.items(): (build_file_root, build_file_ext) = os.path.splitext(build_file) if build_file_ext != '.gyp': continue xcodeproj_path = build_file_root + options.suffix + '.xcodeproj' if options.generator_output: xcodeproj_path = os.path.join(options.generator_output, xcodeproj_path) xcp = XcodeProject(build_file, xcodeproj_path, build_file_dict) xcode_projects[build_file] = xcp pbxp = xcp.project # Set project-level attributes from multiple options project_attributes = {}; if parallel_builds: project_attributes['BuildIndependentTargetsInParallel'] = 'YES' if upgrade_check_project_version: project_attributes['LastUpgradeCheck'] = upgrade_check_project_version project_attributes['LastTestingUpgradeCheck'] = \ upgrade_check_project_version project_attributes['LastSwiftUpdateCheck'] = \ upgrade_check_project_version pbxp.SetProperty('attributes', project_attributes) # Add gyp/gypi files to project if not generator_flags.get('standalone'): main_group = pbxp.GetProperty('mainGroup') build_group = gyp.xcodeproj_file.PBXGroup({'name': 'Build'}) main_group.AppendChild(build_group) for included_file in build_file_dict['included_files']: build_group.AddOrGetFileByPath(included_file, False) xcode_targets = {} xcode_target_to_target_dict = {} for qualified_target in target_list: [build_file, target_name, toolset] = \ gyp.common.ParseQualifiedTarget(qualified_target) spec = target_dicts[qualified_target] if spec['toolset'] != 'target': raise Exception( 'Multiple toolsets not supported in xcode build (target %s)' % qualified_target) configuration_names = [spec['default_configuration']] for configuration_name in sorted(spec['configurations'].keys()): if configuration_name not in configuration_names: configuration_names.append(configuration_name) xcp = xcode_projects[build_file] pbxp = xcp.project # Set up the configurations for the target according to the list of names # supplied. xccl = CreateXCConfigurationList(configuration_names) # Create an XCTarget subclass object for the target. The type with # "+bundle" appended will be used if the target has "mac_bundle" set. # loadable_modules not in a mac_bundle are mapped to # com.googlecode.gyp.xcode.bundle, a pseudo-type that xcode.py interprets # to create a single-file mh_bundle. _types = { 'executable': 'com.apple.product-type.tool', 'loadable_module': 'com.googlecode.gyp.xcode.bundle', 'shared_library': 'com.apple.product-type.library.dynamic', 'static_library': 'com.apple.product-type.library.static', 'mac_kernel_extension': 'com.apple.product-type.kernel-extension', 'executable+bundle': 'com.apple.product-type.application', 'loadable_module+bundle': 'com.apple.product-type.bundle', 'loadable_module+xctest': 'com.apple.product-type.bundle.unit-test', 'loadable_module+xcuitest': 'com.apple.product-type.bundle.ui-testing', 'shared_library+bundle': 'com.apple.product-type.framework', 'executable+extension+bundle': 'com.apple.product-type.app-extension', 'executable+watch+extension+bundle': 'com.apple.product-type.watchkit-extension', 'executable+watch+bundle': 'com.apple.product-type.application.watchapp', 'mac_kernel_extension+bundle': 'com.apple.product-type.kernel-extension', } target_properties = { 'buildConfigurationList': xccl, 'name': target_name, } type = spec['type'] is_xctest = int(spec.get('mac_xctest_bundle', 0)) is_xcuitest = int(spec.get('mac_xcuitest_bundle', 0)) is_bundle = int(spec.get('mac_bundle', 0)) or is_xctest or is_xcuitest is_app_extension = int(spec.get('ios_app_extension', 0)) is_watchkit_extension = int(spec.get('ios_watchkit_extension', 0)) is_watch_app = int(spec.get('ios_watch_app', 0)) if type != 'none': type_bundle_key = type if is_xcuitest: type_bundle_key += '+xcuitest' assert type == 'loadable_module', ( 'mac_xcuitest_bundle targets must have type loadable_module ' '(target %s)' % target_name) elif is_xctest: type_bundle_key += '+xctest' assert type == 'loadable_module', ( 'mac_xctest_bundle targets must have type loadable_module ' '(target %s)' % target_name) elif is_app_extension: assert is_bundle, ('ios_app_extension flag requires mac_bundle ' '(target %s)' % target_name) type_bundle_key += '+extension+bundle' elif is_watchkit_extension: assert is_bundle, ('ios_watchkit_extension flag requires mac_bundle ' '(target %s)' % target_name) type_bundle_key += '+watch+extension+bundle' elif is_watch_app: assert is_bundle, ('ios_watch_app flag requires mac_bundle ' '(target %s)' % target_name) type_bundle_key += '+watch+bundle' elif is_bundle: type_bundle_key += '+bundle' xctarget_type = gyp.xcodeproj_file.PBXNativeTarget try: target_properties['productType'] = _types[type_bundle_key] except KeyError as e: gyp.common.ExceptionAppend(e, "-- unknown product type while " "writing target %s" % target_name) raise else: xctarget_type = gyp.xcodeproj_file.PBXAggregateTarget assert not is_bundle, ( 'mac_bundle targets cannot have type none (target "%s")' % target_name) assert not is_xcuitest, ( 'mac_xcuitest_bundle targets cannot have type none (target "%s")' % target_name) assert not is_xctest, ( 'mac_xctest_bundle targets cannot have type none (target "%s")' % target_name) target_product_name = spec.get('product_name') if target_product_name is not None: target_properties['productName'] = target_product_name xct = xctarget_type(target_properties, parent=pbxp, force_outdir=spec.get('product_dir'), force_prefix=spec.get('product_prefix'), force_extension=spec.get('product_extension')) pbxp.AppendProperty('targets', xct) xcode_targets[qualified_target] = xct xcode_target_to_target_dict[xct] = spec spec_actions = spec.get('actions', []) spec_rules = spec.get('rules', []) # Xcode has some "issues" with checking dependencies for the "Compile # sources" step with any source files/headers generated by actions/rules. # To work around this, if a target is building anything directly (not # type "none"), then a second target is used to run the GYP actions/rules # and is made a dependency of this target. This way the work is done # before the dependency checks for what should be recompiled. support_xct = None # The Xcode "issues" don't affect xcode-ninja builds, since the dependency # logic all happens in ninja. Don't bother creating the extra targets in # that case. if type != 'none' and (spec_actions or spec_rules) and not ninja_wrapper: support_xccl = CreateXCConfigurationList(configuration_names); support_target_suffix = generator_flags.get( 'support_target_suffix', ' Support') support_target_properties = { 'buildConfigurationList': support_xccl, 'name': target_name + support_target_suffix, } if target_product_name: support_target_properties['productName'] = \ target_product_name + ' Support' support_xct = \ gyp.xcodeproj_file.PBXAggregateTarget(support_target_properties, parent=pbxp) pbxp.AppendProperty('targets', support_xct) xct.AddDependency(support_xct) # Hang the support target off the main target so it can be tested/found # by the generator during Finalize. xct.support_target = support_xct prebuild_index = 0 # Add custom shell script phases for "actions" sections. for action in spec_actions: # There's no need to write anything into the script to ensure that the # output directories already exist, because Xcode will look at the # declared outputs and automatically ensure that they exist for us. # Do we have a message to print when this action runs? message = action.get('message') if message: message = 'echo note: ' + gyp.common.EncodePOSIXShellArgument(message) else: message = '' # Turn the list into a string that can be passed to a shell. action_string = gyp.common.EncodePOSIXShellList(action['action']) # Convert Xcode-type variable references to sh-compatible environment # variable references. message_sh = gyp.xcodeproj_file.ConvertVariablesToShellSyntax(message) action_string_sh = gyp.xcodeproj_file.ConvertVariablesToShellSyntax( action_string) script = '' # Include the optional message if message_sh: script += message_sh + '\n' # Be sure the script runs in exec, and that if exec fails, the script # exits signalling an error. script += 'exec ' + action_string_sh + '\nexit 1\n' ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({ 'inputPaths': action['inputs'], 'name': 'Action "' + action['action_name'] + '"', 'outputPaths': action['outputs'], 'shellScript': script, 'showEnvVarsInLog': 0, }) if support_xct: support_xct.AppendProperty('buildPhases', ssbp) else: # TODO(mark): this assumes too much knowledge of the internals of # xcodeproj_file; some of these smarts should move into xcodeproj_file # itself. xct._properties['buildPhases'].insert(prebuild_index, ssbp) prebuild_index = prebuild_index + 1 # TODO(mark): Should verify that at most one of these is specified. if int(action.get('process_outputs_as_sources', False)): for output in action['outputs']: AddSourceToTarget(output, type, pbxp, xct) if int(action.get('process_outputs_as_mac_bundle_resources', False)): for output in action['outputs']: AddResourceToTarget(output, pbxp, xct) # tgt_mac_bundle_resources holds the list of bundle resources so # the rule processing can check against it. if is_bundle: tgt_mac_bundle_resources = spec.get('mac_bundle_resources', []) else: tgt_mac_bundle_resources = [] # Add custom shell script phases driving "make" for "rules" sections. # # Xcode's built-in rule support is almost powerful enough to use directly, # but there are a few significant deficiencies that render them unusable. # There are workarounds for some of its inadequacies, but in aggregate, # the workarounds added complexity to the generator, and some workarounds # actually require input files to be crafted more carefully than I'd like. # Consequently, until Xcode rules are made more capable, "rules" input # sections will be handled in Xcode output by shell script build phases # performed prior to the compilation phase. # # The following problems with Xcode rules were found. The numbers are # Apple radar IDs. I hope that these shortcomings are addressed, I really # liked having the rules handled directly in Xcode during the period that # I was prototyping this. # # 6588600 Xcode compiles custom script rule outputs too soon, compilation # fails. This occurs when rule outputs from distinct inputs are # interdependent. The only workaround is to put rules and their # inputs in a separate target from the one that compiles the rule # outputs. This requires input file cooperation and it means that # process_outputs_as_sources is unusable. # 6584932 Need to declare that custom rule outputs should be excluded from # compilation. A possible workaround is to lie to Xcode about a # rule's output, giving it a dummy file it doesn't know how to # compile. The rule action script would need to touch the dummy. # 6584839 I need a way to declare additional inputs to a custom rule. # A possible workaround is a shell script phase prior to # compilation that touches a rule's primary input files if any # would-be additional inputs are newer than the output. Modifying # the source tree - even just modification times - feels dirty. # 6564240 Xcode "custom script" build rules always dump all environment # variables. This is a low-prioroty problem and is not a # show-stopper. rules_by_ext = {} for rule in spec_rules: rules_by_ext[rule['extension']] = rule # First, some definitions: # # A "rule source" is a file that was listed in a target's "sources" # list and will have a rule applied to it on the basis of matching the # rule's "extensions" attribute. Rule sources are direct inputs to # rules. # # Rule definitions may specify additional inputs in their "inputs" # attribute. These additional inputs are used for dependency tracking # purposes. # # A "concrete output" is a rule output with input-dependent variables # resolved. For example, given a rule with: # 'extension': 'ext', 'outputs': ['$(INPUT_FILE_BASE).cc'], # if the target's "sources" list contained "one.ext" and "two.ext", # the "concrete output" for rule input "two.ext" would be "two.cc". If # a rule specifies multiple outputs, each input file that the rule is # applied to will have the same number of concrete outputs. # # If any concrete outputs are outdated or missing relative to their # corresponding rule_source or to any specified additional input, the # rule action must be performed to generate the concrete outputs. # concrete_outputs_by_rule_source will have an item at the same index # as the rule['rule_sources'] that it corresponds to. Each item is a # list of all of the concrete outputs for the rule_source. concrete_outputs_by_rule_source = [] # concrete_outputs_all is a flat list of all concrete outputs that this # rule is able to produce, given the known set of input files # (rule_sources) that apply to it. concrete_outputs_all = [] # messages & actions are keyed by the same indices as rule['rule_sources'] # and concrete_outputs_by_rule_source. They contain the message and # action to perform after resolving input-dependent variables. The # message is optional, in which case None is stored for each rule source. messages = [] actions = [] for rule_source in rule.get('rule_sources', []): rule_source_dirname, rule_source_basename = \ posixpath.split(rule_source) (rule_source_root, rule_source_ext) = \ posixpath.splitext(rule_source_basename) # These are the same variable names that Xcode uses for its own native # rule support. Because Xcode's rule engine is not being used, they # need to be expanded as they are written to the makefile. rule_input_dict = { 'INPUT_FILE_BASE': rule_source_root, 'INPUT_FILE_SUFFIX': rule_source_ext, 'INPUT_FILE_NAME': rule_source_basename, 'INPUT_FILE_PATH': rule_source, 'INPUT_FILE_DIRNAME': rule_source_dirname, } concrete_outputs_for_this_rule_source = [] for output in rule.get('outputs', []): # Fortunately, Xcode and make both use $(VAR) format for their # variables, so the expansion is the only transformation necessary. # Any remaning $(VAR)-type variables in the string can be given # directly to make, which will pick up the correct settings from # what Xcode puts into the environment. concrete_output = ExpandXcodeVariables(output, rule_input_dict) concrete_outputs_for_this_rule_source.append(concrete_output) # Add all concrete outputs to the project. pbxp.AddOrGetFileInRootGroup(concrete_output) concrete_outputs_by_rule_source.append( \ concrete_outputs_for_this_rule_source) concrete_outputs_all.extend(concrete_outputs_for_this_rule_source) # TODO(mark): Should verify that at most one of these is specified. if int(rule.get('process_outputs_as_sources', False)): for output in concrete_outputs_for_this_rule_source: AddSourceToTarget(output, type, pbxp, xct) # If the file came from the mac_bundle_resources list or if the rule # is marked to process outputs as bundle resource, do so. was_mac_bundle_resource = rule_source in tgt_mac_bundle_resources if was_mac_bundle_resource or \ int(rule.get('process_outputs_as_mac_bundle_resources', False)): for output in concrete_outputs_for_this_rule_source: AddResourceToTarget(output, pbxp, xct) # Do we have a message to print when this rule runs? message = rule.get('message') if message: message = gyp.common.EncodePOSIXShellArgument(message) message = ExpandXcodeVariables(message, rule_input_dict) messages.append(message) # Turn the list into a string that can be passed to a shell. action_string = gyp.common.EncodePOSIXShellList(rule['action']) action = ExpandXcodeVariables(action_string, rule_input_dict) actions.append(action) if len(concrete_outputs_all) > 0: # TODO(mark): There's a possibilty for collision here. Consider # target "t" rule "A_r" and target "t_A" rule "r". makefile_name = '%s.make' % re.sub( '[^a-zA-Z0-9_]', '_' , '%s_%s' % (target_name, rule['rule_name'])) makefile_path = os.path.join(xcode_projects[build_file].path, makefile_name) # TODO(mark): try/close? Write to a temporary file and swap it only # if it's got changes? makefile = open(makefile_path, 'w') # make will build the first target in the makefile by default. By # convention, it's called "all". List all (or at least one) # concrete output for each rule source as a prerequisite of the "all" # target. makefile.write('all: \\\n') for concrete_output_index, concrete_output_by_rule_source in \ enumerate(concrete_outputs_by_rule_source): # Only list the first (index [0]) concrete output of each input # in the "all" target. Otherwise, a parallel make (-j > 1) would # attempt to process each input multiple times simultaneously. # Otherwise, "all" could just contain the entire list of # concrete_outputs_all. concrete_output = concrete_output_by_rule_source[0] if concrete_output_index == len(concrete_outputs_by_rule_source) - 1: eol = '' else: eol = ' \\' makefile.write(' %s%s\n' % (concrete_output, eol)) for (rule_source, concrete_outputs, message, action) in \ zip(rule['rule_sources'], concrete_outputs_by_rule_source, messages, actions): makefile.write('\n') # Add a rule that declares it can build each concrete output of a # rule source. Collect the names of the directories that are # required. concrete_output_dirs = [] for concrete_output_index, concrete_output in \ enumerate(concrete_outputs): if concrete_output_index == 0: bol = '' else: bol = ' ' makefile.write('%s%s \\\n' % (bol, concrete_output)) concrete_output_dir = posixpath.dirname(concrete_output) if (concrete_output_dir and concrete_output_dir not in concrete_output_dirs): concrete_output_dirs.append(concrete_output_dir) makefile.write(' : \\\n') # The prerequisites for this rule are the rule source itself and # the set of additional rule inputs, if any. prerequisites = [rule_source] prerequisites.extend(rule.get('inputs', [])) for prerequisite_index, prerequisite in enumerate(prerequisites): if prerequisite_index == len(prerequisites) - 1: eol = '' else: eol = ' \\' makefile.write(' %s%s\n' % (prerequisite, eol)) # Make sure that output directories exist before executing the rule # action. if len(concrete_output_dirs) > 0: makefile.write('\t@mkdir -p "%s"\n' % '" "'.join(concrete_output_dirs)) # The rule message and action have already had the necessary variable # substitutions performed. if message: # Mark it with note: so Xcode picks it up in build output. makefile.write('\t@echo note: %s\n' % message) makefile.write('\t%s\n' % action) makefile.close() # It might be nice to ensure that needed output directories exist # here rather than in each target in the Makefile, but that wouldn't # work if there ever was a concrete output that had an input-dependent # variable anywhere other than in the leaf position. # To help speed things up, pass -j COUNT to make so it does some work # in parallel. Don't use ncpus because Xcode will build ncpus targets # in parallel and if each target happens to have a rules step, there # would be ncpus^2 things going. With a machine that has 2 quad-core # Xeons, a build can quickly run out of processes based on # scheduling/other tasks, and randomly failing builds are no good. script = \ """JOB_COUNT="$(/usr/sbin/sysctl -n hw.ncpu)" if [ "${JOB_COUNT}" -gt 4 ]; then JOB_COUNT=4 fi exec xcrun make -f "${PROJECT_FILE_PATH}/%s" -j "${JOB_COUNT}" exit 1 """ % makefile_name ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({ 'inputPaths': rule['rule_sources'], 'name': 'Rule "' + rule['rule_name'] + '"', 'outputPaths': concrete_outputs_all, 'shellScript': script, 'showEnvVarsInLog': 0, }) if support_xct: support_xct.AppendProperty('buildPhases', ssbp) else: # TODO(mark): this assumes too much knowledge of the internals of # xcodeproj_file; some of these smarts should move into xcodeproj_file # itself. xct._properties['buildPhases'].insert(prebuild_index, ssbp) prebuild_index = prebuild_index + 1 # Extra rule inputs also go into the project file. Concrete outputs were # already added when they were computed. groups = ['inputs', 'inputs_excluded'] if skip_excluded_files: groups = [x for x in groups if not x.endswith('_excluded')] for group in groups: for item in rule.get(group, []): pbxp.AddOrGetFileInRootGroup(item) # Add "sources". for source in spec.get('sources', []): (source_root, source_extension) = posixpath.splitext(source) if source_extension[1:] not in rules_by_ext: # AddSourceToTarget will add the file to a root group if it's not # already there. AddSourceToTarget(source, type, pbxp, xct) else: pbxp.AddOrGetFileInRootGroup(source) # Add "mac_bundle_resources" and "mac_framework_private_headers" if # it's a bundle of any type. if is_bundle: for resource in tgt_mac_bundle_resources: (resource_root, resource_extension) = posixpath.splitext(resource) if resource_extension[1:] not in rules_by_ext: AddResourceToTarget(resource, pbxp, xct) else: pbxp.AddOrGetFileInRootGroup(resource) for header in spec.get('mac_framework_private_headers', []): AddHeaderToTarget(header, pbxp, xct, False) # Add "mac_framework_headers". These can be valid for both frameworks # and static libraries. if is_bundle or type == 'static_library': for header in spec.get('mac_framework_headers', []): AddHeaderToTarget(header, pbxp, xct, True) # Add "copies". pbxcp_dict = {} for copy_group in spec.get('copies', []): dest = copy_group['destination'] if dest[0] not in ('/', '$'): # Relative paths are relative to $(SRCROOT). dest = '$(SRCROOT)/' + dest code_sign = int(copy_group.get('xcode_code_sign', 0)) settings = (None, '{ATTRIBUTES = (CodeSignOnCopy, ); }')[code_sign]; # Coalesce multiple "copies" sections in the same target with the same # "destination" property into the same PBXCopyFilesBuildPhase, otherwise # they'll wind up with ID collisions. pbxcp = pbxcp_dict.get(dest, None) if pbxcp is None: pbxcp = gyp.xcodeproj_file.PBXCopyFilesBuildPhase({ 'name': 'Copy to ' + copy_group['destination'] }, parent=xct) pbxcp.SetDestination(dest) # TODO(mark): The usual comment about this knowing too much about # gyp.xcodeproj_file internals applies. xct._properties['buildPhases'].insert(prebuild_index, pbxcp) pbxcp_dict[dest] = pbxcp for file in copy_group['files']: pbxcp.AddFile(file, settings) # Excluded files can also go into the project file. if not skip_excluded_files: for key in ['sources', 'mac_bundle_resources', 'mac_framework_headers', 'mac_framework_private_headers']: excluded_key = key + '_excluded' for item in spec.get(excluded_key, []): pbxp.AddOrGetFileInRootGroup(item) # So can "inputs" and "outputs" sections of "actions" groups. groups = ['inputs', 'inputs_excluded', 'outputs', 'outputs_excluded'] if skip_excluded_files: groups = [x for x in groups if not x.endswith('_excluded')] for action in spec.get('actions', []): for group in groups: for item in action.get(group, []): # Exclude anything in BUILT_PRODUCTS_DIR. They're products, not # sources. if not item.startswith('$(BUILT_PRODUCTS_DIR)/'): pbxp.AddOrGetFileInRootGroup(item) for postbuild in spec.get('postbuilds', []): action_string_sh = gyp.common.EncodePOSIXShellList(postbuild['action']) script = 'exec ' + action_string_sh + '\nexit 1\n' # Make the postbuild step depend on the output of ld or ar from this # target. Apparently putting the script step after the link step isn't # sufficient to ensure proper ordering in all cases. With an input # declared but no outputs, the script step should run every time, as # desired. ssbp = gyp.xcodeproj_file.PBXShellScriptBuildPhase({ 'inputPaths': ['$(BUILT_PRODUCTS_DIR)/$(EXECUTABLE_PATH)'], 'name': 'Postbuild "' + postbuild['postbuild_name'] + '"', 'shellScript': script, 'showEnvVarsInLog': 0, }) xct.AppendProperty('buildPhases', ssbp) # Add dependencies before libraries, because adding a dependency may imply # adding a library. It's preferable to keep dependencies listed first # during a link phase so that they can override symbols that would # otherwise be provided by libraries, which will usually include system # libraries. On some systems, ld is finicky and even requires the # libraries to be ordered in such a way that unresolved symbols in # earlier-listed libraries may only be resolved by later-listed libraries. # The Mac linker doesn't work that way, but other platforms do, and so # their linker invocations need to be constructed in this way. There's # no compelling reason for Xcode's linker invocations to differ. if 'dependencies' in spec: for dependency in spec['dependencies']: xct.AddDependency(xcode_targets[dependency]) # The support project also gets the dependencies (in case they are # needed for the actions/rules to work). if support_xct: support_xct.AddDependency(xcode_targets[dependency]) if 'libraries' in spec: for library in spec['libraries']: xct.FrameworksPhase().AddFile(library) # Add the library's directory to LIBRARY_SEARCH_PATHS if necessary. # I wish Xcode handled this automatically. library_dir = posixpath.dirname(library) if library_dir not in xcode_standard_library_dirs and ( not xct.HasBuildSetting(_library_search_paths_var) or library_dir not in xct.GetBuildSetting(_library_search_paths_var)): xct.AppendBuildSetting(_library_search_paths_var, library_dir) for configuration_name in configuration_names: configuration = spec['configurations'][configuration_name] xcbc = xct.ConfigurationNamed(configuration_name) for include_dir in configuration.get('mac_framework_dirs', []): xcbc.AppendBuildSetting('FRAMEWORK_SEARCH_PATHS', include_dir) for include_dir in configuration.get('include_dirs', []): xcbc.AppendBuildSetting('HEADER_SEARCH_PATHS', include_dir) for library_dir in configuration.get('library_dirs', []): if library_dir not in xcode_standard_library_dirs and ( not xcbc.HasBuildSetting(_library_search_paths_var) or library_dir not in xcbc.GetBuildSetting(_library_search_paths_var)): xcbc.AppendBuildSetting(_library_search_paths_var, library_dir) if 'defines' in configuration: for define in configuration['defines']: set_define = EscapeXcodeDefine(define) xcbc.AppendBuildSetting('GCC_PREPROCESSOR_DEFINITIONS', set_define) if 'xcode_settings' in configuration: for xck, xcv in configuration['xcode_settings'].items(): xcbc.SetBuildSetting(xck, xcv) if 'xcode_config_file' in configuration: config_ref = pbxp.AddOrGetFileInRootGroup( configuration['xcode_config_file']) xcbc.SetBaseConfiguration(config_ref) build_files = [] for build_file, build_file_dict in data.items(): if build_file.endswith('.gyp'): build_files.append(build_file) for build_file in build_files: xcode_projects[build_file].Finalize1(xcode_targets, serialize_all_tests) for build_file in build_files: xcode_projects[build_file].Finalize2(xcode_targets, xcode_target_to_target_dict) for build_file in build_files: xcode_projects[build_file].Write()
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from airflow.models import DAG from airflow.operators.bash_operator import BashOperator from datetime import datetime from textwrap import dedent DEFAULT_DATE = datetime(2016, 1, 1) args = { 'owner': 'airflow', 'start_date': DEFAULT_DATE, } dag = DAG(dag_id='test_default_impersonation', default_args=args) deelevated_user = 'airflow_test_user' test_command = dedent( """\ if [ '{user}' != "$(whoami)" ]; then echo current user $(whoami) is not {user}! exit 1 fi """.format(user=deelevated_user)) task = BashOperator( task_id='test_deelevated_user', bash_command=test_command, dag=dag, )
unknown
codeparrot/codeparrot-clean
from bokeh.io import vplot from bokeh.models import ColumnDataSource, DataRange1d, Plot, LinearAxis, Grid, Circle, HoverTool, BoxSelectTool from bokeh.models.widgets import DataTable, TableColumn, StringFormatter, NumberFormatter, StringEditor, IntEditor, NumberEditor, SelectEditor from bokeh.embed import file_html from bokeh.resources import INLINE from bokeh.browserlib import view from bokeh.sampledata.autompg2 import autompg2 as mpg source = ColumnDataSource(mpg) manufacturers = sorted(mpg["manufacturer"].unique()) models = sorted(mpg["model"].unique()) transmissions = sorted(mpg["trans"].unique()) drives = sorted(mpg["drv"].unique()) classes = sorted(mpg["class"].unique()) columns = [ TableColumn(field="manufacturer", title="Manufacturer", editor=SelectEditor(options=manufacturers), formatter=StringFormatter(font_style="bold")), TableColumn(field="model", title="Model", editor=StringEditor(completions=models)), TableColumn(field="displ", title="Displacement", editor=NumberEditor(step=0.1), formatter=NumberFormatter(format="0.0")), TableColumn(field="year", title="Year", editor=IntEditor()), TableColumn(field="cyl", title="Cylinders", editor=IntEditor()), TableColumn(field="trans", title="Transmission", editor=SelectEditor(options=transmissions)), TableColumn(field="drv", title="Drive", editor=SelectEditor(options=drives)), TableColumn(field="class", title="Class", editor=SelectEditor(options=classes)), TableColumn(field="cty", title="City MPG", editor=IntEditor()), TableColumn(field="hwy", title="Highway MPG", editor=IntEditor()), ] data_table = DataTable(source=source, columns=columns, editable=True) plot = Plot(title=None, x_range= DataRange1d(), y_range=DataRange1d(), plot_width=1000, plot_height=300) # Set up x & y axis plot.add_layout(LinearAxis(), 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) # Add Glyphs cty_glyph = Circle(x="index", y="cty", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5) hwy_glyph = Circle(x="index", y="hwy", fill_color="#CE603D", size=8, fill_alpha=0.5, line_alpha=0.5) cty = plot.add_glyph(source, cty_glyph) hwy = plot.add_glyph(source, hwy_glyph) # Add the tools tooltips = [ ("Manufacturer", "@manufacturer"), ("Model", "@model"), ("Displacement", "@displ"), ("Year", "@year"), ("Cylinders", "@cyl"), ("Transmission", "@trans"), ("Drive", "@drv"), ("Class", "@class"), ] cty_hover_tool = HoverTool(renderers=[cty], tooltips=tooltips + [("City MPG", "@cty")]) hwy_hover_tool = HoverTool(renderers=[hwy], tooltips=tooltips + [("Highway MPG", "@hwy")]) select_tool = BoxSelectTool(renderers=[cty, hwy], dimensions=['width']) plot.add_tools(cty_hover_tool, hwy_hover_tool, select_tool) layout = vplot(plot, data_table) if __name__ == "__main__": filename = "data_tables.html" with open(filename, "w") as f: f.write(file_html(layout, INLINE, "Data Tables")) print("Wrote %s" % filename) view(filename)
unknown
codeparrot/codeparrot-clean
# =========================================================================== # eXe # Copyright 2004-2006, University of Auckland # Copyright 2006-2008 eXe Project, http://eXeLearning.org/ # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # =========================================================================== """ Package represents the collection of resources the user is editing i.e. the "package". """ import logging import time import zipfile import re from xml.dom import minidom from exe.engine.path import Path, TempDirPath, toUnicode from exe.engine.node import Node from exe.engine.genericidevice import GenericIdevice from exe.engine.persist import Persistable, encodeObject, \ decodeObject, decodeObjectRaw from exe import globals as G from exe.engine.resource import Resource from twisted.persisted.styles import Versioned, doUpgrade from twisted.spread.jelly import Jellyable, Unjellyable from exe.engine.beautifulsoup import BeautifulSoup from exe.engine.field import Field from exe.engine.persistxml import encodeObjectToXML, decodeObjectFromXML log = logging.getLogger(__name__) def clonePrototypeIdevice(title): idevice = None for prototype in G.application.ideviceStore.getIdevices(): if prototype.get_title() == title: log.debug('have prototype of:' + prototype.get_title()) idevice = prototype.clone() idevice.edit = False break return idevice def burstIdevice(idev_type, i, node): # given the iDevice type and the BeautifulSoup fragment i, burst it: idevice = clonePrototypeIdevice(idev_type) if idevice is None: log.warn("unable to clone " + idev_type + " idevice") freetext_idevice = clonePrototypeIdevice('Free Text') if freetext_idevice is None: log.error("unable to clone Free Text for " + idev_type + " idevice") return idevice = freetext_idevice # For idevices such as GalleryImage, where resources are being attached, # the idevice should already be attached to a node before bursting it open: node.addIdevice(idevice) idevice.burstHTML(i) return idevice def loadNodesIdevices(node, s): soup = BeautifulSoup(s) body = soup.find('body') if body: idevices = body.findAll(name='div', attrs={'class' : re.compile('Idevice$') }) if len(idevices) > 0: for i in idevices: # WARNING: none of the idevices yet re-attach their media, # but they do attempt to re-attach images and other links. if i.attrMap['class']=="activityIdevice": idevice = burstIdevice('Activity', i, node) elif i.attrMap['class']=="objectivesIdevice": idevice = burstIdevice('Objectives', i, node) #added kthamm 111028 elif i.attrMap['class']=="devsummaryIdevice": idevice = burstIdevice('Devsummary', i, node) elif i.attrMap['class']=="devpreviewIdevice": idevice = burstIdevice('Devpreview', i, node) elif i.attrMap['class']=="devresourceIdevice": idevice = burstIdevice('Devresource', i, node) elif i.attrMap['class']=="devdiscussionIdevice": idevice = burstIdevice('Devdiscussion', i, node) #end added kthamm elif i.attrMap['class']=="preknowledgeIdevice": idevice = burstIdevice('Preknowledge', i, node) elif i.attrMap['class']=="readingIdevice": idevice = burstIdevice('Reading Activity', i, node) # the above are all Generic iDevices; # below are all others: elif i.attrMap['class']=="RssIdevice": idevice = burstIdevice('RSS', i, node) elif i.attrMap['class']=="WikipediaIdevice": # WARNING: Wiki problems loading images with accents, etc: idevice = burstIdevice('Wiki Article', i, node) elif i.attrMap['class']=="ReflectionIdevice": idevice = burstIdevice('Reflection', i, node) elif i.attrMap['class']=="GalleryIdevice": # WARNING: Gallery problems with the popup html: idevice = burstIdevice('Image Gallery', i, node) elif i.attrMap['class']=="ImageMagnifierIdevice": # WARNING: Magnifier missing major bursting components: idevice = burstIdevice('Image Magnifier', i, node) elif i.attrMap['class']=="AppletIdevice": # WARNING: Applet missing file bursting components: idevice = burstIdevice('Java Applet', i, node) elif i.attrMap['class']=="ExternalUrlIdevice": idevice = burstIdevice('External Web Site', i, node) elif i.attrMap['class']=="ClozeIdevice": idevice = burstIdevice('Cloze Activity', i, node) elif i.attrMap['class']=="FreeTextIdevice": idevice = burstIdevice('Free Text', i, node) elif i.attrMap['class']=="CasestudyIdevice": idevice = burstIdevice('Case Study', i, node) elif i.attrMap['class']=="MultichoiceIdevice": idevice = burstIdevice('Multi-choice', i, node) elif i.attrMap['class']=="MultiSelectIdevice": idevice = burstIdevice('Multi-select', i, node) elif i.attrMap['class']=="QuizTestIdevice": idevice = burstIdevice('SCORM Quiz', i, node) elif i.attrMap['class']=="TrueFalseIdevice": idevice = burstIdevice('True-False Question', i, node) else: # NOTE: no custom idevices burst yet, # nor any deprecated idevices. Just burst into a FreeText: log.warn("unburstable idevice " + i.attrMap['class'] + "; bursting into Free Text") idevice = burstIdevice('Free Text', i, node) else: # no idevices listed on this page, # just create a free-text for the entire page: log.warn("no idevices found on this node, bursting into Free Text.") idevice = burstIdevice('Free Text', i, node) else: log.warn("unable to read the body of this node.") def test_for_node(html_content): # to see if this html really is an exe-generated node exe_string = u"<!-- Created using eXe: http://exelearning.org -->" if html_content.decode('utf-8').find(exe_string) >= 0: return True else: return False def loadNode(pass_num, resourceDir, zippedFile, node, doc, item, level): # populate this node # 1st pass = merely unzipping all resources such that they are available, # 2nd pass = loading the actual node idevices. titles = item.getElementsByTagName('title') node.setTitle(titles[0].firstChild.data) node_resource = item.attributes['identifierref'].value log.debug('*' * level + ' ' + titles[0].firstChild.data + '->' + item.attributes['identifierref'].value) for resource in doc.getElementsByTagName('resource'): if resource.attributes['identifier'].value == node_resource: for file in resource.childNodes: if file.nodeName == 'file': filename = file.attributes['href'].value is_exe_node_html = False if filename.endswith('.html') \ and filename != "fdl.html" \ and not filename.startswith("galleryPopup"): # fdl.html is the wikipedia license, ignore it # as well as any galleryPopups: is_exe_node_html = \ test_for_node(zippedFile.read(filename)) if is_exe_node_html: if pass_num == 1: # 2nd pass call to actually load the nodes: log.debug('loading idevices from node: ' + filename) loadNodesIdevices(node, zippedFile.read(filename)) elif filename == "fdl.html" or \ filename.startswith("galleryPopup."): # let these be re-created upon bursting. if pass_num == 0: # 1st pass call to unzip the resources: log.debug('ignoring resource file: '+ filename) else: if pass_num == 0: # 1st pass call to unzip the resources: try: zipinfo = zippedFile.getinfo(filename) log.debug('unzipping resource file: ' + resourceDir/filename ) outFile = open(resourceDir/filename, "wb") outFile.write(zippedFile.read(filename)) outFile.flush() outFile.close() except: log.warn('error unzipping resource file: ' + resourceDir/filename ) ########## # WARNING: the resource is now in the resourceDir, # BUT it is NOT YET added into any of the project, # much less to the specific idevices or fields! # Although they WILL be saved out with the project # upon the next Save. ########## break # process this node's children for subitem in item.childNodes: if subitem.nodeName == 'item': # for the first pass, of unzipping only, do not # create any child nodes, just cruise on with this one: next_node = node if pass_num == 1: # if this is actually loading the nodes: next_node = node.createChild() loadNode(pass_num, resourceDir, zippedFile, next_node, doc, subitem, level+1) def loadCC(zippedFile, filename): """ Load an IMS Common Cartridge or Content Package from filename """ package = Package(Path(filename).namebase) xmldoc = minidom.parseString( zippedFile.read('imsmanifest.xml')) organizations_list = xmldoc.getElementsByTagName('organizations') level = 0 # now a two-pass system to first unzip all applicable resources: for pass_num in range(2): for organizations in organizations_list: organization_list = organizations.getElementsByTagName( 'organization') for organization in organization_list: for item in organization.childNodes: if item.nodeName == 'item': loadNode(pass_num, package.resourceDir, zippedFile, package.root, xmldoc, item, level) return package # =========================================================================== class DublinCore(Jellyable, Unjellyable): """ Holds dublin core info """ def __init__(self): self.title = '' self.creator = '' self.subject = '' self.description = '' self.publisher = '' self.contributors = '' self.date = '' self.type = '' self.format = '' self.identifier = '' self.source = '' self.language = '' self.relation = '' self.coverage = '' self.rights = '' def __setattr__(self, name, value): self.__dict__[name] = toUnicode(value) class Package(Persistable): """ Package represents the collection of resources the user is editing i.e. the "package". """ persistenceVersion = 9 nonpersistant = ['resourceDir', 'filename'] # Name is used in filenames and urls (saving and navigating) _name = '' tempFile = False # This is set when the package is saved as a temp copy file # Title is rendered in exports _title = '' _author = '' _description = '' _backgroundImg = '' # This is like a constant defaultLevelNames = [x_(u"Topic"), x_(u"Section"), x_(u"Unit")] def __init__(self, name): """ Initialize """ log.debug(u"init " + repr(name)) self._nextIdeviceId = 0 self._nextNodeId = 0 # For looking up nodes by ids self._nodeIdDict = {} self._levelNames = self.defaultLevelNames[:] self.name = name self._title = u'' self._backgroundImg = u'' self.backgroundImgTile = False # Empty if never saved/loaded self.filename = u'' self.root = Node(self, None, _(u"Home")) self.currentNode = self.root self.style = u"default" self.isChanged = False self.idevices = [] self.dublinCore = DublinCore() self.scolinks = False self.scowsinglepage= False self.scowwebsite = False self.scowsource = False self.license = "None" self.footer = "" # Temporary directory to hold resources in self.resourceDir = TempDirPath() self.resources = {} # Checksum-[_Resource(),..] # Property Handlers def set_name(self, value): self._name = toUnicode(value) def set_title(self, value): self._title = toUnicode(value) def set_author(self, value): self._author = toUnicode(value) def set_description(self, value): self._description = toUnicode(value) def get_backgroundImg(self): """Get the background image for this package""" if self._backgroundImg: return "file://" + self._backgroundImg.path else: return "" def set_backgroundImg(self, value): """Set the background image for this package""" if self._backgroundImg: self._backgroundImg.delete() if value: if value.startswith("file://"): value = value[7:] imgFile = Path(value) self._backgroundImg = Resource(self, Path(imgFile)) else: self._backgroundImg = u'' def get_level1(self): return self.levelName(0) def set_level1(self, value): if value != '': self._levelNames[0] = value else: self._levelNames[0] = self.defaultLevelNames[0] def get_level2(self): return self.levelName(1) def set_level2(self, value): if value != '': self._levelNames[1] = value else: self._levelNames[1] = self.defaultLevelNames[1] def get_level3(self): return self.levelName(2) def set_level3(self, value): if value != '': self._levelNames[2] = value else: self._levelNames[2] = self.defaultLevelNames[2] # Properties name = property(lambda self:self._name, set_name) title = property(lambda self:self._title, set_title) author = property(lambda self:self._author, set_author) description = property(lambda self:self._description, set_description) backgroundImg = property(get_backgroundImg, set_backgroundImg) level1 = property(get_level1, set_level1) level2 = property(get_level2, set_level2) level3 = property(get_level3, set_level3) def findNode(self, nodeId): """ Finds a node from its nodeId (nodeId can be a string or a list/tuple) """ log.debug(u"findNode" + repr(nodeId)) node = self._nodeIdDict.get(nodeId) if node and node.package is self: return node else: return None def levelName(self, level): """ Return the level name """ if level < len(self._levelNames): return _(self._levelNames[level]) else: return _(u"?????") def save(self, filename=None, tempFile=False): """ Save package to disk pass an optional filename """ self.tempFile = tempFile # Get the filename if filename: filename = Path(filename) # If we are being given a new filename... # Change our name to match our new filename name = filename.splitpath()[1] if not tempFile: self.name = name.basename().splitext()[0] elif self.filename: # Otherwise use our last saved/loaded from filename filename = Path(self.filename) else: # If we don't have a last saved/loaded from filename, # raise an exception because, we need to have a new # file passed when a brand new package is saved raise AssertionError(u'No name passed when saving a new package') # Store our new filename for next file|save, and save the package log.debug(u"Will save %s to: %s" % (self.name, filename)) if tempFile: self.nonpersistant.remove('filename') oldFilename, self.filename = self.filename, unicode(self.filename) try: filename.safeSave(self.doSave, _('SAVE FAILED!\nLast succesful save is %s.')) finally: self.nonpersistant.append('filename') self.filename = oldFilename else: # Update our new filename for future saves self.filename = filename filename.safeSave(self.doSave, _('SAVE FAILED!\nLast succesful save is %s.')) self.isChanged = False self.updateRecentDocuments(filename) def updateRecentDocuments(self, filename): """ Updates the list of recent documents """ # Don't update the list for the generic.data "package" genericData = G.application.config.configDir/'idevices'/'generic.data' if genericData.isfile() or genericData.islink(): if Path(filename).samefile(genericData): return # Save in recentDocuments list recentProjects = G.application.config.recentProjects if filename in recentProjects: # If we're already number one, carry on if recentProjects[0] == filename: return recentProjects.remove(filename) recentProjects.insert(0, filename) del recentProjects[5:] # Delete any older names from the list G.application.config.configParser.write() # Save the settings def doSave(self, fileObj): """ Actually performs the save to 'fileObj'. """ zippedFile = zipfile.ZipFile(fileObj, "w", zipfile.ZIP_DEFLATED) try: for resourceFile in self.resourceDir.files(): zippedFile.write(unicode(resourceFile.normpath()), resourceFile.name.encode('utf8'), zipfile.ZIP_DEFLATED) zinfo = zipfile.ZipInfo(filename='content.data', date_time=time.localtime()[0:6]) zinfo.external_attr = 0100644<<16L zinfo.compress_type = zipfile.ZIP_DEFLATED zippedFile.writestr(zinfo, encodeObject(self)) zinfo2 = zipfile.ZipInfo(filename='contentv2.xml', date_time=time.localtime()[0:6]) zinfo2.external_attr = 0100644<<16L zinfo2.compress_type = zipfile.ZIP_DEFLATED zippedFile.writestr(zinfo2, encodeObjectToXML(self)) zippedFile.write(G.application.config.xulDir/'templates'/'content.xsd', 'content.xsd', zipfile.ZIP_DEFLATED) finally: zippedFile.close() def extractNode(self): """ Clones and extracts the currently selected node into a new package. """ newPackage = Package('NoName') # Name will be set once it is saved.. newPackage.title = self.currentNode.title newPackage.style = self.style newPackage.author = self.author newPackage._nextNodeId = self._nextNodeId # Copy the nodes from the original package # and merge into the root of the new package self.currentNode.copyToPackage(newPackage) return newPackage @staticmethod def load(filename, newLoad=True, destinationPackage=None, fromxml=None): """ Load package from disk, returns a package. """ if not zipfile.is_zipfile(filename): return None zippedFile = zipfile.ZipFile(filename, "r") xml = None try: xml = zippedFile.read(u"contentv2.xml") except: pass if not xml: try: # Get the jellied package data toDecode = zippedFile.read(u"content.data") except KeyError: log.info("no content.data, trying Common Cartridge/Content Package") newPackage = loadCC(zippedFile, filename) newPackage.tempFile = False newPackage.isChanged = False newPackage.filename = Path(filename) return newPackage # Need to add a TempDirPath because it is a nonpersistant member resourceDir = TempDirPath() # Extract resource files from package to temporary directory for fn in zippedFile.namelist(): if unicode(fn, 'utf8') not in [u"content.data", u"content.xml", u"contentv2.xml", u"content.xsd" ]: outFile = open(resourceDir/fn, "wb") outFile.write(zippedFile.read(fn)) outFile.flush() outFile.close() try: validxml = False if fromxml: newPackage, validxml = decodeObjectFromXML(fromxml) elif xml: xmlinfo = zippedFile.getinfo(u"contentv2.xml") datainfo = zippedFile.getinfo(u"content.data") if xmlinfo.date_time >= datainfo.date_time: newPackage, validxml = decodeObjectFromXML(xml) if not validxml: toDecode = zippedFile.read(u"content.data") newPackage = decodeObjectRaw(toDecode) G.application.afterUpgradeHandlers = [] newPackage.resourceDir = resourceDir G.application.afterUpgradeZombies2Delete = [] if not validxml and (xml or fromxml or "content.xml" in zippedFile.namelist()): for key, res in newPackage.resources.items(): if len(res) < 1: newPackage.resources.pop(key) else: res[0].testForAndDeleteZombieResources() if newLoad: # provide newPackage to doUpgrade's versionUpgrade() to # correct old corrupt extracted packages by setting the # any corrupt package references to the new package: log.debug("load() about to doUpgrade newPackage \"" + newPackage._name + "\" " + repr(newPackage) ) if hasattr(newPackage, 'resourceDir'): log.debug("newPackage resourceDir = " + newPackage.resourceDir) else: # even though it was just set above? should not get here: log.error("newPackage resourceDir has NO resourceDir!") doUpgrade(newPackage) # after doUpgrade, compare the largest found field ID: if G.application.maxFieldId >= Field.nextId: Field.nextId = G.application.maxFieldId + 1 else: # and when merging, automatically set package references to # the destinationPackage, into which this is being merged: log.debug("load() about to merge doUpgrade newPackage \"" + newPackage._name + "\" " + repr(newPackage) + " INTO destinationPackage \"" + destinationPackage._name + "\" " + repr(destinationPackage)) log.debug("using their resourceDirs:") if hasattr(newPackage, 'resourceDir'): log.debug(" newPackage resourceDir = " + newPackage.resourceDir) else: log.error("newPackage has NO resourceDir!") if hasattr(destinationPackage, 'resourceDir'): log.debug(" destinationPackage resourceDir = " + destinationPackage.resourceDir) else: log.error("destinationPackage has NO resourceDir!") doUpgrade(destinationPackage, isMerge=True, preMergePackage=newPackage) # after doUpgrade, compare the largest found field ID: if G.application.maxFieldId >= Field.nextId: Field.nextId = G.application.maxFieldId + 1 except: import traceback traceback.print_exc() raise if newPackage.tempFile: # newPackage.filename was stored as it's original filename newPackage.tempFile = False else: # newPackage.filename is the name that the package was last loaded from # or saved to newPackage.filename = Path(filename) # Let idevices and nodes handle any resource upgrading they may need to # Note: Package afterUpgradeHandlers *must* be done after Resources' # and the package should be updated before everything else, # so, prioritize with a 3-pass, 3-level calling setup # in order of: 1) resources, 2) package, 3) anything other objects for handler_priority in range(3): for handler in G.application.afterUpgradeHandlers: if handler_priority == 0 and \ repr(handler.im_class)=="<class 'exe.engine.resource.Resource'>": # level-0 handlers: Resource handler() elif handler_priority == 1 and \ repr(handler.im_class)=="<class 'exe.engine.package.Package'>": # level-1 handlers: Package (requires resources first) if handler.im_self == newPackage: handler() else: log.warn("Extra package object found, " \ + "ignoring its afterUpgradeHandler: " \ + repr(handler)) elif handler_priority == 2 and \ repr(handler.im_class)!="<class 'exe.engine.resource.Resource'>" \ and \ repr(handler.im_class)!="<class 'exe.engine.package.Package'>": # level-2 handlers: all others handler() G.application.afterUpgradeHandlers = [] num_zombies = len(G.application.afterUpgradeZombies2Delete) for i in range(num_zombies-1, -1, -1): zombie = G.application.afterUpgradeZombies2Delete[i] # now, the zombie list can contain nodes OR resources to delete. # if zombie is a node, then also pass in a pruning parameter.. zombie_is_node = False if isinstance(zombie, Node): zombie_is_node = True if zombie_is_node: zombie.delete(pruningZombies=True) else: zombie.delete() del zombie G.application.afterUpgradeZombies2Delete = [] newPackage.updateRecentDocuments(newPackage.filename) newPackage.isChanged = False return newPackage def cleanUpResources(self): """ Removes duplicate resource files """ # Delete unused resources. # Only really needed for upgrading to version 0.20, # but upgrading of resources and package happens in no particular order # and must be done after all resources have been upgraded # some earlier .elp files appear to have been corrupted with # two packages loaded, *possibly* from some strange extract/merge # functionality in earlier eXe versions? # Regardless, only the real package will have a resourceDir, # and the other will fail. # For now, then, put in this quick and easy safety check: if not hasattr(self,'resourceDir'): log.warn("cleanUpResources called on a redundant package") return existingFiles = set([fn.basename() for fn in self.resourceDir.files()]) usedFiles = set([reses[0].storageName for reses in self.resources.values()]) for fn in existingFiles - usedFiles: (self.resourceDir/fn).remove() def findResourceByName(self, queryName): """ Support for merging, and anywhere else that unique names might be checked before actually comparing against the files (as will be done by the resource class itself in its _addOurselvesToPackage() ) """ foundResource = None queryResources = self.resources for this_checksum in queryResources: for this_resource in queryResources[this_checksum]: if queryName == this_resource.storageName: foundResource = this_resource return foundResource return foundResource def upgradeToVersion1(self): """ Called to upgrade from 0.3 release """ self._nextNodeId = 0 self._nodeIdDict = {} # Also upgrade all the nodes. # This needs to be done here so that draft gets id 0 # If it's done in the nodes, the ids are assigned in reverse order draft = getattr(self, 'draft') draft._id = self._regNewNode(draft) draft._package = self setattr(self, 'editor', Node(self, None, _(u"iDevice Editor"))) # Add a default idevice to the editor idevice = GenericIdevice("", "", "", "", "") editor = getattr(self, 'editor') idevice.parentNode = editor editor.addIdevice(idevice) def superReg(node): """Registers all our nodes because in v0 they were not registered in this way""" node._id = self._regNewNode(node) node._package = self for child in node.children: superReg(child) superReg(self.root) def _regNewNode(self, node): """ Called only by nodes, stores the node in our id lookup dict returns a new unique id """ id_ = unicode(self._nextNodeId) self._nextNodeId += 1 self._nodeIdDict[id_] = node return id_ def getNewIdeviceId(self): """ Returns an iDevice Id which is unique for this package. """ id_ = unicode(self._nextIdeviceId) self._nextIdeviceId += 1 return id_ def upgradeToVersion2(self): """ Called to upgrade from 0.4 release """ getattr(self, 'draft').delete() getattr(self, 'editor').delete() delattr(self, 'draft') delattr(self, 'editor') # Need to renumber nodes because idevice node and draft nodes are gone self._nextNodeId = 0 def renumberNode(node): """ Gives the old node a number """ node._id = self._regNewNode(node) for child in node.children: renumberNode(child) renumberNode(self.root) def upgradeToVersion3(self): """ Also called to upgrade from 0.4 release """ self._nextIdeviceId = 0 def upgradeToVersion4(self): """ Puts properties in their place Also called to upgrade from 0.8 release """ self._name = toUnicode(self.__dict__['name']) self._author = toUnicode(self.__dict__['author']) self._description = toUnicode(self.__dict__['description']) def upgradeToVersion5(self): """ For version 0.11 """ self._levelNames = self.levelNames del self.levelNames def upgradeToVersion6(self): """ For version 0.14 """ self.dublinCore = DublinCore() # Copy some of the package properties to dublin core self.title = self.root.title self.dublinCore.title = self.root.title self.dublinCore.creator = self._author self.dublinCore.description = self._description self.scolinks = False def upgradeToVersion7(self): """ For version 0.15 """ self._backgroundImg = '' self.backgroundImgTile = False def upgradeToVersion8(self): """ For version 0.20, alpha, for nightlies r2469 """ self.license = 'None' self.footer = "" self.idevices = [] def upgradeToVersion9(self): """ For version >= 0.20.4 """ if not hasattr(self, 'resources'): # The hasattr is needed, because sometimes, Resource instances are upgraded # first and they also set this attribute on the package self.resources = {} G.application.afterUpgradeHandlers.append(self.cleanUpResources) # ===========================================================================
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- "Test for Annotation Xmodule functional logic." import unittest from mock import Mock from lxml import etree from xblock.field_data import DictFieldData from xblock.fields import ScopeIds from xmodule.videoannotation_module import VideoAnnotationModule from . import get_test_system class VideoAnnotationModuleTestCase(unittest.TestCase): ''' Video Annotation Module Test Case ''' sample_xml = ''' <annotatable> <instructions><p>Video Test Instructions.</p></instructions> </annotatable> ''' sample_sourceurl = "http://video-js.zencoder.com/oceans-clip.mp4" sample_youtubeurl = "http://www.youtube.com/watch?v=yxLIu-scR9Y" def setUp(self): """ Makes sure that the Video Annotation Module is created. """ super(VideoAnnotationModuleTestCase, self).setUp() # return anything except None to test LMS def test_real_user(useless): useless_user = Mock(email='fake@fake.com', id=useless) return useless_user # test to make sure that role is checked in LMS def test_user_role(): return 'staff' self.system = get_test_system() self.system.get_real_user = test_real_user self.system.get_user_role = test_user_role self.system.anonymous_student_id = None self.mod = VideoAnnotationModule( Mock(), self.system, DictFieldData({'data': self.sample_xml, 'sourceUrl': self.sample_sourceurl}), ScopeIds(None, None, None, None) ) def test_extract_instructions(self): """ This test ensures that if an instruction exists it is pulled and formatted from the <instructions> tags. Otherwise, it should return nothing. """ xmltree = etree.fromstring(self.sample_xml) expected_xml = u"<div><p>Video Test Instructions.</p></div>" actual_xml = self.mod._extract_instructions(xmltree) # pylint: disable=protected-access self.assertIsNotNone(actual_xml) self.assertEqual(expected_xml.strip(), actual_xml.strip()) xmltree = etree.fromstring('<annotatable>foo</annotatable>') actual = self.mod._extract_instructions(xmltree) # pylint: disable=protected-access self.assertIsNone(actual) def test_get_extension(self): """ Tests the function that returns the appropriate extension depending on whether it is a video from youtube, or one uploaded to the EdX server. """ expectedyoutube = 'video/youtube' expectednotyoutube = 'video/mp4' result1 = self.mod._get_extension(self.sample_sourceurl) # pylint: disable=protected-access result2 = self.mod._get_extension(self.sample_youtubeurl) # pylint: disable=protected-access self.assertEqual(expectedyoutube, result2) self.assertEqual(expectednotyoutube, result1) def test_student_view(self): """ Tests to make sure variables passed in truly exist within the html once it is all rendered. """ context = self.mod.student_view({}).content for key in ['display_name', 'instructions_html', 'sourceUrl', 'typeSource', 'poster', 'annotation_storage', 'default_tab', 'instructor_email', 'annotation_mode', 'is_course_staff']: self.assertIn(key, context)
unknown
codeparrot/codeparrot-clean
#!/usr/bin/python # -*- coding: utf-8 -*- # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified'} DOCUMENTATION = r''' --- module: aci_interface_policy_l2 short_description: Manage Layer 2 interface policies (l2:IfPol) description: - Manage Layer 2 interface policies on Cisco ACI fabrics. version_added: '2.4' options: l2_policy: description: - The name of the Layer 2 interface policy. type: str required: yes aliases: [ name ] description: description: - The description of the Layer 2 interface policy. type: str aliases: [ descr ] qinq: description: - Determines if QinQ is disabled or if the port should be considered a core or edge port. - The APIC defaults to C(disabled) when unset during creation. type: str choices: [ core, disabled, edge ] vepa: description: - Determines if Virtual Ethernet Port Aggregator is disabled or enabled. - The APIC defaults to C(no) when unset during creation. type: bool vlan_scope: description: - The scope of the VLAN. - The APIC defaults to C(global) when unset during creation. type: str choices: [ global, portlocal ] state: description: - Use C(present) or C(absent) for adding or removing. - Use C(query) for listing an object or multiple objects. type: str choices: [ absent, present, query ] default: present name_alias: version_added: '2.10' description: - The alias for the current object. This relates to the nameAlias field in ACI. type: str extends_documentation_fragment: aci seealso: - name: APIC Management Information Model reference description: More information about the internal APIC class B(l2:IfPol). link: https://developer.cisco.com/docs/apic-mim-ref/ author: - Dag Wieers (@dagwieers) ''' EXAMPLES = r''' - aci_interface_policy_l2: host: '{{ hostname }}' username: '{{ username }}' password: '{{ password }}' l2_policy: '{{ l2_policy }}' vlan_scope: '{{ vlan_policy }}' description: '{{ description }}' delegate_to: localhost ''' RETURN = r''' current: description: The existing configuration from the APIC after the module has finished returned: success type: list sample: [ { "fvTenant": { "attributes": { "descr": "Production environment", "dn": "uni/tn-production", "name": "production", "nameAlias": "", "ownerKey": "", "ownerTag": "" } } } ] error: description: The error information as returned from the APIC returned: failure type: dict sample: { "code": "122", "text": "unknown managed object class foo" } raw: description: The raw output returned by the APIC REST API (xml or json) returned: parse error type: str sample: '<?xml version="1.0" encoding="UTF-8"?><imdata totalCount="1"><error code="122" text="unknown managed object class foo"/></imdata>' sent: description: The actual/minimal configuration pushed to the APIC returned: info type: list sample: { "fvTenant": { "attributes": { "descr": "Production environment" } } } previous: description: The original configuration from the APIC before the module has started returned: info type: list sample: [ { "fvTenant": { "attributes": { "descr": "Production", "dn": "uni/tn-production", "name": "production", "nameAlias": "", "ownerKey": "", "ownerTag": "" } } } ] proposed: description: The assembled configuration from the user-provided parameters returned: info type: dict sample: { "fvTenant": { "attributes": { "descr": "Production environment", "name": "production" } } } filter_string: description: The filter string used for the request returned: failure or debug type: str sample: ?rsp-prop-include=config-only method: description: The HTTP method used for the request to the APIC returned: failure or debug type: str sample: POST response: description: The HTTP response from the APIC returned: failure or debug type: str sample: OK (30 bytes) status: description: The HTTP status from the APIC returned: failure or debug type: int sample: 200 url: description: The HTTP url used for the request to the APIC returned: failure or debug type: str sample: https://10.11.12.13/api/mo/uni/tn-production.json ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.aci.aci import ACIModule, aci_argument_spec # Mapping dicts are used to normalize the proposed data to what the APIC expects, which will keep diffs accurate QINQ_MAPPING = dict( core='corePort', disabled='disabled', edge='edgePort', ) def main(): argument_spec = aci_argument_spec() argument_spec.update( l2_policy=dict(type='str', aliases=['name']), # Not required for querying all policies description=dict(type='str', aliases=['descr']), vlan_scope=dict(type='str', choices=['global', 'portlocal']), # No default provided on purpose qinq=dict(type='str', choices=['core', 'disabled', 'edge']), vepa=dict(type='bool'), state=dict(type='str', default='present', choices=['absent', 'present', 'query']), name_alias=dict(type='str'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_if=[ ['state', 'absent', ['l2_policy']], ['state', 'present', ['l2_policy']], ], ) aci = ACIModule(module) l2_policy = module.params.get('l2_policy') vlan_scope = module.params.get('vlan_scope') qinq = module.params.get('qinq') if qinq is not None: qinq = QINQ_MAPPING.get(qinq) vepa = aci.boolean(module.params.get('vepa'), 'enabled', 'disabled') description = module.params.get('description') state = module.params.get('state') name_alias = module.params.get('name_alias') aci.construct_url( root_class=dict( aci_class='l2IfPol', aci_rn='infra/l2IfP-{0}'.format(l2_policy), module_object=l2_policy, target_filter={'name': l2_policy}, ), ) aci.get_existing() if state == 'present': aci.payload( aci_class='l2IfPol', class_config=dict( name=l2_policy, descr=description, vlanScope=vlan_scope, qinq=qinq, vepa=vepa, nameAlias=name_alias, ), ) aci.get_diff(aci_class='l2IfPol') aci.post_config() elif state == 'absent': aci.delete_config() aci.exit_json() if __name__ == "__main__": main()
unknown
codeparrot/codeparrot-clean
pr: 139685 summary: Reduce priority of clear-cache tasks area: Machine Learning type: bug issues: []
unknown
github
https://github.com/elastic/elasticsearch
docs/changelog/139685.yaml
{ "private": true, "scripts": { "dev": "next --turbo", "build": "next build", "start": "next start" }, "dependencies": { "next": "latest", "react": "^18.2.0", "react-dom": "^18.2.0" }, "devDependencies": { "@svgr/webpack": "6.5.1", "@types/node": "^18.11.9", "@types/react": "^18.0.25", "@types/react-dom": "^18.0.9", "stylus": "0.59.0", "stylus-loader": "7.1.3", "typescript": "^4.9.3" } }
json
github
https://github.com/vercel/next.js
examples/with-turbopack-loaders/package.json
# testing/util.py # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from ..util import jython, pypy, defaultdict, decorator, py2k import decimal import gc import time import random import sys import types if jython: def jython_gc_collect(*args): """aggressive gc.collect for tests.""" gc.collect() time.sleep(0.1) gc.collect() gc.collect() return 0 # "lazy" gc, for VM's that don't GC on refcount == 0 gc_collect = lazy_gc = jython_gc_collect elif pypy: def pypy_gc_collect(*args): gc.collect() gc.collect() gc_collect = lazy_gc = pypy_gc_collect else: # assume CPython - straight gc.collect, lazy_gc() is a pass gc_collect = gc.collect def lazy_gc(): pass def picklers(): picklers = set() if py2k: try: import cPickle picklers.add(cPickle) except ImportError: pass import pickle picklers.add(pickle) # yes, this thing needs this much testing for pickle_ in picklers: for protocol in -1, 0, 1, 2: yield pickle_.loads, lambda d: pickle_.dumps(d, protocol) def round_decimal(value, prec): if isinstance(value, float): return round(value, prec) # can also use shift() here but that is 2.6 only return (value * decimal.Decimal("1" + "0" * prec) ).to_integral(decimal.ROUND_FLOOR) / \ pow(10, prec) class RandomSet(set): def __iter__(self): l = list(set.__iter__(self)) random.shuffle(l) return iter(l) def pop(self): index = random.randint(0, len(self) - 1) item = list(set.__iter__(self))[index] self.remove(item) return item def union(self, other): return RandomSet(set.union(self, other)) def difference(self, other): return RandomSet(set.difference(self, other)) def intersection(self, other): return RandomSet(set.intersection(self, other)) def copy(self): return RandomSet(self) def conforms_partial_ordering(tuples, sorted_elements): """True if the given sorting conforms to the given partial ordering.""" deps = defaultdict(set) for parent, child in tuples: deps[parent].add(child) for i, node in enumerate(sorted_elements): for n in sorted_elements[i:]: if node in deps[n]: return False else: return True def all_partial_orderings(tuples, elements): edges = defaultdict(set) for parent, child in tuples: edges[child].add(parent) def _all_orderings(elements): if len(elements) == 1: yield list(elements) else: for elem in elements: subset = set(elements).difference([elem]) if not subset.intersection(edges[elem]): for sub_ordering in _all_orderings(subset): yield [elem] + sub_ordering return iter(_all_orderings(elements)) def function_named(fn, name): """Return a function with a given __name__. Will assign to __name__ and return the original function if possible on the Python implementation, otherwise a new function will be constructed. This function should be phased out as much as possible in favor of @decorator. Tests that "generate" many named tests should be modernized. """ try: fn.__name__ = name except TypeError: fn = types.FunctionType(fn.__code__, fn.__globals__, name, fn.__defaults__, fn.__closure__) return fn def run_as_contextmanager(ctx, fn, *arg, **kw): """Run the given function under the given contextmanager, simulating the behavior of 'with' to support older Python versions. This is not necessary anymore as we have placed 2.6 as minimum Python version, however some tests are still using this structure. """ obj = ctx.__enter__() try: result = fn(obj, *arg, **kw) ctx.__exit__(None, None, None) return result except: exc_info = sys.exc_info() raise_ = ctx.__exit__(*exc_info) if raise_ is None: raise else: return raise_ def rowset(results): """Converts the results of sql execution into a plain set of column tuples. Useful for asserting the results of an unordered query. """ return set([tuple(row) for row in results]) def fail(msg): assert False, msg @decorator def provide_metadata(fn, *args, **kw): """Provide bound MetaData for a single test, dropping afterwards.""" from . import config from . import engines from sqlalchemy import schema metadata = schema.MetaData(config.db) self = args[0] prev_meta = getattr(self, 'metadata', None) self.metadata = metadata try: return fn(*args, **kw) finally: engines.drop_all_tables(metadata, config.db) self.metadata = prev_meta def force_drop_names(*names): """Force the given table names to be dropped after test complete, isolating for foreign key cycles """ from . import config from sqlalchemy import inspect @decorator def go(fn, *args, **kw): try: return fn(*args, **kw) finally: drop_all_tables( config.db, inspect(config.db), include_names=names) return go class adict(dict): """Dict keys available as attributes. Shadows.""" def __getattribute__(self, key): try: return self[key] except KeyError: return dict.__getattribute__(self, key) def __call__(self, *keys): return tuple([self[key] for key in keys]) get_all = __call__ def drop_all_tables(engine, inspector, schema=None, include_names=None): from sqlalchemy import Column, Table, Integer, MetaData, \ ForeignKeyConstraint from sqlalchemy.schema import DropTable, DropConstraint if include_names is not None: include_names = set(include_names) with engine.connect() as conn: for tname, fkcs in reversed( inspector.get_sorted_table_and_fkc_names(schema=schema)): if tname: if include_names is not None and tname not in include_names: continue conn.execute(DropTable( Table(tname, MetaData(), schema=schema) )) elif fkcs: if not engine.dialect.supports_alter: continue for tname, fkc in fkcs: if include_names is not None and \ tname not in include_names: continue tb = Table( tname, MetaData(), Column('x', Integer), Column('y', Integer), schema=schema ) conn.execute(DropConstraint( ForeignKeyConstraint( [tb.c.x], [tb.c.y], name=fkc) )) def teardown_events(event_cls): @decorator def decorate(fn, *arg, **kw): try: return fn(*arg, **kw) finally: event_cls._clear() return decorate
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env bash set -eux function cleanup { ansible-playbook -i "${INVENTORY_PATH}" cleanup.yml -e "output_dir=${OUTPUT_DIR}" -b "$@" unset ANSIBLE_CACHE_PLUGIN unset ANSIBLE_CACHE_PLUGIN_CONNECTION } trap 'cleanup "$@"' EXIT # setup required roles ln -s ../../setup_remote_tmp_dir roles/setup_remote_tmp_dir # run old type role tests ansible-playbook -i ../../inventory run_fetch_tests.yml -e "output_dir=${OUTPUT_DIR}" "$@" # run same test with become ansible-playbook -i ../../inventory run_fetch_tests.yml -e "output_dir=${OUTPUT_DIR}" -b "$@" # run tests to avoid path injection from slurp when fetch uses become ansible-playbook -i ../../inventory injection/avoid_slurp_return.yml -e "output_dir=${OUTPUT_DIR}" "$@" ## Test unreadable file with stat. Requires running without become and as a user other than root. # # Change the known_hosts file to avoid changing the test environment export ANSIBLE_CACHE_PLUGIN=jsonfile export ANSIBLE_CACHE_PLUGIN_CONNECTION="${OUTPUT_DIR}/cache" # Create a non-root user account and configure SSH access for that account ansible-playbook -i "${INVENTORY_PATH}" setup_unreadable_test.yml -e "output_dir=${OUTPUT_DIR}" "$@" # Run the tests as the unprivileged user without become to test the use of the stat module from the fetch module ansible-playbook -i "${INVENTORY_PATH}" test_unreadable_with_stat.yml -e ansible_user=fetcher -e ansible_become=no -e "output_dir=${OUTPUT_DIR}" "$@"
unknown
github
https://github.com/ansible/ansible
test/integration/targets/fetch/runme.sh
# coding: utf-8 # # Copyright (C) 2015-2016 YouCompleteMe contributors # # This file is part of YouCompleteMe. # # YouCompleteMe is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # YouCompleteMe is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with YouCompleteMe. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from builtins import * # noqa from ycm.tests.test_utils import ( CurrentWorkingDirectory, ExtendedMock, MockVimBuffers, MockVimModule, VimBuffer ) MockVimModule() import contextlib import os from ycm.tests import PathToTestFile, YouCompleteMeInstance from ycmd.responses import ( BuildDiagnosticData, Diagnostic, Location, Range, UnknownExtraConf, ServerError ) from hamcrest import assert_that, contains, has_entries, has_item from mock import call, MagicMock, patch from nose.tools import eq_, ok_ def PresentDialog_Confirm_Call( message ): """Return a mock.call object for a call to vimsupport.PresentDialog, as called why vimsupport.Confirm with the supplied confirmation message""" return call( message, [ 'Ok', 'Cancel' ] ) def PlaceSign_Call( sign_id, line_num, buffer_num, is_error ): sign_name = 'YcmError' if is_error else 'YcmWarning' return call( 'sign place {0} line={1} name={2} buffer={3}' .format( sign_id, line_num, sign_name, buffer_num ) ) def UnplaceSign_Call( sign_id, buffer_num ): return call( 'try | exec "sign unplace {0} buffer={1}" |' ' catch /E158/ | endtry'.format( sign_id, buffer_num ) ) @contextlib.contextmanager def MockArbitraryBuffer( filetype ): """Used via the with statement, set up a single buffer with an arbitrary name and no contents. Its filetype is set to the supplied filetype.""" # Arbitrary, but valid, single buffer open. current_buffer = VimBuffer( os.path.realpath( 'TEST_BUFFER' ), window = 1, filetype = filetype ) with MockVimBuffers( [ current_buffer ], current_buffer ): yield @contextlib.contextmanager def MockEventNotification( response_method, native_filetype_completer = True ): """Mock out the EventNotification client request object, replacing the Response handler's JsonFromFuture with the supplied |response_method|. Additionally mock out YouCompleteMe's FiletypeCompleterExistsForFiletype method to return the supplied |native_filetype_completer| parameter, rather than querying the server""" # We don't want the event to actually be sent to the server, just have it # return success with patch( 'ycm.client.base_request.BaseRequest.PostDataToHandlerAsync', return_value = MagicMock( return_value=True ) ): # We set up a fake a Response (as called by EventNotification.Response) # which calls the supplied callback method. Generally this callback just # raises an apropriate exception, otherwise it would have to return a mock # future object. # # Note: JsonFromFuture is actually part of ycm.client.base_request, but we # must patch where an object is looked up, not where it is defined. # See https://docs.python.org/dev/library/unittest.mock.html#where-to-patch # for details. with patch( 'ycm.client.event_notification.JsonFromFuture', side_effect = response_method ): # Filetype available information comes from the server, so rather than # relying on that request, we mock out the check. The caller decides if # filetype completion is available with patch( 'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype', return_value = native_filetype_completer ): yield @patch( 'ycm.vimsupport.PostVimMessage', new_callable = ExtendedMock ) @YouCompleteMeInstance() def EventNotification_FileReadyToParse_NonDiagnostic_Error_test( ycm, post_vim_message ): # This test validates the behaviour of YouCompleteMe.HandleFileParseRequest # in combination with YouCompleteMe.OnFileReadyToParse when the completer # raises an exception handling FileReadyToParse event notification ERROR_TEXT = 'Some completer response text' def ErrorResponse( *args ): raise ServerError( ERROR_TEXT ) with MockArbitraryBuffer( 'javascript' ): with MockEventNotification( ErrorResponse ): ycm.OnFileReadyToParse() ok_( ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() # The first call raises a warning post_vim_message.assert_has_exact_calls( [ call( ERROR_TEXT, truncate = True ) ] ) # Subsequent calls don't re-raise the warning ycm.HandleFileParseRequest() post_vim_message.assert_has_exact_calls( [ call( ERROR_TEXT, truncate = True ) ] ) # But it does if a subsequent event raises again ycm.OnFileReadyToParse() ok_( ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() post_vim_message.assert_has_exact_calls( [ call( ERROR_TEXT, truncate = True ), call( ERROR_TEXT, truncate = True ) ] ) @patch( 'vim.command' ) @YouCompleteMeInstance() def EventNotification_FileReadyToParse_NonDiagnostic_Error_NonNative_test( ycm, vim_command ): with MockArbitraryBuffer( 'javascript' ): with MockEventNotification( None, False ): ycm.OnFileReadyToParse() ycm.HandleFileParseRequest() vim_command.assert_not_called() @patch( 'ycm.client.base_request._LoadExtraConfFile', new_callable = ExtendedMock ) @patch( 'ycm.client.base_request._IgnoreExtraConfFile', new_callable = ExtendedMock ) @YouCompleteMeInstance() def EventNotification_FileReadyToParse_NonDiagnostic_ConfirmExtraConf_test( ycm, ignore_extra_conf, load_extra_conf ): # This test validates the behaviour of YouCompleteMe.HandleFileParseRequest # in combination with YouCompleteMe.OnFileReadyToParse when the completer # raises the (special) UnknownExtraConf exception FILE_NAME = 'a_file' MESSAGE = ( 'Found ' + FILE_NAME + '. Load? \n\n(Question can be ' 'turned off with options, see YCM docs)' ) def UnknownExtraConfResponse( *args ): raise UnknownExtraConf( FILE_NAME ) with MockArbitraryBuffer( 'javascript' ): with MockEventNotification( UnknownExtraConfResponse ): # When the user accepts the extra conf, we load it with patch( 'ycm.vimsupport.PresentDialog', return_value = 0, new_callable = ExtendedMock ) as present_dialog: ycm.OnFileReadyToParse() ok_( ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() present_dialog.assert_has_exact_calls( [ PresentDialog_Confirm_Call( MESSAGE ), ] ) load_extra_conf.assert_has_exact_calls( [ call( FILE_NAME ), ] ) # Subsequent calls don't re-raise the warning ycm.HandleFileParseRequest() present_dialog.assert_has_exact_calls( [ PresentDialog_Confirm_Call( MESSAGE ) ] ) load_extra_conf.assert_has_exact_calls( [ call( FILE_NAME ), ] ) # But it does if a subsequent event raises again ycm.OnFileReadyToParse() ok_( ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() present_dialog.assert_has_exact_calls( [ PresentDialog_Confirm_Call( MESSAGE ), PresentDialog_Confirm_Call( MESSAGE ), ] ) load_extra_conf.assert_has_exact_calls( [ call( FILE_NAME ), call( FILE_NAME ), ] ) # When the user rejects the extra conf, we reject it with patch( 'ycm.vimsupport.PresentDialog', return_value = 1, new_callable = ExtendedMock ) as present_dialog: ycm.OnFileReadyToParse() ok_( ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() present_dialog.assert_has_exact_calls( [ PresentDialog_Confirm_Call( MESSAGE ), ] ) ignore_extra_conf.assert_has_exact_calls( [ call( FILE_NAME ), ] ) # Subsequent calls don't re-raise the warning ycm.HandleFileParseRequest() present_dialog.assert_has_exact_calls( [ PresentDialog_Confirm_Call( MESSAGE ) ] ) ignore_extra_conf.assert_has_exact_calls( [ call( FILE_NAME ), ] ) # But it does if a subsequent event raises again ycm.OnFileReadyToParse() ok_( ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() present_dialog.assert_has_exact_calls( [ PresentDialog_Confirm_Call( MESSAGE ), PresentDialog_Confirm_Call( MESSAGE ), ] ) ignore_extra_conf.assert_has_exact_calls( [ call( FILE_NAME ), call( FILE_NAME ), ] ) @YouCompleteMeInstance() def EventNotification_FileReadyToParse_Diagnostic_Error_Native_test( ycm ): _Check_FileReadyToParse_Diagnostic_Error( ycm ) _Check_FileReadyToParse_Diagnostic_Warning( ycm ) _Check_FileReadyToParse_Diagnostic_Clean( ycm ) @patch( 'vim.command' ) def _Check_FileReadyToParse_Diagnostic_Error( ycm, vim_command ): # Tests Vim sign placement and error/warning count python API # when one error is returned. def DiagnosticResponse( *args ): start = Location( 1, 2, 'TEST_BUFFER' ) end = Location( 1, 4, 'TEST_BUFFER' ) extent = Range( start, end ) diagnostic = Diagnostic( [], start, extent, 'expected ;', 'ERROR' ) return [ BuildDiagnosticData( diagnostic ) ] with MockArbitraryBuffer( 'cpp' ): with MockEventNotification( DiagnosticResponse ): ycm.OnFileReadyToParse() ok_( ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() vim_command.assert_has_calls( [ PlaceSign_Call( 1, 1, 1, True ) ] ) eq_( ycm.GetErrorCount(), 1 ) eq_( ycm.GetWarningCount(), 0 ) # Consequent calls to HandleFileParseRequest shouldn't mess with # existing diagnostics, when there is no new parse request. vim_command.reset_mock() ok_( not ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() vim_command.assert_not_called() eq_( ycm.GetErrorCount(), 1 ) eq_( ycm.GetWarningCount(), 0 ) @patch( 'vim.command' ) def _Check_FileReadyToParse_Diagnostic_Warning( ycm, vim_command ): # Tests Vim sign placement/unplacement and error/warning count python API # when one warning is returned. # Should be called after _Check_FileReadyToParse_Diagnostic_Error def DiagnosticResponse( *args ): start = Location( 2, 2, 'TEST_BUFFER' ) end = Location( 2, 4, 'TEST_BUFFER' ) extent = Range( start, end ) diagnostic = Diagnostic( [], start, extent, 'cast', 'WARNING' ) return [ BuildDiagnosticData( diagnostic ) ] with MockArbitraryBuffer( 'cpp' ): with MockEventNotification( DiagnosticResponse ): ycm.OnFileReadyToParse() ok_( ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() vim_command.assert_has_calls( [ PlaceSign_Call( 2, 2, 1, False ), UnplaceSign_Call( 1, 1 ) ] ) eq_( ycm.GetErrorCount(), 0 ) eq_( ycm.GetWarningCount(), 1 ) # Consequent calls to HandleFileParseRequest shouldn't mess with # existing diagnostics, when there is no new parse request. vim_command.reset_mock() ok_( not ycm.FileParseRequestReady() ) ycm.HandleFileParseRequest() vim_command.assert_not_called() eq_( ycm.GetErrorCount(), 0 ) eq_( ycm.GetWarningCount(), 1 ) @patch( 'vim.command' ) def _Check_FileReadyToParse_Diagnostic_Clean( ycm, vim_command ): # Tests Vim sign unplacement and error/warning count python API # when there are no errors/warnings left. # Should be called after _Check_FileReadyToParse_Diagnostic_Warning with MockArbitraryBuffer( 'cpp' ): with MockEventNotification( MagicMock( return_value = [] ) ): ycm.OnFileReadyToParse() ycm.HandleFileParseRequest() vim_command.assert_has_calls( [ UnplaceSign_Call( 2, 1 ) ] ) eq_( ycm.GetErrorCount(), 0 ) eq_( ycm.GetWarningCount(), 0 ) @patch( 'ycm.youcompleteme.YouCompleteMe._AddUltiSnipsDataIfNeeded' ) @YouCompleteMeInstance( { 'collect_identifiers_from_tags_files': 1 } ) def EventNotification_FileReadyToParse_TagFiles_UnicodeWorkingDirectory_test( ycm, *args ): unicode_dir = PathToTestFile( 'uni¢𐍈d€' ) current_buffer_file = PathToTestFile( 'uni¢𐍈d€', 'current_buffer' ) current_buffer = VimBuffer( name = current_buffer_file, contents = [ 'current_buffer_contents' ], filetype = 'some_filetype' ) with patch( 'ycm.client.base_request.BaseRequest.' 'PostDataToHandlerAsync' ) as post_data_to_handler_async: with CurrentWorkingDirectory( unicode_dir ): with MockVimBuffers( [ current_buffer ], current_buffer, ( 6, 5 ) ): ycm.OnFileReadyToParse() assert_that( # Positional arguments passed to PostDataToHandlerAsync. post_data_to_handler_async.call_args[ 0 ], contains( has_entries( { 'filepath': current_buffer_file, 'line_num': 6, 'column_num': 6, 'file_data': has_entries( { current_buffer_file: has_entries( { 'contents': 'current_buffer_contents\n', 'filetypes': [ 'some_filetype' ] } ) } ), 'event_name': 'FileReadyToParse', 'tag_files': has_item( PathToTestFile( 'uni¢𐍈d€', 'tags' ) ) } ), 'event_notification' ) ) @patch( 'ycm.youcompleteme.YouCompleteMe._AddUltiSnipsDataIfNeeded' ) @YouCompleteMeInstance() def EventNotification_BufferVisit_BuildRequestForCurrentAndUnsavedBuffers_test( ycm, *args ): current_buffer_file = os.path.realpath( 'current_buffer' ) current_buffer = VimBuffer( name = current_buffer_file, number = 1, contents = [ 'current_buffer_contents' ], filetype = 'some_filetype', modified = False ) modified_buffer_file = os.path.realpath( 'modified_buffer' ) modified_buffer = VimBuffer( name = modified_buffer_file, number = 2, contents = [ 'modified_buffer_contents' ], filetype = 'some_filetype', modified = True ) unmodified_buffer_file = os.path.realpath( 'unmodified_buffer' ) unmodified_buffer = VimBuffer( name = unmodified_buffer_file, number = 3, contents = [ 'unmodified_buffer_contents' ], filetype = 'some_filetype', modified = False ) with patch( 'ycm.client.base_request.BaseRequest.' 'PostDataToHandlerAsync' ) as post_data_to_handler_async: with MockVimBuffers( [ current_buffer, modified_buffer, unmodified_buffer ], current_buffer, ( 3, 5 ) ): ycm.OnBufferVisit() assert_that( # Positional arguments passed to PostDataToHandlerAsync. post_data_to_handler_async.call_args[ 0 ], contains( has_entries( { 'filepath': current_buffer_file, 'line_num': 3, 'column_num': 6, 'file_data': has_entries( { current_buffer_file: has_entries( { 'contents': 'current_buffer_contents\n', 'filetypes': [ 'some_filetype' ] } ), modified_buffer_file: has_entries( { 'contents': 'modified_buffer_contents\n', 'filetypes': [ 'some_filetype' ] } ) } ), 'event_name': 'BufferVisit' } ), 'event_notification' ) ) @YouCompleteMeInstance() def EventNotification_BufferUnload_BuildRequestForDeletedAndUnsavedBuffers_test( ycm ): current_buffer_file = os.path.realpath( 'current_buffer' ) current_buffer = VimBuffer( name = current_buffer_file, number = 1, contents = [ 'current_buffer_contents' ], filetype = 'some_filetype', modified = True ) deleted_buffer_file = os.path.realpath( 'deleted_buffer' ) deleted_buffer = VimBuffer( name = deleted_buffer_file, number = 2, contents = [ 'deleted_buffer_contents' ], filetype = 'some_filetype', modified = False ) with patch( 'ycm.client.base_request.BaseRequest.' 'PostDataToHandlerAsync' ) as post_data_to_handler_async: with MockVimBuffers( [ current_buffer, deleted_buffer ], current_buffer ): ycm.OnBufferUnload( deleted_buffer_file ) assert_that( # Positional arguments passed to PostDataToHandlerAsync. post_data_to_handler_async.call_args[ 0 ], contains( has_entries( { 'filepath': deleted_buffer_file, 'line_num': 1, 'column_num': 1, 'file_data': has_entries( { current_buffer_file: has_entries( { 'contents': 'current_buffer_contents\n', 'filetypes': [ 'some_filetype' ] } ), deleted_buffer_file: has_entries( { 'contents': 'deleted_buffer_contents\n', 'filetypes': [ 'some_filetype' ] } ) } ), 'event_name': 'BufferUnload' } ), 'event_notification' ) )
unknown
codeparrot/codeparrot-clean
use bytes::BufMut; use std::future::poll_fn; use std::io; use std::pin::Pin; use tokio::io::AsyncRead; /// Read data from an `AsyncRead` into an implementer of the [`BufMut`] trait. /// /// [`BufMut`]: bytes::BufMut /// /// # Example /// /// ``` /// use bytes::{Bytes, BytesMut}; /// use tokio_stream as stream; /// use tokio::io::Result; /// use tokio_util::io::{StreamReader, read_buf}; /// # #[tokio::main(flavor = "current_thread")] /// # async fn main() -> std::io::Result<()> { /// /// // Create a reader from an iterator. This particular reader will always be /// // ready. /// let mut read = StreamReader::new(stream::iter(vec![Result::Ok(Bytes::from_static(&[0, 1, 2, 3]))])); /// /// let mut buf = BytesMut::new(); /// let mut reads = 0; /// /// loop { /// reads += 1; /// let n = read_buf(&mut read, &mut buf).await?; /// /// if n == 0 { /// break; /// } /// } /// /// // one or more reads might be necessary. /// assert!(reads >= 1); /// assert_eq!(&buf[..], &[0, 1, 2, 3]); /// # Ok(()) /// # } /// ``` pub async fn read_buf<R, B>(read: &mut R, buf: &mut B) -> io::Result<usize> where R: AsyncRead + Unpin, B: BufMut, { poll_fn(|cx| crate::util::poll_read_buf(Pin::new(read), cx, buf)).await }
rust
github
https://github.com/tokio-rs/tokio
tokio-util/src/io/read_buf.rs
# -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. from functools import partial import errno import sys try: import eventlet except ImportError: raise RuntimeError("You need eventlet installed to use this worker.") # validate the eventlet version if eventlet.version_info < (0, 9, 7): raise RuntimeError("You need eventlet >= 0.9.7") from eventlet import hubs, greenthread from eventlet.greenio import GreenSocket from eventlet.hubs import trampoline import greenlet from gunicorn.http.wsgi import sendfile as o_sendfile from gunicorn.workers.async import AsyncWorker def _eventlet_sendfile(fdout, fdin, offset, nbytes): while True: try: return o_sendfile(fdout, fdin, offset, nbytes) except OSError as e: if e.args[0] == errno.EAGAIN: trampoline(fdout, write=True) else: raise def _eventlet_serve(sock, handle, concurrency): """ Serve requests forever. This code is nearly identical to ``eventlet.convenience.serve`` except that it attempts to join the pool at the end, which allows for gunicorn graceful shutdowns. """ pool = eventlet.greenpool.GreenPool(concurrency) server_gt = eventlet.greenthread.getcurrent() while True: try: conn, addr = sock.accept() gt = pool.spawn(handle, conn, addr) gt.link(_eventlet_stop, server_gt, conn) conn, addr, gt = None, None, None except eventlet.StopServe: sock.close() pool.waitall() return def _eventlet_stop(client, server, conn): """ Stop a greenlet handling a request and close its connection. This code is lifted from eventlet so as not to depend on undocumented functions in the library. """ try: try: client.wait() finally: conn.close() except greenlet.GreenletExit: pass except Exception: greenthread.kill(server, *sys.exc_info()) def patch_sendfile(): from gunicorn.http import wsgi if o_sendfile is not None: setattr(wsgi, "sendfile", _eventlet_sendfile) class EventletWorker(AsyncWorker): def patch(self): hubs.use_hub() eventlet.monkey_patch(os=False) patch_sendfile() def init_process(self): self.patch() super(EventletWorker, self).init_process() def handle_quit(self, sig, frame): eventlet.spawn(super(EventletWorker, self).handle_quit, sig, frame) def timeout_ctx(self): return eventlet.Timeout(self.cfg.keepalive or None, False) def handle(self, listener, client, addr): if self.cfg.is_ssl: client = eventlet.wrap_ssl(client, server_side=True, **self.cfg.ssl_options) super(EventletWorker, self).handle(listener, client, addr) def run(self): acceptors = [] for sock in self.sockets: gsock = GreenSocket(sock) gsock.setblocking(1) hfun = partial(self.handle, gsock) acceptor = eventlet.spawn(_eventlet_serve, gsock, hfun, self.worker_connections) acceptors.append(acceptor) eventlet.sleep(0.0) while self.alive: self.notify() eventlet.sleep(1.0) self.notify() try: with eventlet.Timeout(self.cfg.graceful_timeout) as t: [a.kill(eventlet.StopServe()) for a in acceptors] [a.wait() for a in acceptors] except eventlet.Timeout as te: if te != t: raise [a.kill() for a in acceptors]
unknown
codeparrot/codeparrot-clean
/*! An implementation of `grep-matcher`'s `Matcher` trait for Rust's regex engine. */ #![deny(missing_docs)] pub use crate::{ error::{Error, ErrorKind}, matcher::{RegexCaptures, RegexMatcher, RegexMatcherBuilder}, }; mod ast; mod ban; mod config; mod error; mod literal; mod matcher; mod non_matching; mod strip;
rust
github
https://github.com/BurntSushi/ripgrep
crates/regex/src/lib.rs
WIP ML Build Docker container for ML repositories (Tensorflow, JAX and XLA). This container branches off from /tensorflow/tools/tf_sig_build_dockerfiles/. However, since hermetic CUDA and hermetic Python is now available for Tensorflow, a lot of the requirements installed on the original container can be removed to reduce the footprint of the container and make it more reusable across different ML repositories.
unknown
github
https://github.com/tensorflow/tensorflow
ci/official/containers/ml_build/README.md
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Jiangge Zhang <tonyseek@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} DOCUMENTATION = """ module: bearychat short_description: Send BearyChat notifications description: - The M(bearychat) module sends notifications to U(https://bearychat.com) via the Incoming Robot integration. version_added: "2.4" author: "Jiangge Zhang (@tonyseek)" options: url: description: - BearyChat WebHook URL. This authenticates you to the bearychat service. It looks like C(https://hook.bearychat.com/=ae2CF/incoming/e61bd5c57b164e04b11ac02e66f47f60). required: true text: description: - Message to send. markdown: description: - If C(yes), text will be parsed as markdown. default: 'yes' type: bool channel: description: - Channel to send the message to. If absent, the message goes to the default channel selected by the I(url). attachments: description: - Define a list of attachments. For more information, see https://github.com/bearyinnovative/bearychat-tutorial/blob/master/robots/incoming.md#attachments """ EXAMPLES = """ - name: Send notification message via BearyChat local_action: module: bearychat url: | https://hook.bearychat.com/=ae2CF/incoming/e61bd5c57b164e04b11ac02e66f47f60 text: "{{ inventory_hostname }} completed" - name: Send notification message via BearyChat all options local_action: module: bearychat url: | https://hook.bearychat.com/=ae2CF/incoming/e61bd5c57b164e04b11ac02e66f47f60 text: "{{ inventory_hostname }} completed" markdown: no channel: "#ansible" attachments: - title: "Ansible on {{ inventory_hostname }}" text: "May the Force be with you." color: "#ffffff" images: - http://example.com/index.png """ RETURN = """ msg: description: execution result returned: success type: str sample: "OK" """ try: from ansible.module_utils.six.moves.urllib.parse import urlparse, urlunparse HAS_URLPARSE = True except Exception: HAS_URLPARSE = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.urls import fetch_url def build_payload_for_bearychat(module, text, markdown, channel, attachments): payload = {} if text is not None: payload['text'] = text if markdown is not None: payload['markdown'] = markdown if channel is not None: payload['channel'] = channel if attachments is not None: payload.setdefault('attachments', []).extend( build_payload_for_bearychat_attachment( module, item.get('title'), item.get('text'), item.get('color'), item.get('images')) for item in attachments) payload = 'payload=%s' % module.jsonify(payload) return payload def build_payload_for_bearychat_attachment(module, title, text, color, images): attachment = {} if title is not None: attachment['title'] = title if text is not None: attachment['text'] = text if color is not None: attachment['color'] = color if images is not None: target_images = attachment.setdefault('images', []) if not isinstance(images, (list, tuple)): images = [images] for image in images: if isinstance(image, dict) and 'url' in image: image = {'url': image['url']} elif hasattr(image, 'startswith') and image.startswith('http'): image = {'url': image} else: module.fail_json( msg="BearyChat doesn't have support for this kind of " "attachment image") target_images.append(image) return attachment def do_notify_bearychat(module, url, payload): response, info = fetch_url(module, url, data=payload) if info['status'] != 200: url_info = urlparse(url) obscured_incoming_webhook = urlunparse( (url_info.scheme, url_info.netloc, '[obscured]', '', '', '')) module.fail_json( msg=" failed to send %s to %s: %s" % ( payload, obscured_incoming_webhook, info['msg'])) def main(): module = AnsibleModule(argument_spec={ 'url': dict(type='str', required=True, no_log=True), 'text': dict(type='str'), 'markdown': dict(default='yes', type='bool'), 'channel': dict(type='str'), 'attachments': dict(type='list'), }) if not HAS_URLPARSE: module.fail_json(msg='urlparse is not installed') url = module.params['url'] text = module.params['text'] markdown = module.params['markdown'] channel = module.params['channel'] attachments = module.params['attachments'] payload = build_payload_for_bearychat( module, text, markdown, channel, attachments) do_notify_bearychat(module, url, payload) module.exit_json(msg="OK") if __name__ == '__main__': main()
unknown
codeparrot/codeparrot-clean
#include <c10/util/LeftRight.h>
cpp
github
https://github.com/pytorch/pytorch
c10/util/LeftRight.cpp
# Copyright (c) 2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import operator from nova.openstack.common import jsonutils from nova.scheduler import filters class JsonFilter(filters.BaseHostFilter): """Host Filter to allow simple JSON-based grammar for selecting hosts. """ def _op_compare(self, args, op): """Returns True if the specified operator can successfully compare the first item in the args with all the rest. Will return False if only one item is in the list. """ if len(args) < 2: return False if op is operator.contains: bad = args[0] not in args[1:] else: bad = [arg for arg in args[1:] if not op(args[0], arg)] return not bool(bad) def _equals(self, args): """First term is == all the other terms.""" return self._op_compare(args, operator.eq) def _less_than(self, args): """First term is < all the other terms.""" return self._op_compare(args, operator.lt) def _greater_than(self, args): """First term is > all the other terms.""" return self._op_compare(args, operator.gt) def _in(self, args): """First term is in set of remaining terms.""" return self._op_compare(args, operator.contains) def _less_than_equal(self, args): """First term is <= all the other terms.""" return self._op_compare(args, operator.le) def _greater_than_equal(self, args): """First term is >= all the other terms.""" return self._op_compare(args, operator.ge) def _not(self, args): """Flip each of the arguments.""" return [not arg for arg in args] def _or(self, args): """True if any arg is True.""" return any(args) def _and(self, args): """True if all args are True.""" return all(args) commands = { '=': _equals, '<': _less_than, '>': _greater_than, 'in': _in, '<=': _less_than_equal, '>=': _greater_than_equal, 'not': _not, 'or': _or, 'and': _and, } def _parse_string(self, string, host_state): """Strings prefixed with $ are capability lookups in the form '$variable' where 'variable' is an attribute in the HostState class. If $variable is a dictionary, you may use: $variable.dictkey """ if not string: return None if not string.startswith("$"): return string path = string[1:].split(".") obj = getattr(host_state, path[0], None) if obj is None: return None for item in path[1:]: obj = obj.get(item, None) if obj is None: return None return obj def _process_filter(self, query, host_state): """Recursively parse the query structure.""" if not query: return True cmd = query[0] method = self.commands[cmd] cooked_args = [] for arg in query[1:]: if isinstance(arg, list): arg = self._process_filter(arg, host_state) elif isinstance(arg, basestring): arg = self._parse_string(arg, host_state) if arg is not None: cooked_args.append(arg) result = method(self, cooked_args) return result def host_passes(self, host_state, filter_properties): """Return a list of hosts that can fulfill the requirements specified in the query. """ try: query = filter_properties['scheduler_hints']['query'] except KeyError: query = None if not query: return True # NOTE(comstud): Not checking capabilities or service for # enabled/disabled so that a provided json filter can decide result = self._process_filter(jsonutils.loads(query), host_state) if isinstance(result, list): # If any succeeded, include the host result = any(result) if result: # Filter it out. return True return False
unknown
codeparrot/codeparrot-clean
//===--- DominatorTree.swift - the dominator tree -------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SIL import OptimizerBridging struct DominatorTree { let bridged: BridgedDomTree func getChildren(of block: BasicBlock) -> DomChildren { return DomChildren(bridgedDomTree: bridged, bb: block) } /// Returns the immediate dominator of `block`, i.e. the parent of `block` in the tree. func getImmediateDominator(of block: BasicBlock) -> BasicBlock? { bridged.getImmediateDominator(block.bridged).block } /// Returns the sub-dominator-tree of `startBlock` in dominance order. /// /// Blocks - including their sub-tree - are only included if `filter` returns true. func getDominanceOrder(startingAt startBlock: BasicBlock, filter: (BasicBlock) -> Bool) -> [BasicBlock] { guard filter(startBlock) else { return [] } var order = [BasicBlock]() order.append(startBlock) var idx = 0 while idx < order.count { let block = order[idx] idx += 1 order.append(contentsOf: getChildren(of: block).lazy.filter(filter)) } return order } } struct DomChildren: BridgedRandomAccessCollection { private let bridgedDomTree: BridgedDomTree private let block: BasicBlock let count: Int var startIndex: Int { return 0 } var endIndex: Int { return count } init(bridgedDomTree: BridgedDomTree, bb: BasicBlock) { self.bridgedDomTree = bridgedDomTree self.block = bb self.count = bridgedDomTree.getNumberOfChildren(bb.bridged) } subscript(_ index: Int) -> BasicBlock { assert(index >= startIndex && index < endIndex) return bridgedDomTree.getChildAt(block.bridged, index).block } } extension BasicBlock { func dominates(_ other: BasicBlock, _ domTree: DominatorTree) -> Bool { domTree.bridged.dominates(self.bridged, other.bridged) } func strictlyDominates(_ other: BasicBlock, _ domTree: DominatorTree) -> Bool { dominates(other, domTree) && self != other } } //===--------------------------------------------------------------------===// // Tests //===--------------------------------------------------------------------===// let domtreeTest = FunctionTest("domtree") { function, arguments, context in let domtree = context.dominatorTree let startBlock = arguments.takeBlock() let order = domtree.getDominanceOrder(startingAt: startBlock, filter: { block in if let sli = block.instructions.first! as? StringLiteralInst, sli.value == "skip" { return false } return true }) print("order: \(order.map { $0.index })") }
swift
github
https://github.com/apple/swift
SwiftCompilerSources/Sources/Optimizer/Analysis/DominatorTree.swift
# encoding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( clean_html, xpath_text, int_or_none, ) class NTVRuIE(InfoExtractor): IE_NAME = 'ntv.ru' _VALID_URL = r'http://(?:www\.)?ntv\.ru/(?P<id>.+)' _TESTS = [ { 'url': 'http://www.ntv.ru/novosti/863142/', 'md5': 'ba7ea172a91cb83eb734cad18c10e723', 'info_dict': { 'id': '746000', 'ext': 'mp4', 'title': 'Командующий Черноморским флотом провел переговоры в штабе ВМС Украины', 'description': 'Командующий Черноморским флотом провел переговоры в штабе ВМС Украины', 'thumbnail': 're:^http://.*\.jpg', 'duration': 136, }, }, { 'url': 'http://www.ntv.ru/video/novosti/750370/', 'md5': 'adecff79691b4d71e25220a191477124', 'info_dict': { 'id': '750370', 'ext': 'mp4', 'title': 'Родные пассажиров пропавшего Boeing не верят в трагический исход', 'description': 'Родные пассажиров пропавшего Boeing не верят в трагический исход', 'thumbnail': 're:^http://.*\.jpg', 'duration': 172, }, }, { 'url': 'http://www.ntv.ru/peredacha/segodnya/m23700/o232416', 'md5': '82dbd49b38e3af1d00df16acbeab260c', 'info_dict': { 'id': '747480', 'ext': 'mp4', 'title': '«Сегодня». 21 марта 2014 года. 16:00', 'description': '«Сегодня». 21 марта 2014 года. 16:00', 'thumbnail': 're:^http://.*\.jpg', 'duration': 1496, }, }, { 'url': 'http://www.ntv.ru/kino/Koma_film', 'md5': 'f825770930937aa7e5aca0dc0d29319a', 'info_dict': { 'id': '1007609', 'ext': 'mp4', 'title': 'Остросюжетный фильм «Кома»', 'description': 'Остросюжетный фильм «Кома»', 'thumbnail': 're:^http://.*\.jpg', 'duration': 5592, }, }, { 'url': 'http://www.ntv.ru/serial/Delo_vrachey/m31760/o233916/', 'md5': '9320cd0e23f3ea59c330dc744e06ff3b', 'info_dict': { 'id': '751482', 'ext': 'mp4', 'title': '«Дело врачей»: «Деревце жизни»', 'description': '«Дело врачей»: «Деревце жизни»', 'thumbnail': 're:^http://.*\.jpg', 'duration': 2590, }, }, ] _VIDEO_ID_REGEXES = [ r'<meta property="og:url" content="http://www\.ntv\.ru/video/(\d+)', r'<video embed=[^>]+><id>(\d+)</id>', r'<video restriction[^>]+><key>(\d+)</key>', ] def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) video_id = self._html_search_regex(self._VIDEO_ID_REGEXES, webpage, 'video id') player = self._download_xml( 'http://www.ntv.ru/vi%s/' % video_id, video_id, 'Downloading video XML') title = clean_html(xpath_text(player, './data/title', 'title', fatal=True)) description = clean_html(xpath_text(player, './data/description', 'description')) video = player.find('./data/video') video_id = xpath_text(video, './id', 'video id') thumbnail = xpath_text(video, './splash', 'thumbnail') duration = int_or_none(xpath_text(video, './totaltime', 'duration')) view_count = int_or_none(xpath_text(video, './views', 'view count')) token = self._download_webpage( 'http://stat.ntv.ru/services/access/token', video_id, 'Downloading access token') formats = [] for format_id in ['', 'hi', 'webm']: file_ = video.find('./%sfile' % format_id) if file_ is None: continue size = video.find('./%ssize' % format_id) formats.append({ 'url': 'http://media2.ntv.ru/vod/%s&tok=%s' % (file_.text, token), 'filesize': int_or_none(size.text if size is not None else None), }) self._sort_formats(formats) return { 'id': video_id, 'title': title, 'description': description, 'thumbnail': thumbnail, 'duration': duration, 'view_count': view_count, 'formats': formats, }
unknown
codeparrot/codeparrot-clean
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utilities for dealing with the python unittest module.""" import fnmatch import sys import unittest class _TextTestResult(unittest._TextTestResult): """A test result class that can print formatted text results to a stream. Results printed in conformance with gtest output format, like: [ RUN ] autofill.AutofillTest.testAutofillInvalid: "test desc." [ OK ] autofill.AutofillTest.testAutofillInvalid [ RUN ] autofill.AutofillTest.testFillProfile: "test desc." [ OK ] autofill.AutofillTest.testFillProfile [ RUN ] autofill.AutofillTest.testFillProfileCrazyCharacters: "Test." [ OK ] autofill.AutofillTest.testFillProfileCrazyCharacters """ def __init__(self, stream, descriptions, verbosity): unittest._TextTestResult.__init__(self, stream, descriptions, verbosity) self._fails = set() def _GetTestURI(self, test): return '%s.%s.%s' % (test.__class__.__module__, test.__class__.__name__, test._testMethodName) def getDescription(self, test): return '%s: "%s"' % (self._GetTestURI(test), test.shortDescription()) def startTest(self, test): unittest.TestResult.startTest(self, test) self.stream.writeln('[ RUN ] %s' % self.getDescription(test)) def addSuccess(self, test): unittest.TestResult.addSuccess(self, test) self.stream.writeln('[ OK ] %s' % self._GetTestURI(test)) def addError(self, test, err): unittest.TestResult.addError(self, test, err) self.stream.writeln('[ ERROR ] %s' % self._GetTestURI(test)) self._fails.add(self._GetTestURI(test)) def addFailure(self, test, err): unittest.TestResult.addFailure(self, test, err) self.stream.writeln('[ FAILED ] %s' % self._GetTestURI(test)) self._fails.add(self._GetTestURI(test)) def getRetestFilter(self): return ':'.join(self._fails) class TextTestRunner(unittest.TextTestRunner): """Test Runner for displaying test results in textual format. Results are displayed in conformance with google test output. """ def __init__(self, verbosity=1): unittest.TextTestRunner.__init__(self, stream=sys.stderr, verbosity=verbosity) def _makeResult(self): return _TextTestResult(self.stream, self.descriptions, self.verbosity) def GetTestsFromSuite(suite): """Returns all the tests from a given test suite.""" tests = [] for x in suite: if isinstance(x, unittest.TestSuite): tests += GetTestsFromSuite(x) else: tests += [x] return tests def GetTestNamesFromSuite(suite): """Returns a list of every test name in the given suite.""" return map(lambda x: GetTestName(x), GetTestsFromSuite(suite)) def GetTestName(test): """Gets the test name of the given unittest test.""" return '.'.join([test.__class__.__module__, test.__class__.__name__, test._testMethodName]) def FilterTestSuite(suite, gtest_filter): """Returns a new filtered tests suite based on the given gtest filter. See http://code.google.com/p/googletest/wiki/AdvancedGuide for gtest_filter specification. """ return unittest.TestSuite(FilterTests(GetTestsFromSuite(suite), gtest_filter)) def FilterTests(all_tests, gtest_filter): """Returns a filtered list of tests based on the given gtest filter. See http://code.google.com/p/googletest/wiki/AdvancedGuide for gtest_filter specification. """ pattern_groups = gtest_filter.split('-') positive_patterns = pattern_groups[0].split(':') negative_patterns = None if len(pattern_groups) > 1: negative_patterns = pattern_groups[1].split(':') tests = [] for test in all_tests: test_name = GetTestName(test) # Test name must by matched by one positive pattern. for pattern in positive_patterns: if fnmatch.fnmatch(test_name, pattern): break else: continue # Test name must not be matched by any negative patterns. for pattern in negative_patterns or []: if fnmatch.fnmatch(test_name, pattern): break else: tests += [test] return tests
unknown
codeparrot/codeparrot-clean
use displaydoc::Display; #[derive(Display)] enum EmptyInside {} static_assertions::assert_impl_all!(EmptyInside: core::fmt::Display);
rust
github
https://github.com/nodejs/node
deps/crates/vendor/displaydoc/tests/variantless.rs
#!/usr/bin/env python3 # ===--- convertToJSON.py ------------------------------------------------===// # # This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See https://swift.org/LICENSE.txt for license information # See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors # # ===---------------------------------------------------------------------===// # This script converts results from pre-commit benchmark tests to JSON. # Usage: PrecommitBench_O | convertToJSON.py # # Input example: # #,TEST,SAMPLES,MIN(ms),MAX(ms),MEAN(ms),SD(ms),MEDIAN(ms) # 1,2Sum,1,1318,1318,1318,0,1318 # 2,Ackermann,1,805,805,805,0,805 # # Totals,2,2123,2123,2123,0,0 # # Output for this input: # { # "Machine": {}, # "Run": {}, # "Tests": [ # { # "Data": [ # 1318 # ], # "Info": {}, # "Name": [ # "2Sum" # ] # }, # { # "Data": [ # 805 # ], # "Info": {}, # "Name": [ # "Ackermann" # ] # }, # { # "Data": [ # 2123 # ], # "Info": {}, # "Name": [ # "Totals" # ] # } # ] # } import json import re import sys # Parse lines like this # #,TEST,SAMPLES,MIN(ms),MAX(ms),MEAN(ms),SD(ms),MEDIAN(ms) SCORERE = re.compile(r"(\d+),[ \t]*(\w+),[ \t]*([\d.]+),[ \t]*([\d.]+)") # The Totals line would be parsed like this. TOTALRE = re.compile(r"()(Totals),[ \t]*([\d.]+),[ \t]*([\d.]+)") KEYGROUP = 2 VALGROUP = 4 if __name__ == "__main__": data = {} data["Tests"] = [] data["Machine"] = {} data["Run"] = {} for line in sys.stdin: m = SCORERE.match(line) if not m: m = TOTALRE.match(line) if not m: continue test = {} test["Data"] = [int(m.group(VALGROUP))] test["Info"] = {} test["Name"] = [m.group(KEYGROUP)] data["Tests"].append(test) print(json.dumps(data, sort_keys=True, indent=4))
python
github
https://github.com/apple/swift
benchmark/utils/convertToJSON.py
# -*- coding: utf-8 -*- # Copyright (c) 2014, 2015 Mitch Garnaat # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from botocore.exceptions import ClientError import kappa.awsclient import kappa.log LOG = logging.getLogger(__name__) class RestApi(object): def __init__(self, context, config): self._context = context self._config = config self._apigateway_client = kappa.awsclient.create_client( 'apigateway', context.session) self._api = None self._resources = None self._resource = None @property def arn(self): _, _, _, region, account, _ = self._context.function.arn.split(':', 5) arn = 'arn:aws:execute-api:{}:{}:{}/*/*/{}'.format( region, account, self.api_id, self.resource_name) return arn @property def api_name(self): return self._config['name'] @property def description(self): return self._config['description'] @property def resource_name(self): return self._config['resource']['name'] @property def parent_resource(self): return self._config['resource']['parent'] @property def full_path(self): parts = self.parent_resource.split('/') parts.append(self.resource_name) return '/'.join(parts) @property def api_id(self): api = self._get_api() return api.get('id') @property def resource_id(self): resources = self._get_resources() return resources.get(self.full_path).get('id') def _get_api(self): if self._api is None: try: response = self._apigateway_client.call( 'get_rest_apis') LOG.debug(response) for item in response['items']: if item['name'] == self.api_name: self._api = item except Exception: LOG.exception('Error finding restapi') return self._api def _get_resources(self): if self._resources is None: try: response = self._apigateway_client.call( 'get_resources', restApiId=self.api_id) LOG.debug(response) self._resources = {} for item in response['items']: self._resources[item['path']] = item except Exception: LOG.exception('Unable to find resources for: %s', self.api_name) return self._resources def create_restapi(self): if not self.api_exists(): LOG.info('creating restapi %s', self.api_name) try: response = self._apigateway_client.call( 'create_rest_api', name=self.api_name, description=self.description) LOG.debug(response) except Exception: LOG.exception('Unable to create new restapi') def create_resource_path(self): path = self.full_path parts = path.split('/') resources = self._get_resources() parent = None build_path = [] for part in parts: LOG.debug('part=%s', part) build_path.append(part) LOG.debug('build_path=%s', build_path) full_path = '/'.join(build_path) LOG.debug('full_path=%s', full_path) if full_path is '': parent = resources['/'] else: if full_path not in resources and parent: try: response = self._apigateway_client.call( 'create_resource', restApiId=self.api_id, parentId=parent['id'], pathPart=part) LOG.debug(response) resources[full_path] = response except Exception: LOG.exception('Unable to create new resource') parent = resources[full_path] self._item = resources[path] def create_method(self, method, config): LOG.info('creating method: %s', method) try: response = self._apigateway_client.call( 'put_method', restApiId=self.api_id, resourceId=self.resource_id, httpMethod=method, authorizationType=config.get('authorization_type'), apiKeyRequired=config.get('apikey_required', False) ) LOG.debug(response) LOG.debug('now create integration') uri = 'arn:aws:apigateway:{}:'.format( self._apigateway_client.region_name) uri += 'lambda:path/2015-03-31/functions/' uri += self._context.function.arn uri += ':${stageVariables.environment}/invocations' LOG.debug(uri) response = self._apigateway_client.call( 'put_integration', restApiId=self.api_id, resourceId=self.resource_id, httpMethod=method, integrationHttpMethod=method, type='AWS', uri=uri ) except Exception: LOG.exception('Unable to create integration: %s', method) def create_deployment(self): LOG.info('creating a deployment for %s to stage: %s', self.api_name, self._context.environment) try: response = self._apigateway_client.call( 'create_deployment', restApiId=self.api_id, stageName=self._context.environment ) LOG.debug(response) LOG.info('Now deployed to: %s', self.deployment_uri) except Exception: LOG.exception('Unable to create a deployment') def create_methods(self): resource_config = self._config['resource'] for method in resource_config.get('methods', dict()): if not self.method_exists(method): method_config = resource_config['methods'][method] self.create_method(method, method_config) def api_exists(self): return self._get_api() def resource_exists(self): resources = self._get_resources() return resources.get(self.full_path) def method_exists(self, method): exists = False resource = self.resource_exists() if resource: methods = resource.get('resourceMethods') if methods: for method_name in methods: if method_name == method: exists = True return exists def find_parent_resource_id(self): parent_id = None resources = self._get_resources() for item in resources: if item['path'] == self.parent: parent_id = item['id'] return parent_id def api_update(self): LOG.info('updating restapi %s', self.api_name) def resource_update(self): LOG.info('updating resource %s', self.full_path) def add_permission(self): LOG.info('Adding permission for APIGateway to call function') self._context.function.add_permission( action='lambda:InvokeFunction', principal='apigateway.amazonaws.com', source_arn=self.arn) def deploy(self): if self.api_exists(): self.api_update() else: self.create_restapi() if self.resource_exists(): self.resource_update() else: self.create_resource_path() self.create_methods() self.add_permission() def delete(self): LOG.info('deleting resource %s', self.resource_name) try: response = self._apigateway_client.call( 'delete_resource', restApiId=self.api_id, resourceId=self.resource_id) LOG.debug(response) except ClientError: LOG.exception('Unable to delete resource %s', self.resource_name) return response def status(self): try: response = self._apigateway_client.call( 'delete_', FunctionName=self.name) LOG.debug(response) except ClientError: LOG.exception('function %s not found', self.name) response = None return response
unknown
codeparrot/codeparrot-clean
# Copyright (c) 2008-2009 Citrix Systems Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 2 only. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") from XSConsoleStandard import * class ClaimSRDialogue(Dialogue): def __init__(self): Dialogue.__init__(self) self.deviceToErase = None self.srName = None self.srSize = None self.typeChoice = 'SRONLY' # Default for HD installations self.ChangeState('INITIAL') def DeviceString(self, inDevice): retVal = "%-6.6s%-46.46s%20.20s" % ( FirstValue(inDevice.bus, '')[:6], FirstValue(inDevice.name, '')[:46], SizeUtils.DiskSizeString(inDevice.size)[:20] ) return retVal def BuildPaneBase(self): pane = self.NewPane(DialoguePane(self.parent)) pane.TitleSet(Lang("Claim Disk As Storage Repository")) pane.AddBox() def BuildPaneINITIAL(self): self.BuildPaneBase() self.UpdateFields() def BuildPaneDEVICE(self): self.deviceList = FileUtils.SRDeviceList() self.BuildPaneBase() choiceDefs = [] for device in self.deviceList: choiceDefs.append(ChoiceDef(self.DeviceString(device), lambda: self.HandleDeviceChoice(self.deviceMenu.ChoiceIndex()) ) ) if len(choiceDefs) == 0: choiceDefs.append(ChoiceDef(Lang("<No devices available>", 70), None)) # 'Custom' manual choice disabled # choiceDefs.append(ChoiceDef(Lang("Specify a device manually", 70), lambda: self.HandleDeviceChoice(None) ) ) self.deviceMenu = Menu(self, None, Lang("Select Device"), choiceDefs) self.UpdateFields() def BuildPaneALREADYTHERE(self): self.BuildPaneBase() self.UpdateFields() def BuildPaneCUSTOM(self): self.BuildPaneBase() self.UpdateFields() def BuildPaneCONFIRM(self): self.BuildPaneBase() self.UpdateFields() def BuildPaneREBOOT(self): self.BuildPaneBase() self.UpdateFields() def BuildPaneCHOOSETYPE(self): self.typeMenu = Menu() self.typeMenu.AddChoice(name = Lang('Claim Disk for Storage Repository and XenServer Use'), onAction = self.HandleTypeChoice, handle = 'CLAIM' ) self.typeMenu.AddChoice(name = Lang('Use Disk As Storage Repository Only'), onAction = self.HandleTypeChoice, handle = 'SRONLY' ) self.BuildPaneBase() self.UpdateFields() def ChangeState(self, inState): self.state = inState getattr(self, 'BuildPane'+self.state)() # Despatch method named 'BuildPane'+self.state def UpdateFields(self): self.Pane().ResetPosition() getattr(self, 'UpdateFields'+self.state)() # Despatch method named 'UpdateFields'+self.state def UpdateFieldsINITIAL(self): pane = self.Pane() pane.ResetFields() pane.AddWarningField(Lang("WARNING")) pane.AddWrappedTextField(Lang("Once a disk is selected, this function will erase all information on that disk. Do you want to continue?")) pane.AddKeyHelpField( { Lang("<F8>") : Lang("Continue"), Lang("<Esc>") : Lang("Cancel") } ) def UpdateFieldsDEVICE(self): pane = self.Pane() pane.ResetFields() pane.AddTitleField(Lang("Select a disk to erase and claim as a Storage Repository.")) pane.AddMenuField(self.deviceMenu) pane.AddWrappedTextField(Lang('Sizes shown are in binary (1kB = 1024) and decimal (1kB = 1000) units.')) pane.AddKeyHelpField( { Lang("<Enter>") : Lang("OK"), Lang("<Esc>") : Lang("Cancel"), "<F5>" : Lang("Rescan") } ) def UpdateFieldsALREADYTHERE(self): pane = self.Pane() pane.ResetFields() pane.AddWarningField(Lang("WARNING")) pane.AddWrappedBoldTextField(Lang("A Storage Repository has already been created on this disk. " "Continuing will destroy all information in this Storage Repository. Would you like to continue?")) pane.NewLine() pane.AddStatusField(Lang("Current SR Name", 20), str(self.srName)) pane.AddKeyHelpField( { Lang("<F8>") : Lang("Continue"), Lang("<Esc>") : Lang("Cancel") } ) def UpdateFieldsCUSTOM(self): pane = self.Pane() pane.ResetFields() pane.AddTitleField(Lang("Enter the device name, e.g. /dev/sdb")) pane.AddInputField(Lang("Device Name", 16), '', 'device') pane.NewLine() pane.AddWrappedTextField(Lang("WARNING: No checks will be performed on this device before it is erased.")) pane.AddKeyHelpField( { Lang("<Enter>") : Lang("OK"), Lang("<Esc>") : Lang("Exit") } ) if pane.CurrentInput() is None: pane.InputIndexSet(0) def UpdateFieldsCHOOSETYPE(self): pane = self.Pane() pane.ResetFields() pane.AddTitleField(Lang("Please choose the assignment for this disk.")) pane.AddMenuField(self.typeMenu) pane.AddWrappedTextField(Lang('For disks that are not going to be removed, the Storage Repository and ' 'XenServer Use option is strongly recommended.')) pane.AddKeyHelpField( { Lang("<Enter>") : Lang("OK"), Lang("<Esc>") : Lang("Cancel") } ) def UpdateFieldsCONFIRM(self): pane = self.Pane() pane.ResetFields() pane.AddWrappedBoldTextField(Lang("Press <F8> to confirm that you want to erase all information on this disk and use it as a Storage Repository. Data currently on this disk cannot be recovered after this step.")) pane.NewLine() pane.AddWrappedBoldTextField(Lang("Device")) if isinstance(self.deviceToErase, Struct): pane.AddWrappedTextField(self.DeviceString(self.deviceToErase)) else: pane.AddWrappedTextField(str(self.deviceToErase)) pane.AddKeyHelpField( { Lang("<F8>") : Lang("Erase and Claim"), Lang("<Esc>") : Lang("Cancel") } ) def UpdateFieldsREBOOT(self): pane = self.Pane() pane.ResetFields() pane.AddWrappedBoldTextField(Lang("This server needs to reboot to use the new Storage Repository. Press <F8> to reboot now.")) pane.AddKeyHelpField( { Lang("<F8>") : Lang("Reboot"), Lang("<Esc>") : Lang("Cancel") } ) def HandleKey(self, inKey): handled = False if hasattr(self, 'HandleKey'+self.state): handled = getattr(self, 'HandleKey'+self.state)(inKey) if not handled and inKey == 'KEY_ESCAPE': Layout.Inst().PopDialogue() handled = True return handled def HandleKeyINITIAL(self, inKey): handled = False if inKey == 'KEY_F(8)': Layout.Inst().TransientBanner(Lang("Scanning...")) Data.Inst().Update() # Get current SR list self.ChangeState('DEVICE') handled = True return handled def HandleKeyDEVICE(self, inKey): handled = self.deviceMenu.HandleKey(inKey) if not handled and inKey == 'KEY_F(5)': Layout.Inst().PushDialogue(BannerDialogue( Lang("Rescanning..."))) Layout.Inst().Refresh() Layout.Inst().DoUpdate() Layout.Inst().PopDialogue() self.BuildPaneDEVICE() # Updates self.deviceList time.sleep(0.5) # Display rescanning box for a reasonable time Layout.Inst().Refresh() handled = True return handled def HandleKeyALREADYTHERE(self, inKey): handled = False if inKey == 'KEY_F(8)': XSLog('Disk claim will overwrite existing SR') if Data.Inst().state_on_usb_media(True): self.ChangeState('CHOOSETYPE') else: self.ChangeState('CONFIRM') handled = True return handled def HandleKeyCHOOSETYPE(self, inKey): return self.typeMenu.HandleKey(inKey) def HandleKeyCUSTOM(self, inKey): handled = True pane = self.Pane() if pane.CurrentInput() is None: pane.InputIndexSet(0) if inKey == 'KEY_ENTER': inputValues = pane.GetFieldValues() self.deviceToErase = Struct(device = inputValues['device']) self.ChangeState('CONFIRM') elif pane.CurrentInput().HandleKey(inKey): pass # Leave handled as True else: handled = False return handled def HandleKeyCONFIRM(self, inKey): handled = False if inKey == 'KEY_F(8)': self.DoAction() handled = True return handled def HandleKeyREBOOT(self, inKey): handled = False if inKey == 'KEY_F(8)': Layout.Inst().ExitBannerSet(Lang("Rebooting...")) Layout.Inst().ExitCommandSet('/sbin/shutdown -r now') XSLog('Disk claim initiated reboot') handled = True return handled def HandleDeviceChoice(self, inChoice): if inChoice is None: self.ChangeState('CUSTOM') else: self.deviceToErase = self.deviceList[inChoice] if self.IsKnownSROnDisk(self.deviceToErase.device): self.ChangeState('ALREADYTHERE') else: if Data.Inst().state_on_usb_media(True): self.ChangeState('CHOOSETYPE') else: self.ChangeState('CONFIRM') def HandleTypeChoice(self, inChoice): self.typeChoice = inChoice self.ChangeState('CONFIRM') def IsKnownSROnDisk(self, inDevice): retVal = False for pbd in Data.Inst().host.PBDs([]): device = pbd.get('device_config', {}).get('device', '') if Data.Inst().RemovePartitionSuffix(device) == inDevice: # This is the PBD we want to claim. Does it have an SR? srName = pbd.get('SR', {}).get('name_label', None) if srName is not None: self.srName = srName self.srSize = int(pbd.get('SR', {}).get('physical_size', 0)) retVal = True return retVal def DoAction(self): Layout.Inst().TransientBanner(Lang("Claiming and Configuring Disk...")) XSLog('Disk claim initiated for '+str(self.deviceToErase.device)) Data.Inst().CloseSession() # Disk claim restarts xapi, so close the session in Data.Inst() if self.typeChoice == 'SRONLY': pipe = ShellPipe( "/opt/xensource/libexec/delete-partitions-and-claim-disk", '--sr-only', self.deviceToErase.device) else: pipe = ShellPipe( "/opt/xensource/libexec/delete-partitions-and-claim-disk", self.deviceToErase.device) status = pipe.CallRC() time.sleep(4) # Allow xapi to pick up the new SR Data.Inst().Update() # Read information about the new SR if status != 0: output = "\n".join(pipe.AllOutput()) XSLogFailure("Disk claim failed", output) Layout.Inst().PopDialogue() Layout.Inst().PushDialogue(InfoDialogue(Lang("Disk Claim Failed"), output)) else: if self.typeChoice == 'SRONLY': Layout.Inst().PopDialogue() Layout.Inst().PushDialogue(InfoDialogue(Lang('Disk Claimed Successfully'))) else: XSLog('Requesting reboot after claiming disk') self.ChangeState('REBOOT') try: Data.Inst().SetPoolSRsFromDeviceIfNotSet(self.deviceToErase.device) except Exception, e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Disk claimed, but could not set as default SR: ") + Lang(e))) # Continue to reboot dialogue class XSFeatureClaimSR: @classmethod def StatusUpdateHandler(cls, inPane): data = Data.Inst() inPane.AddTitleField(Lang("Claim Local Disk As SR")) inPane.AddWrappedTextField(Lang("Local disks can be configured as Storage Repositories " "for use by virtual machines. Press <Enter> to list the disks available.")) inPane.AddKeyHelpField( { Lang("<Enter>") : Lang("Claim Disk As SR") }) @classmethod def ActivateHandler(cls): DialogueUtils.AuthenticatedOnly(lambda: Layout.Inst().PushDialogue(ClaimSRDialogue())) def Register(self): Importer.RegisterNamedPlugIn( self, 'CLAIM_SR', # Key of this plugin for replacement, etc. { 'menuname' : 'MENU_DISK', 'menupriority' : 600, 'menutext' : Lang('Claim Local Disk As SR') , 'statusupdatehandler' : self.StatusUpdateHandler, 'activatehandler' : self.ActivateHandler } ) # Register this plugin when module is imported XSFeatureClaimSR().Register()
unknown
codeparrot/codeparrot-clean
#!/bin/sh test_description='CRLF conversion' . ./test-lib.sh has_cr() { tr '\015' Q <"$1" | grep Q >/dev/null } test_expect_success setup ' git config core.autocrlf false && echo "one text" > .gitattributes && test_write_lines Hello world how are you >one && test_write_lines I am very very fine thank you >two && git add . && git commit -m initial && one=$(git rev-parse HEAD:one) && two=$(git rev-parse HEAD:two) && echo happy. ' test_expect_success 'eol=lf puts LFs in normalized file' ' rm -f .gitattributes tmp one two && git config core.eol lf && git read-tree --reset -u HEAD && ! has_cr one && ! has_cr two && onediff=$(git diff one) && twodiff=$(git diff two) && test -z "$onediff" && test -z "$twodiff" ' test_expect_success 'eol=crlf puts CRLFs in normalized file' ' rm -f .gitattributes tmp one two && git config core.eol crlf && git read-tree --reset -u HEAD && has_cr one && ! has_cr two && onediff=$(git diff one) && twodiff=$(git diff two) && test -z "$onediff" && test -z "$twodiff" ' test_expect_success 'autocrlf=true overrides eol=lf' ' rm -f .gitattributes tmp one two && git config core.eol lf && git config core.autocrlf true && git read-tree --reset -u HEAD && has_cr one && has_cr two && onediff=$(git diff one) && twodiff=$(git diff two) && test -z "$onediff" && test -z "$twodiff" ' test_expect_success 'autocrlf=true overrides unset eol' ' rm -f .gitattributes tmp one two && git config --unset-all core.eol && git config core.autocrlf true && git read-tree --reset -u HEAD && has_cr one && has_cr two && onediff=$(git diff one) && twodiff=$(git diff two) && test -z "$onediff" && test -z "$twodiff" ' test_expect_success NATIVE_CRLF 'eol native is crlf' ' rm -rf native_eol && mkdir native_eol && ( cd native_eol && printf "*.txt text\n" >.gitattributes && printf "one\r\ntwo\r\nthree\r\n" >filedos.txt && printf "one\ntwo\nthree\n" >fileunix.txt && git init && git config core.autocrlf false && git config core.eol native && git add filedos.txt fileunix.txt && git commit -m "first" && rm file*.txt && git reset --hard HEAD && has_cr filedos.txt && has_cr fileunix.txt ) ' test_done
unknown
github
https://github.com/git/git
t/t0026-eol-config.sh
# -*- coding: utf-8 -*- import re from module.plugins.Crypter import Crypter from module.plugins.hoster.MediafireCom import checkHTMLHeader from module.common.json_layer import json_loads class MediafireComFolder(Crypter): __name__ = "MediafireComFolder" __type__ = "crypter" __pattern__ = r"http://(\w*\.)*mediafire\.com/(folder/|\?sharekey=|\?\w{13}($|[/#]))" __version__ = "0.14" __description__ = """Mediafire.com Folder Plugin""" __author_name__ = ("zoidberg") __author_mail__ = ("zoidberg@mujmail.cz") FOLDER_KEY_PATTERN = r"var afI= '(\w+)';" FILE_URL_PATTERN = '<meta property="og:url" content="http://www.mediafire.com/\?(\w+)"/>' def decrypt(self, pyfile): new_links = [] url, result = checkHTMLHeader(pyfile.url) self.logDebug('Location (%d): %s' % (result, url)) if result == 0: # load and parse html html = self.load(pyfile.url) found = re.search(self.FILE_URL_PATTERN, html) if found: # file page new_links.append("http://www.mediafire.com/file/%s" % found.group(1)) else: # folder page found = re.search(self.FOLDER_KEY_PATTERN, html) if found: folder_key = found.group(1) self.logDebug("FOLDER KEY: %s" % folder_key) json_resp = json_loads(self.load("http://www.mediafire.com/api/folder/get_info.php?folder_key=%s&response_format=json&version=1" % folder_key)) #self.logInfo(json_resp) if json_resp['response']['result'] == "Success": for link in json_resp['response']['folder_info']['files']: new_links.append("http://www.mediafire.com/file/%s" % link['quickkey']) else: self.fail(json_resp['response']['message']) elif result == 1: self.offline() else: new_links.append(url) if new_links: self.core.files.addLinks(new_links, self.pyfile.package().id) else: self.fail('Could not extract any links')
unknown
codeparrot/codeparrot-clean
"""Simple reference counter implementations.""" import abc class BaseReferenceCounter(object): """Abstract base class for reference counters.""" __metaclass__ = abc.ABCMeta __slots__ = [] def inc(self, key): """Abstract increment interface. Args: key: Key whose reference counter shall be incremented. Returns: Number of references of key after increment. """ raise NotImplementedError def dec(self, key): """Abstract decrement interface. Args: key: Key whose reference counter shall be decremented. Returns: Number of references of key after decrement. """ raise NotImplementedError def get(self, key): """Abstract get interface. Args: key: Key whose reference counter shall be retrieved. Returns: Number of references of key. """ raise NotImplementedError class NoReferenceCounter(BaseReferenceCounter): """Non-counting reference counter, always returns 1 for any key. Can be used to disable reference counting where a reference counter is required. """ __slots__ = [] def inc(self, key): """Increment interface. Returns: 1 """ return 1 def dec(self, key): """Decrement interface. Returns: 1 """ return 1 def get(self, key): """Get interface. Returns: 1 """ return 1 class DatabaseReferenceCounter(BaseReferenceCounter): """Database-backed reference counter. Uses a given database to store reference counters. The reference counter of an element `key` is stored as follows: * If its value is 0, `key` is not stored in the database. * If its value is > 0, its int value is stored in the database under `key`. Args: database: Database object with a dict-like interface, i.e., implementing the operations __getitem__, __setitem__ and __delitem__. """ __slots__ = ['_database'] def __init__(self, database): super(DatabaseReferenceCounter, self).__init__() self._database = database def inc(self, key): """Incrementes reference counter of key. See :meth:`.BaseReferenceCounter.inc`. """ database = self._database database[key] = new_count = ( database[key] if key in database else 0) + 1 return new_count def dec(self, key): """Decrementes reference counter of key. See :meth:`.BaseReferenceCounter.dec`. """ database = self._database new_count = database[key] - 1 if new_count == 0: del database[key] else: database[key] = new_count return new_count def get(self, key): """Gets reference counter of key. See :meth:`.BaseReferenceCounter.get`. """ database = self._database if key in database: return database[key] else: return 0 class KeySuffixDatabaseReferenceCounter(DatabaseReferenceCounter): """Database-backed reference counter. Similar to :class:`.DatabaseReferenceCounter`, but the reference counter of a `key` is not stored directly under `key`, but under `key` || `suffix`. Args: database: Database object with a dict-like interface, i.e., implementing the operations __getitem__, __setitem__ and __delitem__. suffix: Suffix for keys. """ __slots__ = ['_suffix'] def __init__(self, database, suffix): super(KeySuffixDatabaseReferenceCounter, self).__init__(database) self._suffix = suffix def inc(self, key): """Incrementes reference counter of key. See :meth:`.DatabaseReferenceCounter.inc`. """ return DatabaseReferenceCounter.inc(self, key + self._suffix) def dec(self, key): """Decrementes reference counter of key. See :meth:`.DatabaseReferenceCounter.dec`. """ return DatabaseReferenceCounter.dec(self, key + self._suffix) def get(self, key): """Gets reference counter of key. See :meth:`.DatabaseReferenceCounter.get`. """ return DatabaseReferenceCounter.get(self, key + self._suffix)
unknown
codeparrot/codeparrot-clean
# -*- coding: UTF-8 -*- ####################################################################### # ---------------------------------------------------------------------------- # "THE BEER-WARE LICENSE" (Revision 42): # @tantrumdev wrote this file. As long as you retain this notice you # can do whatever you want with this stuff. If we meet some day, and you think # this stuff is worth it, you can buy me a beer in return. - Muad'Dib # ---------------------------------------------------------------------------- ####################################################################### # Addon Name: Placenta # Addon id: plugin.video.placenta # Addon Provider: Mr.Blamo def get(version): try: import xbmc,xbmcgui,xbmcaddon,xbmcvfs f = xbmcvfs.File(xbmcaddon.Addon().getAddonInfo('changelog')) text = f.read() ; f.close() label = '%s - %s' % (xbmc.getLocalizedString(24054), xbmcaddon.Addon().getAddonInfo('name')) id = 10147 xbmc.executebuiltin('ActivateWindow(%d)' % id) xbmc.sleep(100) win = xbmcgui.Window(id) retry = 50 while (retry > 0): try: xbmc.sleep(10) win.getControl(1).setLabel(label) win.getControl(5).setText(text) retry = 0 except: retry -= 1 return '1' except: return '1'
unknown
codeparrot/codeparrot-clean
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c), meiliu@fusionlayer.com, 2017 # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. from __future__ import (absolute_import, division, print_function) __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = """ module: infinity short_description: "manage Infinity IPAM using Rest API" description: - "Manage Infinity IPAM using REST API" version_added: "2.4" author: - "Meirong Liu" options: server_ip: description: - Infinity server_ip with IP address required: true username: description: - Username to access Infinity - The user must have Rest API privileges required: true password: description: - Infinity password required: true action: description: - Action to perform required: true choices: - reserve_next_available_ip - release_ip - delete_network - add_network - reserve_network - release_network - get_network_id network_id: description: - Network ID default: '' ip_address: description: - IP Address for a reservation or a release default: '' network_address: description: - Network address with CIDR format (e.g., 192.168.310.0) required: false default: "" network_size: description: - Network bitmask (e.g. 255.255.255.220) or CIDR format (e.g., /26) default: '' network_name: description: - The name of a network default: '' network_location: description: - the parent network id for a given network default: -1 network_type: description: - Network type defined by Infinity choices: - lan - shared_lan - supernet default: "lan" network_family: description: - Network family defined by Infinity, e.g. IPv4, IPv6 and Dual stack choices: - 4 - 6 - dual default: "4" """ EXAMPLES = """ --- - hosts: localhost connection: local strategy: debug tasks: - name: Reserve network into Infinity IPAM infinity: server_ip: "80.75.107.12" username: "username" password: "password" action: "reserve_network" network_name: "reserve_new_ansible_network" network_family: "4" network_type: 'lan' network_id: "1201" network_size: "/28" register: infinity """ RETURN = """ network_id: description: id for a given network returned: success type: string sample: '1501' ip_info: description: when reserve next available ip address from a network, the ip address info ) is returned. returned: success type: string sample: '{"address": "192.168.10.3", "hostname": "", "FQDN": "", "domainname": "", "id": 3229}' network_info: description: when reserving a LAN network from a Infinity supernet by providing network_size, the information about the reserved network is returned. returned: success type: string sample: {"network_address": "192.168.10.32/28","network_family": "4", "network_id": 3102, "network_size": null,"description": null,"network_location": "3085", "ranges": { "id": 0, "name": null,"first_ip": null,"type": null,"last_ip": null}, "network_type": "lan","network_name": "'reserve_new_ansible_network'"} """ from ansible.module_utils.basic import json from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.urls import open_url class Infinity(object): """ Class for manage REST API calls with the Infinity. """ def __init__(self, module, server_ip, username, password): self.module = module self.auth_user = username self.auth_pass = password self.base_url = "https://%s/rest/v1/" % (str(server_ip)) def _get_api_call_ansible_handler( self, method='get', resource_url='', stat_codes=None, params=None, payload_data=None): """ Perform the HTTPS request by using anible get/delete method """ stat_codes = [200] if stat_codes is None else stat_codes request_url = str(self.base_url) + str(resource_url) response = None headers = {'Content-Type': 'application/json'} if not request_url: self.module.exit_json( msg="When sending Rest api call , the resource URL is empty, please check.") if payload_data and not isinstance(payload_data, str): payload_data = json.dumps(payload_data) response_raw = open_url( str(request_url), method=method, timeout=20, headers=headers, url_username=self.auth_user, url_password=self.auth_pass, validate_certs=False, force_basic_auth=True, data=payload_data) response = response_raw.read() payload = '' if response_raw.code not in stat_codes: self.module.exit_json( changed=False, meta=" openurl response_raw.code show error and error code is %r" % (response_raw.code)) else: if isinstance(response, str) and len(response) > 0: payload = response elif method.lower() == 'delete' and response_raw.code == 204: payload = 'Delete is done.' if isinstance(payload, dict) and "text" in payload: self.module.exit_json( changed=False, meta="when calling rest api, returned data is not json ") raise Exception(payload["text"]) return payload # --------------------------------------------------------------------------- # get_network() # --------------------------------------------------------------------------- def get_network(self, network_id, network_name, limit=-1): """ Search network_name inside Infinity by using rest api Network id or network_name needs to be provided return the details of a given with given network_id or name """ if network_name is None and network_id is None: self.module.exit_json( msg="You must specify one of the options 'network_name' or 'network_id'.") method = "get" resource_url = '' params = {} response = None if network_id: resource_url = "networks/" + str(network_id) response = self._get_api_call_ansible_handler(method, resource_url) if network_id is None and network_name: method = "get" resource_url = "search" params = {"query": json.dumps( {"name": network_name, "type": "network"})} response = self._get_api_call_ansible_handler( method, resource_url, payload_data=json.dumps(params)) if response and isinstance(response, str): response = json.loads(response) if response and isinstance(response, list) and len( response) > 1 and limit == 1: response = response[0] response = json.dumps(response) return response # --------------------------------------------------------------------------- # get_network_id() # --------------------------------------------------------------------------- def get_network_id(self, network_name="", network_type='lan'): """ query network_id from Infinity via rest api based on given network_name """ method = 'get' resource_url = 'search' response = None if network_name is None: self.module.exit_json( msg="You must specify the option 'network_name'") params = {"query": json.dumps( {"name": network_name, "type": "network"})} response = self._get_api_call_ansible_handler( method, resource_url, payload_data=json.dumps(params)) network_id = "" if response and isinstance(response, str): response = json.loads(response) if response and isinstance(response, list): response = response[0] network_id = response['id'] return network_id # --------------------------------------------------------------------------- # reserve_next_available_ip() # --------------------------------------------------------------------------- def reserve_next_available_ip(self, network_id=""): """ Reserve ip address via Infinity by using rest api network_id: the id of the network that users would like to reserve network from return the next available ip address from that given network """ method = "post" resource_url = '' response = None ip_info = '' if not network_id: self.module.exit_json( msg="You must specify the option 'network_id'.") if network_id: resource_url = "networks/" + str(network_id) + "/reserve_ip" response = self._get_api_call_ansible_handler(method, resource_url) if response and response.find( "[") >= 0 and response.find("]") >= 0: start_pos = response.find("{") end_pos = response.find("}") ip_info = response[start_pos: (end_pos + 1)] return ip_info # ------------------------- # release_ip() # ------------------------- def release_ip(self, network_id="", ip_address=""): """ Reserve ip address via Infinity by using rest api """ method = "get" resource_url = '' response = None if ip_address is None or network_id is None: self.module.exit_json( msg="You must specify those two options: 'network_id' and 'ip_address'.") resource_url = "networks/" + str(network_id) + "/children" response = self._get_api_call_ansible_handler(method, resource_url) if not response: self.module.exit_json( msg="There is an error in release ip %s from network %s." % (ip_address, network_id)) ip_list = json.loads(response) ip_idlist = [] for ip_item in ip_list: ip_id = ip_item['id'] ip_idlist.append(ip_id) deleted_ip_id = '' for ip_id in ip_idlist: ip_response = '' resource_url = "ip_addresses/" + str(ip_id) ip_response = self._get_api_call_ansible_handler( method, resource_url, stat_codes=[200]) if ip_response and json.loads( ip_response)['address'] == str(ip_address): deleted_ip_id = ip_id break if deleted_ip_id: method = 'delete' resource_url = "ip_addresses/" + str(deleted_ip_id) response = self._get_api_call_ansible_handler( method, resource_url, stat_codes=[204]) else: self.module.exit_json( msg=" When release ip, could not find the ip address %r from the given network %r' ." % (ip_address, network_id)) return response # ------------------- # delete_network() # ------------------- def delete_network(self, network_id="", network_name=""): """ delete network from Infinity by using rest api """ method = 'delete' resource_url = '' response = None if network_id is None and network_name is None: self.module.exit_json( msg="You must specify one of those options: 'network_id','network_name' .") if network_id is None and network_name: network_id = self.get_network_id(network_name=network_name) if network_id: resource_url = "networks/" + str(network_id) response = self._get_api_call_ansible_handler( method, resource_url, stat_codes=[204]) return response # reserve_network() # --------------------------------------------------------------------------- def reserve_network(self, network_id="", reserved_network_name="", reserved_network_description="", reserved_network_size="", reserved_network_family='4', reserved_network_type='lan', reserved_network_address="",): """ Reserves the first available network of specified size from a given supernet <dt>network_name (required)</dt><dd>Name of the network</dd> <dt>description (optional)</dt><dd>Free description</dd> <dt>network_family (required)</dt><dd>Address family of the network. One of '4', '6', 'IPv4', 'IPv6', 'dual'</dd> <dt>network_address (optional)</dt><dd>Address of the new network. If not given, the first network available will be created.</dd> <dt>network_size (required)</dt><dd>Size of the new network in /&lt;prefix&gt; notation.</dd> <dt>network_type (required)</dt><dd>Type of network. One of 'supernet', 'lan', 'shared_lan'</dd> """ method = 'post' resource_url = '' network_info = None if network_id is None or reserved_network_name is None or reserved_network_size is None: self.module.exit_json( msg="You must specify those options: 'network_id', 'reserved_network_name' and 'reserved_network_size'") if network_id: resource_url = "networks/" + str(network_id) + "/reserve_network" if not reserved_network_family: reserved_network_family = '4' if not reserved_network_type: reserved_network_type = 'lan' payload_data = { "network_name": reserved_network_name, 'description': reserved_network_description, 'network_size': reserved_network_size, 'network_family': reserved_network_family, 'network_type': reserved_network_type, 'network_location': int(network_id)} if reserved_network_address: payload_data.update({'network_address': reserved_network_address}) network_info = self._get_api_call_ansible_handler( method, resource_url, stat_codes=[200, 201], payload_data=payload_data) return network_info # --------------------------------------------------------------------------- # release_network() # --------------------------------------------------------------------------- def release_network( self, network_id="", released_network_name="", released_network_type='lan'): """ Release the network with name 'released_network_name' from the given supernet network_id """ method = 'get' response = None if network_id is None or released_network_name is None: self.module.exit_json( msg="You must specify those options 'network_id', 'reserved_network_name' and 'reserved_network_size'") matched_network_id = "" resource_url = "networks/" + str(network_id) + "/children" response = self._get_api_call_ansible_handler(method, resource_url) if not response: self.module.exit_json( msg=" there is an error in releasing network %r from network %s." % (network_id, released_network_name)) if response: response = json.loads(response) for child_net in response: if child_net['network'] and child_net['network']['network_name'] == released_network_name: matched_network_id = child_net['network']['network_id'] break response = None if matched_network_id: method = 'delete' resource_url = "networks/" + str(matched_network_id) response = self._get_api_call_ansible_handler( method, resource_url, stat_codes=[204]) else: self.module.exit_json( msg=" When release network , could not find the network %r from the given superent %r' " % (released_network_name, network_id)) return response # --------------------------------------------------------------------------- # add_network() # --------------------------------------------------------------------------- def add_network( self, network_name="", network_address="", network_size="", network_family='4', network_type='lan', network_location=-1): """ add a new LAN network into a given supernet Fusionlayer Infinity via rest api or default supernet required fields=['network_name', 'network_family', 'network_type', 'network_address','network_size' ] """ method = 'post' resource_url = 'networks' response = None if network_name is None or network_address is None or network_size is None: self.module.exit_json( msg="You must specify those options 'network_name', 'network_address' and 'network_size'") if not network_family: network_family = '4' if not network_type: network_type = 'lan' if not network_location: network_location = -1 payload_data = { "network_name": network_name, 'network_address': network_address, 'network_size': network_size, 'network_family': network_family, 'network_type': network_type, 'network_location': network_location} response = self._get_api_call_ansible_handler( method='post', resource_url=resource_url, stat_codes=[200], payload_data=payload_data) return response def main(): my_module = AnsibleModule(argument_spec=dict( server_ip=dict(required=True, type='str'), username=dict(required=True, type='str'), password=dict(required=True, type='str', no_log=True), network_id=dict(type='str'), ip_address=dict(type='str'), network_name=dict(type='str'), network_location=dict(default=-1, type='int'), network_family=dict(default='4', choices=['4', '6', 'dual']), network_type=dict(default='lan', choices=['lan', 'shared_lan', 'supernet']), network_address=dict(type='str'), network_size=dict(type='str'), action=dict(required=True, choices=['get_network', 'reserve_next_available_ip', 'release_ip', 'delete_network', 'reserve_network', 'release_network', 'add_network', 'get_network_id'],), ), required_together=(['username', 'password'],),) server_ip = my_module.params["server_ip"] username = my_module.params["username"] password = my_module.params["password"] action = my_module.params["action"] network_id = my_module.params["network_id"] released_ip = my_module.params["ip_address"] network_name = my_module.params["network_name"] network_family = my_module.params["network_family"] network_type = my_module.params["network_type"] network_address = my_module.params["network_address"] network_size = my_module.params["network_size"] network_location = my_module.params["network_location"] my_infinity = Infinity(my_module, server_ip, username, password) result = '' if action == "reserve_next_available_ip": if network_id: result = my_infinity.reserve_next_available_ip(network_id) if not result: result = 'There is an error in calling method of reserve_next_available_ip' my_module.exit_json(changed=False, meta=result) my_module.exit_json(changed=True, meta=result) elif action == "release_ip": if network_id and released_ip: result = my_infinity.release_ip( network_id=network_id, ip_address=released_ip) my_module.exit_json(changed=True, meta=result) elif action == "delete_network": result = my_infinity.delete_network( network_id=network_id, network_name=network_name) my_module.exit_json(changed=True, meta=result) elif action == "get_network_id": result = my_infinity.get_network_id( network_name=network_name, network_type=network_type) my_module.exit_json(changed=True, meta=result) elif action == "get_network": result = my_infinity.get_network( network_id=network_id, network_name=network_name) my_module.exit_json(changed=True, meta=result) elif action == "reserve_network": result = my_infinity.reserve_network( network_id=network_id, reserved_network_name=network_name, reserved_network_size=network_size, reserved_network_family=network_family, reserved_network_type=network_type, reserved_network_address=network_address) my_module.exit_json(changed=True, meta=result) elif action == "release_network": result = my_infinity.release_network( network_id=network_id, released_network_name=network_name, released_network_type=network_type) my_module.exit_json(changed=True, meta=result) elif action == "add_network": result = my_infinity.add_network( network_name=network_name, network_location=network_location, network_address=network_address, network_size=network_size, network_family=network_family, network_type=network_type) my_module.exit_json(changed=True, meta=result) if __name__ == '__main__': main()
unknown
codeparrot/codeparrot-clean
#ifndef CURLINC_CURLVER_H #define CURLINC_CURLVER_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * SPDX-License-Identifier: curl * ***************************************************************************/ /* This header file contains nothing but libcurl version info, generated by a script at release-time. This was made its own header file in 7.11.2 */ /* This is the global package copyright */ #define LIBCURL_COPYRIGHT "Daniel Stenberg, <daniel@haxx.se>." /* This is the version number of the libcurl package from which this header file origins: */ #define LIBCURL_VERSION "8.18.0" /* The numeric version number is also available "in parts" by using these defines: */ #define LIBCURL_VERSION_MAJOR 8 #define LIBCURL_VERSION_MINOR 18 #define LIBCURL_VERSION_PATCH 0 /* This is the numeric version of the libcurl version number, meant for easier parsing and comparisons by programs. The LIBCURL_VERSION_NUM define will always follow this syntax: 0xXXYYZZ Where XX, YY and ZZ are the main version, release and patch numbers in hexadecimal (using 8 bits each). All three numbers are always represented using two digits. 1.2 would appear as "0x010200" while version 9.11.7 appears as "0x090b07". This 6-digit (24 bits) hexadecimal number does not show pre-release number, and it is always a greater number in a more recent release. It makes comparisons with greater than and less than work. Note: This define is the full hex number and _does not_ use the CURL_VERSION_BITS() macro since curl's own configure script greps for it and needs it to contain the full number. */ #define LIBCURL_VERSION_NUM 0x081200 /* * This is the date and time when the full source package was created. The * timestamp is not stored in git, as the timestamp is properly set in the * tarballs by the maketgz script. * * The format of the date follows this template: * * "2007-11-23" */ #define LIBCURL_TIMESTAMP "[vcpkg]" #define CURL_VERSION_BITS(x, y, z) ((x) << 16 | (y) << 8 | (z)) #define CURL_AT_LEAST_VERSION(x, y, z) \ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z)) #endif /* CURLINC_CURLVER_H */
c
github
https://github.com/ktorio/ktor
ktor-client/ktor-client-curl/desktop/interop/include/curl/curlver.h
ON = '-' OFF = '.' ON_BIT = '1' OFF_BIT = '0' SEPARATOR = ':' def dec_to_bin(num): bits = [] while True: bits.append(str(num % 2)) num //= 2 if num == 0: break bits.reverse() return "".join(bits) def checkio(timestring): hh, mm, ss = timestring.split(SEPARATOR) return (' ' + SEPARATOR + ' ').join([hour_to_morse(hh), minute_to_morse(mm), second_to_morse(ss)]) def second_to_morse(second): return timeval_to_morse(second, 3, 4) def minute_to_morse(minute): return timeval_to_morse(minute, 3, 4) def hour_to_morse(hour): return timeval_to_morse(hour, 2, 4) def timeval_to_morse(timeval, firstDigitMaxBits, secondDigitMaxBits): if len(timeval) < 2: digit_one_bits = '0'.zfill(firstDigitMaxBits) digit_two_bits = dec_to_bin(int(timeval[0])).zfill(secondDigitMaxBits) else: digit_one_bits = dec_to_bin(int(timeval[0])).zfill(firstDigitMaxBits) digit_two_bits = dec_to_bin(int(timeval[1])).zfill(secondDigitMaxBits) digit_one_morse = [] digit_two_morse = [] for i in range(firstDigitMaxBits): if digit_one_bits[i] == OFF_BIT: digit_one_morse.append(OFF) else: digit_one_morse.append(ON) for i in range(secondDigitMaxBits): if digit_two_bits[i] == OFF_BIT: digit_two_morse.append(OFF) else: digit_two_morse.append(ON) return " ".join(["".join(digit_one_morse), "".join(digit_two_morse)])
unknown
codeparrot/codeparrot-clean
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 Hewlett-Packard Development Company, L.P. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from pbr.hooks import base from pbr import packaging class MetadataConfig(base.BaseConfig): section = 'metadata' def hook(self): self.config['version'] = packaging.get_version( self.config['name'], self.config.get('version', None)) packaging.append_text_list( self.config, 'requires_dist', packaging.parse_requirements()) def get_name(self): return self.config['name']
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env bash # Copyright 2018 The Cockroach Authors. # # Use of this software is governed by the CockroachDB Software License # included in the /LICENSE file. # Detect whether the installed version of Go can build this version of # CockroachDB. # # To bump the required version of Go, edit the appropriate variables: required_version_major=1 minimum_version_minor=20 go=${1-go} if ! raw_version=$("$go" version 2>&1); then echo "unable to detect go version: $raw_version" >&2 exit 1 fi if ! version=$(grep -oE "[0-9]+(\.[0-9]+)+" <<< "$raw_version" | head -n1); then echo "unable to parse go version '$raw_version'" >&2 exit 1 fi version_major=$(cut -f1 -d. <<< "$version") version_minor=$(cut -f2 -d. <<< "$version") version_patch=$(cut -f3 -d. <<< "$version") required_version_patch=$(eval echo \$minimum_version_${version_minor}_patch) check_patch=$(if test -n "$version_patch"; then echo 1; else echo 0; fi) if (( version_major != required_version_major )) || \ (( version_minor < minimum_version_minor )); then echo "go$required_version_major.$minimum_version_minor+ required (detected go$version)" >&2 exit 1 elif (( check_patch == 1 && version_patch < required_version_patch )); then minimum_version_patch=$(eval echo \$minimum_version_${minimum_version_minor}_patch) echo "need Go patch $required_version_major.$version_minor.$required_version_patch+ when using go$required_version_major.$version_minor (detected go$version; minimum version for successful builds is go$required_version_major.$minimum_version_minor.$minimum_version_patch+)" >&2 exit 1 fi
unknown
github
https://github.com/cockroachdb/cockroach
build/go-version-check.sh
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Ivan Kopeykin @vankop */ "use strict"; const makeSerializable = require("../util/makeSerializable"); const ContextDependency = require("./ContextDependency"); const ModuleDependencyTemplateAsRequireId = require("./ModuleDependencyTemplateAsRequireId"); /** @typedef {import("../javascript/JavascriptParser").Range} Range */ /** @typedef {import("./ContextDependency").ContextDependencyOptions} ContextDependencyOptions */ class ImportMetaContextDependency extends ContextDependency { /** * @param {ContextDependencyOptions} options options * @param {Range} range range */ constructor(options, range) { super(options); this.range = range; } get category() { return "esm"; } get type() { return `import.meta.webpackContext ${this.options.mode}`; } } makeSerializable( ImportMetaContextDependency, "webpack/lib/dependencies/ImportMetaContextDependency" ); ImportMetaContextDependency.Template = ModuleDependencyTemplateAsRequireId; module.exports = ImportMetaContextDependency;
javascript
github
https://github.com/webpack/webpack
lib/dependencies/ImportMetaContextDependency.js
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.errors import AnsibleError from ansible.parsing.mod_args import ModuleArgsParser from ansible.parsing.splitter import parse_kv from ansible.parsing.yaml.objects import AnsibleBaseYAMLObject, AnsibleMapping from ansible.plugins import module_loader, lookup_loader from ansible.playbook.attribute import Attribute, FieldAttribute from ansible.playbook.base import Base from ansible.playbook.become import Become from ansible.playbook.block import Block from ansible.playbook.conditional import Conditional from ansible.playbook.role import Role from ansible.playbook.taggable import Taggable __all__ = ['Task'] class Task(Base, Conditional, Taggable, Become): """ A task is a language feature that represents a call to a module, with given arguments and other parameters. A handler is a subclass of a task. Usage: Task.load(datastructure) -> Task Task.something(...) """ # ================================================================================= # ATTRIBUTES # load_<attribute_name> and # validate_<attribute_name> # will be used if defined # might be possible to define others _args = FieldAttribute(isa='dict', default=dict()) _action = FieldAttribute(isa='string') _always_run = FieldAttribute(isa='bool') _any_errors_fatal = FieldAttribute(isa='bool') _async = FieldAttribute(isa='int', default=0) _changed_when = FieldAttribute(isa='string') _connection = FieldAttribute(isa='string') _delay = FieldAttribute(isa='int', default=5) _delegate_to = FieldAttribute(isa='string') _environment = FieldAttribute(isa='dict') _failed_when = FieldAttribute(isa='string') _first_available_file = FieldAttribute(isa='list') _ignore_errors = FieldAttribute(isa='bool') _loop = FieldAttribute(isa='string', private=True) _loop_args = FieldAttribute(isa='list', private=True) _local_action = FieldAttribute(isa='string') # FIXME: this should not be a Task _meta = FieldAttribute(isa='string') _name = FieldAttribute(isa='string') _no_log = FieldAttribute(isa='bool') _notify = FieldAttribute(isa='list') _poll = FieldAttribute(isa='int') _register = FieldAttribute(isa='string') _remote_user = FieldAttribute(isa='string') _retries = FieldAttribute(isa='int', default=1) _run_once = FieldAttribute(isa='bool') _transport = FieldAttribute(isa='string') _until = FieldAttribute(isa='list') # ? _vars = FieldAttribute(isa='dict', default=dict()) def __init__(self, block=None, role=None, task_include=None): ''' constructors a task, without the Task.load classmethod, it will be pretty blank ''' self._block = block self._role = role self._task_include = task_include super(Task, self).__init__() def get_name(self): ''' return the name of the task ''' if self._role and self.name: return "%s : %s" % (self._role.get_name(), self.name) elif self.name: return self.name else: flattened_args = self._merge_kv(self.args) if self._role: return "%s : %s %s" % (self._role.get_name(), self.action, flattened_args) else: return "%s %s" % (self.action, flattened_args) def _merge_kv(self, ds): if ds is None: return "" elif isinstance(ds, basestring): return ds elif isinstance(ds, dict): buf = "" for (k,v) in ds.iteritems(): if k.startswith('_'): continue buf = buf + "%s=%s " % (k,v) buf = buf.strip() return buf @staticmethod def load(data, block=None, role=None, task_include=None, variable_manager=None, loader=None): t = Task(block=block, role=role, task_include=task_include) return t.load_data(data, variable_manager=variable_manager, loader=loader) def __repr__(self): ''' returns a human readable representation of the task ''' return "TASK: %s" % self.get_name() def _munge_loop(self, ds, new_ds, k, v): ''' take a lookup plugin name and store it correctly ''' loop_name = k.replace("with_", "") if new_ds.get('loop') is not None: raise AnsibleError("duplicate loop in task: %s" % loop_name) new_ds['loop'] = loop_name new_ds['loop_args'] = v def munge(self, ds): ''' tasks are especially complex arguments so need pre-processing. keep it short. ''' assert isinstance(ds, dict) # the new, cleaned datastructure, which will have legacy # items reduced to a standard structure suitable for the # attributes of the task class new_ds = AnsibleMapping() if isinstance(ds, AnsibleBaseYAMLObject): new_ds.copy_position_info(ds) # use the args parsing class to determine the action, args, # and the delegate_to value from the various possible forms # supported as legacy args_parser = ModuleArgsParser(task_ds=ds) (action, args, delegate_to) = args_parser.parse() new_ds['action'] = action new_ds['args'] = args new_ds['delegate_to'] = delegate_to for (k,v) in ds.iteritems(): if k in ('action', 'local_action', 'args', 'delegate_to') or k == action or k == 'shell': # we don't want to re-assign these values, which were # determined by the ModuleArgsParser() above continue elif k.replace("with_", "") in lookup_loader: self._munge_loop(ds, new_ds, k, v) else: new_ds[k] = v return super(Task, self).munge(new_ds) def post_validate(self, all_vars=dict(), fail_on_undefined=True): ''' Override of base class post_validate, to also do final validation on the block and task include (if any) to which this task belongs. ''' if self._block: self._block.post_validate(all_vars=all_vars, fail_on_undefined=fail_on_undefined) if self._task_include: self._task_include.post_validate(all_vars=all_vars, fail_on_undefined=fail_on_undefined) super(Task, self).post_validate(all_vars=all_vars, fail_on_undefined=fail_on_undefined) def get_vars(self): all_vars = self.vars.copy() if self._task_include: all_vars.update(self._task_include.get_vars()) all_vars.update(self.serialize()) if 'tags' in all_vars: del all_vars['tags'] if 'when' in all_vars: del all_vars['when'] return all_vars def compile(self): ''' For tasks, this is just a dummy method returning an array with 'self' in it, so we don't have to care about task types further up the chain. ''' return [self] def copy(self): new_me = super(Task, self).copy() new_me._block = None if self._block: new_me._block = self._block.copy() new_me._role = None if self._role: new_me._role = self._role new_me._task_include = None if self._task_include: new_me._task_include = self._task_include.copy() return new_me def serialize(self): data = super(Task, self).serialize() if self._block: data['block'] = self._block.serialize() if self._role: data['role'] = self._role.serialize() if self._task_include: data['task_include'] = self._task_include.serialize() return data def deserialize(self, data): # import is here to avoid import loops #from ansible.playbook.task_include import TaskInclude block_data = data.get('block') if block_data: b = Block() b.deserialize(block_data) self._block = b del data['block'] role_data = data.get('role') if role_data: r = Role() r.deserialize(role_data) self._role = r del data['role'] ti_data = data.get('task_include') if ti_data: #ti = TaskInclude() ti = Task() ti.deserialize(ti_data) self._task_include = ti del data['task_include'] super(Task, self).deserialize(data) def evaluate_conditional(self, all_vars): if self._block is not None: if not self._block.evaluate_conditional(all_vars): return False if self._task_include is not None: if not self._task_include.evaluate_conditional(all_vars): return False return super(Task, self).evaluate_conditional(all_vars) def evaluate_tags(self, only_tags, skip_tags, all_vars): result = False if self._block is not None: result |= self._block.evaluate_tags(only_tags=only_tags, skip_tags=skip_tags, all_vars=all_vars) return result | super(Task, self).evaluate_tags(only_tags=only_tags, skip_tags=skip_tags, all_vars=all_vars) def set_loader(self, loader): ''' Sets the loader on this object and recursively on parent, child objects. This is used primarily after the Task has been serialized/deserialized, which does not preserve the loader. ''' self._loader = loader if self._block: self._block.set_loader(loader) if self._task_include: self._task_include.set_loader(loader)
unknown
codeparrot/codeparrot-clean
/* * Builtin "git commit-commit" * * Copyright (c) 2014 Michael J Gruber <git@drmicha.warpmail.net> * * Based on git-verify-tag */ #include "builtin.h" #include "config.h" #include "environment.h" #include "gettext.h" #include "object-name.h" #include "commit.h" #include "parse-options.h" #include "gpg-interface.h" static const char * const verify_commit_usage[] = { N_("git verify-commit [-v | --verbose] [--raw] <commit>..."), NULL }; static int run_gpg_verify(struct commit *commit, unsigned flags) { struct signature_check signature_check; int ret; memset(&signature_check, 0, sizeof(signature_check)); ret = check_commit_signature(commit, &signature_check); print_signature_buffer(&signature_check, flags); signature_check_clear(&signature_check); return ret; } static int verify_commit(struct repository *repo, const char *name, unsigned flags) { struct object_id oid; struct object *obj; if (repo_get_oid(repo, name, &oid)) return error("commit '%s' not found.", name); obj = parse_object(repo, &oid); if (!obj) return error("%s: unable to read file.", name); if (obj->type != OBJ_COMMIT) return error("%s: cannot verify a non-commit object of type %s.", name, type_name(obj->type)); return run_gpg_verify((struct commit *)obj, flags); } int cmd_verify_commit(int argc, const char **argv, const char *prefix, struct repository *repo) { int i = 1, verbose = 0, had_error = 0; unsigned flags = 0; const struct option verify_commit_options[] = { OPT__VERBOSE(&verbose, N_("print commit contents")), OPT_BIT(0, "raw", &flags, N_("print raw gpg status output"), GPG_VERIFY_RAW), OPT_END() }; repo_config(repo, git_default_config, NULL); argc = parse_options(argc, argv, prefix, verify_commit_options, verify_commit_usage, PARSE_OPT_KEEP_ARGV0); if (argc <= i) usage_with_options(verify_commit_usage, verify_commit_options); if (verbose) flags |= GPG_VERIFY_VERBOSE; /* sometimes the program was terminated because this signal * was received in the process of writing the gpg input: */ signal(SIGPIPE, SIG_IGN); while (i < argc) if (verify_commit(repo, argv[i++], flags)) had_error = 1; return had_error; }
c
github
https://github.com/git/git
builtin/verify-commit.c
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: pogoprotos/settings/level_settings.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='pogoprotos/settings/level_settings.proto', package='pogoprotos.settings', syntax='proto3', serialized_pb=_b('\n(pogoprotos/settings/level_settings.proto\x12\x13pogoprotos.settings\"Q\n\rLevelSettings\x12\x1b\n\x13trainer_cp_modifier\x18\x02 \x01(\x01\x12#\n\x1btrainer_difficulty_modifier\x18\x03 \x01(\x01\x62\x06proto3') ) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _LEVELSETTINGS = _descriptor.Descriptor( name='LevelSettings', full_name='pogoprotos.settings.LevelSettings', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='trainer_cp_modifier', full_name='pogoprotos.settings.LevelSettings.trainer_cp_modifier', index=0, number=2, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='trainer_difficulty_modifier', full_name='pogoprotos.settings.LevelSettings.trainer_difficulty_modifier', index=1, number=3, type=1, cpp_type=5, label=1, has_default_value=False, default_value=float(0), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=65, serialized_end=146, ) DESCRIPTOR.message_types_by_name['LevelSettings'] = _LEVELSETTINGS LevelSettings = _reflection.GeneratedProtocolMessageType('LevelSettings', (_message.Message,), dict( DESCRIPTOR = _LEVELSETTINGS, __module__ = 'pogoprotos.settings.level_settings_pb2' # @@protoc_insertion_point(class_scope:pogoprotos.settings.LevelSettings) )) _sym_db.RegisterMessage(LevelSettings) # @@protoc_insertion_point(module_scope)
unknown
codeparrot/codeparrot-clean
/* origin: FreeBSD /usr/src/lib/msun/src/e_j0.c */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunSoft, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ /* j0(x), y0(x) * Bessel function of the first and second kinds of order zero. * Method -- j0(x): * 1. For tiny x, we use j0(x) = 1 - x^2/4 + x^4/64 - ... * 2. Reduce x to |x| since j0(x)=j0(-x), and * for x in (0,2) * j0(x) = 1-z/4+ z^2*R0/S0, where z = x*x; * (precision: |j0-1+z/4-z^2R0/S0 |<2**-63.67 ) * for x in (2,inf) * j0(x) = sqrt(2/(pi*x))*(p0(x)*cos(x0)-q0(x)*sin(x0)) * where x0 = x-pi/4. It is better to compute sin(x0),cos(x0) * as follow: * cos(x0) = cos(x)cos(pi/4)+sin(x)sin(pi/4) * = 1/sqrt(2) * (cos(x) + sin(x)) * sin(x0) = sin(x)cos(pi/4)-cos(x)sin(pi/4) * = 1/sqrt(2) * (sin(x) - cos(x)) * (To avoid cancellation, use * sin(x) +- cos(x) = -cos(2x)/(sin(x) -+ cos(x)) * to compute the worse one.) * * 3 Special cases * j0(nan)= nan * j0(0) = 1 * j0(inf) = 0 * * Method -- y0(x): * 1. For x<2. * Since * y0(x) = 2/pi*(j0(x)*(ln(x/2)+Euler) + x^2/4 - ...) * therefore y0(x)-2/pi*j0(x)*ln(x) is an even function. * We use the following function to approximate y0, * y0(x) = U(z)/V(z) + (2/pi)*(j0(x)*ln(x)), z= x^2 * where * U(z) = u00 + u01*z + ... + u06*z^6 * V(z) = 1 + v01*z + ... + v04*z^4 * with absolute approximation error bounded by 2**-72. * Note: For tiny x, U/V = u0 and j0(x)~1, hence * y0(tiny) = u0 + (2/pi)*ln(tiny), (choose tiny<2**-27) * 2. For x>=2. * y0(x) = sqrt(2/(pi*x))*(p0(x)*cos(x0)+q0(x)*sin(x0)) * where x0 = x-pi/4. It is better to compute sin(x0),cos(x0) * by the method mentioned above. * 3. Special cases: y0(0)=-inf, y0(x<0)=NaN, y0(inf)=0. */ use super::{cos, fabs, get_high_word, get_low_word, log, sin, sqrt}; const INVSQRTPI: f64 = 5.64189583547756279280e-01; /* 0x3FE20DD7, 0x50429B6D */ const TPI: f64 = 6.36619772367581382433e-01; /* 0x3FE45F30, 0x6DC9C883 */ /* common method when |x|>=2 */ fn common(ix: u32, x: f64, y0: bool) -> f64 { let s: f64; let mut c: f64; let mut ss: f64; let mut cc: f64; let z: f64; /* * j0(x) = sqrt(2/(pi*x))*(p0(x)*cos(x-pi/4)-q0(x)*sin(x-pi/4)) * y0(x) = sqrt(2/(pi*x))*(p0(x)*sin(x-pi/4)+q0(x)*cos(x-pi/4)) * * sin(x-pi/4) = (sin(x) - cos(x))/sqrt(2) * cos(x-pi/4) = (sin(x) + cos(x))/sqrt(2) * sin(x) +- cos(x) = -cos(2x)/(sin(x) -+ cos(x)) */ s = sin(x); c = cos(x); if y0 { c = -c; } cc = s + c; /* avoid overflow in 2*x, big ulp error when x>=0x1p1023 */ if ix < 0x7fe00000 { ss = s - c; z = -cos(2.0 * x); if s * c < 0.0 { cc = z / ss; } else { ss = z / cc; } if ix < 0x48000000 { if y0 { ss = -ss; } cc = pzero(x) * cc - qzero(x) * ss; } } return INVSQRTPI * cc / sqrt(x); } /* R0/S0 on [0, 2.00] */ const R02: f64 = 1.56249999999999947958e-02; /* 0x3F8FFFFF, 0xFFFFFFFD */ const R03: f64 = -1.89979294238854721751e-04; /* 0xBF28E6A5, 0xB61AC6E9 */ const R04: f64 = 1.82954049532700665670e-06; /* 0x3EBEB1D1, 0x0C503919 */ const R05: f64 = -4.61832688532103189199e-09; /* 0xBE33D5E7, 0x73D63FCE */ const S01: f64 = 1.56191029464890010492e-02; /* 0x3F8FFCE8, 0x82C8C2A4 */ const S02: f64 = 1.16926784663337450260e-04; /* 0x3F1EA6D2, 0xDD57DBF4 */ const S03: f64 = 5.13546550207318111446e-07; /* 0x3EA13B54, 0xCE84D5A9 */ const S04: f64 = 1.16614003333790000205e-09; /* 0x3E1408BC, 0xF4745D8F */ /// Zeroth order of the [Bessel function](https://en.wikipedia.org/wiki/Bessel_function) of the first kind (f64). #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn j0(mut x: f64) -> f64 { let z: f64; let r: f64; let s: f64; let mut ix: u32; ix = get_high_word(x); ix &= 0x7fffffff; /* j0(+-inf)=0, j0(nan)=nan */ if ix >= 0x7ff00000 { return 1.0 / (x * x); } x = fabs(x); if ix >= 0x40000000 { /* |x| >= 2 */ /* large ulp error near zeros: 2.4, 5.52, 8.6537,.. */ return common(ix, x, false); } /* 1 - x*x/4 + x*x*R(x^2)/S(x^2) */ if ix >= 0x3f200000 { /* |x| >= 2**-13 */ /* up to 4ulp error close to 2 */ z = x * x; r = z * (R02 + z * (R03 + z * (R04 + z * R05))); s = 1.0 + z * (S01 + z * (S02 + z * (S03 + z * S04))); return (1.0 + x / 2.0) * (1.0 - x / 2.0) + z * (r / s); } /* 1 - x*x/4 */ /* prevent underflow */ /* inexact should be raised when x!=0, this is not done correctly */ if ix >= 0x38000000 { /* |x| >= 2**-127 */ x = 0.25 * x * x; } return 1.0 - x; } const U00: f64 = -7.38042951086872317523e-02; /* 0xBFB2E4D6, 0x99CBD01F */ const U01: f64 = 1.76666452509181115538e-01; /* 0x3FC69D01, 0x9DE9E3FC */ const U02: f64 = -1.38185671945596898896e-02; /* 0xBF8C4CE8, 0xB16CFA97 */ const U03: f64 = 3.47453432093683650238e-04; /* 0x3F36C54D, 0x20B29B6B */ const U04: f64 = -3.81407053724364161125e-06; /* 0xBECFFEA7, 0x73D25CAD */ const U05: f64 = 1.95590137035022920206e-08; /* 0x3E550057, 0x3B4EABD4 */ const U06: f64 = -3.98205194132103398453e-11; /* 0xBDC5E43D, 0x693FB3C8 */ const V01: f64 = 1.27304834834123699328e-02; /* 0x3F8A1270, 0x91C9C71A */ const V02: f64 = 7.60068627350353253702e-05; /* 0x3F13ECBB, 0xF578C6C1 */ const V03: f64 = 2.59150851840457805467e-07; /* 0x3E91642D, 0x7FF202FD */ const V04: f64 = 4.41110311332675467403e-10; /* 0x3DFE5018, 0x3BD6D9EF */ /// Zeroth order of the [Bessel function](https://en.wikipedia.org/wiki/Bessel_function) of the second kind (f64). #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn y0(x: f64) -> f64 { let z: f64; let u: f64; let v: f64; let ix: u32; let lx: u32; ix = get_high_word(x); lx = get_low_word(x); /* y0(nan)=nan, y0(<0)=nan, y0(0)=-inf, y0(inf)=0 */ if ((ix << 1) | lx) == 0 { return -1.0 / 0.0; } if (ix >> 31) != 0 { return 0.0 / 0.0; } if ix >= 0x7ff00000 { return 1.0 / x; } if ix >= 0x40000000 { /* x >= 2 */ /* large ulp errors near zeros: 3.958, 7.086,.. */ return common(ix, x, true); } /* U(x^2)/V(x^2) + (2/pi)*j0(x)*log(x) */ if ix >= 0x3e400000 { /* x >= 2**-27 */ /* large ulp error near the first zero, x ~= 0.89 */ z = x * x; u = U00 + z * (U01 + z * (U02 + z * (U03 + z * (U04 + z * (U05 + z * U06))))); v = 1.0 + z * (V01 + z * (V02 + z * (V03 + z * V04))); return u / v + TPI * (j0(x) * log(x)); } return U00 + TPI * log(x); } /* The asymptotic expansions of pzero is * 1 - 9/128 s^2 + 11025/98304 s^4 - ..., where s = 1/x. * For x >= 2, We approximate pzero by * pzero(x) = 1 + (R/S) * where R = pR0 + pR1*s^2 + pR2*s^4 + ... + pR5*s^10 * S = 1 + pS0*s^2 + ... + pS4*s^10 * and * | pzero(x)-1-R/S | <= 2 ** ( -60.26) */ const PR8: [f64; 6] = [ /* for x in [inf, 8]=1/[0,0.125] */ 0.00000000000000000000e+00, /* 0x00000000, 0x00000000 */ -7.03124999999900357484e-02, /* 0xBFB1FFFF, 0xFFFFFD32 */ -8.08167041275349795626e+00, /* 0xC02029D0, 0xB44FA779 */ -2.57063105679704847262e+02, /* 0xC0701102, 0x7B19E863 */ -2.48521641009428822144e+03, /* 0xC0A36A6E, 0xCD4DCAFC */ -5.25304380490729545272e+03, /* 0xC0B4850B, 0x36CC643D */ ]; const PS8: [f64; 5] = [ 1.16534364619668181717e+02, /* 0x405D2233, 0x07A96751 */ 3.83374475364121826715e+03, /* 0x40ADF37D, 0x50596938 */ 4.05978572648472545552e+04, /* 0x40E3D2BB, 0x6EB6B05F */ 1.16752972564375915681e+05, /* 0x40FC810F, 0x8F9FA9BD */ 4.76277284146730962675e+04, /* 0x40E74177, 0x4F2C49DC */ ]; const PR5: [f64; 6] = [ /* for x in [8,4.5454]=1/[0.125,0.22001] */ -1.14125464691894502584e-11, /* 0xBDA918B1, 0x47E495CC */ -7.03124940873599280078e-02, /* 0xBFB1FFFF, 0xE69AFBC6 */ -4.15961064470587782438e+00, /* 0xC010A370, 0xF90C6BBF */ -6.76747652265167261021e+01, /* 0xC050EB2F, 0x5A7D1783 */ -3.31231299649172967747e+02, /* 0xC074B3B3, 0x6742CC63 */ -3.46433388365604912451e+02, /* 0xC075A6EF, 0x28A38BD7 */ ]; const PS5: [f64; 5] = [ 6.07539382692300335975e+01, /* 0x404E6081, 0x0C98C5DE */ 1.05125230595704579173e+03, /* 0x40906D02, 0x5C7E2864 */ 5.97897094333855784498e+03, /* 0x40B75AF8, 0x8FBE1D60 */ 9.62544514357774460223e+03, /* 0x40C2CCB8, 0xFA76FA38 */ 2.40605815922939109441e+03, /* 0x40A2CC1D, 0xC70BE864 */ ]; const PR3: [f64; 6] = [ /* for x in [4.547,2.8571]=1/[0.2199,0.35001] */ -2.54704601771951915620e-09, /* 0xBE25E103, 0x6FE1AA86 */ -7.03119616381481654654e-02, /* 0xBFB1FFF6, 0xF7C0E24B */ -2.40903221549529611423e+00, /* 0xC00345B2, 0xAEA48074 */ -2.19659774734883086467e+01, /* 0xC035F74A, 0x4CB94E14 */ -5.80791704701737572236e+01, /* 0xC04D0A22, 0x420A1A45 */ -3.14479470594888503854e+01, /* 0xC03F72AC, 0xA892D80F */ ]; const PS3: [f64; 5] = [ 3.58560338055209726349e+01, /* 0x4041ED92, 0x84077DD3 */ 3.61513983050303863820e+02, /* 0x40769839, 0x464A7C0E */ 1.19360783792111533330e+03, /* 0x4092A66E, 0x6D1061D6 */ 1.12799679856907414432e+03, /* 0x40919FFC, 0xB8C39B7E */ 1.73580930813335754692e+02, /* 0x4065B296, 0xFC379081 */ ]; const PR2: [f64; 6] = [ /* for x in [2.8570,2]=1/[0.3499,0.5] */ -8.87534333032526411254e-08, /* 0xBE77D316, 0xE927026D */ -7.03030995483624743247e-02, /* 0xBFB1FF62, 0x495E1E42 */ -1.45073846780952986357e+00, /* 0xBFF73639, 0x8A24A843 */ -7.63569613823527770791e+00, /* 0xC01E8AF3, 0xEDAFA7F3 */ -1.11931668860356747786e+01, /* 0xC02662E6, 0xC5246303 */ -3.23364579351335335033e+00, /* 0xC009DE81, 0xAF8FE70F */ ]; const PS2: [f64; 5] = [ 2.22202997532088808441e+01, /* 0x40363865, 0x908B5959 */ 1.36206794218215208048e+02, /* 0x4061069E, 0x0EE8878F */ 2.70470278658083486789e+02, /* 0x4070E786, 0x42EA079B */ 1.53875394208320329881e+02, /* 0x40633C03, 0x3AB6FAFF */ 1.46576176948256193810e+01, /* 0x402D50B3, 0x44391809 */ ]; fn pzero(x: f64) -> f64 { let p: &[f64; 6]; let q: &[f64; 5]; let z: f64; let r: f64; let s: f64; let mut ix: u32; ix = get_high_word(x); ix &= 0x7fffffff; if ix >= 0x40200000 { p = &PR8; q = &PS8; } else if ix >= 0x40122E8B { p = &PR5; q = &PS5; } else if ix >= 0x4006DB6D { p = &PR3; q = &PS3; } else /*ix >= 0x40000000*/ { p = &PR2; q = &PS2; } z = 1.0 / (x * x); r = p[0] + z * (p[1] + z * (p[2] + z * (p[3] + z * (p[4] + z * p[5])))); s = 1.0 + z * (q[0] + z * (q[1] + z * (q[2] + z * (q[3] + z * q[4])))); return 1.0 + r / s; } /* For x >= 8, the asymptotic expansions of qzero is * -1/8 s + 75/1024 s^3 - ..., where s = 1/x. * We approximate pzero by * qzero(x) = s*(-1.25 + (R/S)) * where R = qR0 + qR1*s^2 + qR2*s^4 + ... + qR5*s^10 * S = 1 + qS0*s^2 + ... + qS5*s^12 * and * | qzero(x)/s +1.25-R/S | <= 2 ** ( -61.22) */ const QR8: [f64; 6] = [ /* for x in [inf, 8]=1/[0,0.125] */ 0.00000000000000000000e+00, /* 0x00000000, 0x00000000 */ 7.32421874999935051953e-02, /* 0x3FB2BFFF, 0xFFFFFE2C */ 1.17682064682252693899e+01, /* 0x40278952, 0x5BB334D6 */ 5.57673380256401856059e+02, /* 0x40816D63, 0x15301825 */ 8.85919720756468632317e+03, /* 0x40C14D99, 0x3E18F46D */ 3.70146267776887834771e+04, /* 0x40E212D4, 0x0E901566 */ ]; const QS8: [f64; 6] = [ 1.63776026895689824414e+02, /* 0x406478D5, 0x365B39BC */ 8.09834494656449805916e+03, /* 0x40BFA258, 0x4E6B0563 */ 1.42538291419120476348e+05, /* 0x41016652, 0x54D38C3F */ 8.03309257119514397345e+05, /* 0x412883DA, 0x83A52B43 */ 8.40501579819060512818e+05, /* 0x4129A66B, 0x28DE0B3D */ -3.43899293537866615225e+05, /* 0xC114FD6D, 0x2C9530C5 */ ]; const QR5: [f64; 6] = [ /* for x in [8,4.5454]=1/[0.125,0.22001] */ 1.84085963594515531381e-11, /* 0x3DB43D8F, 0x29CC8CD9 */ 7.32421766612684765896e-02, /* 0x3FB2BFFF, 0xD172B04C */ 5.83563508962056953777e+00, /* 0x401757B0, 0xB9953DD3 */ 1.35111577286449829671e+02, /* 0x4060E392, 0x0A8788E9 */ 1.02724376596164097464e+03, /* 0x40900CF9, 0x9DC8C481 */ 1.98997785864605384631e+03, /* 0x409F17E9, 0x53C6E3A6 */ ]; const QS5: [f64; 6] = [ 8.27766102236537761883e+01, /* 0x4054B1B3, 0xFB5E1543 */ 2.07781416421392987104e+03, /* 0x40A03BA0, 0xDA21C0CE */ 1.88472887785718085070e+04, /* 0x40D267D2, 0x7B591E6D */ 5.67511122894947329769e+04, /* 0x40EBB5E3, 0x97E02372 */ 3.59767538425114471465e+04, /* 0x40E19118, 0x1F7A54A0 */ -5.35434275601944773371e+03, /* 0xC0B4EA57, 0xBEDBC609 */ ]; const QR3: [f64; 6] = [ /* for x in [4.547,2.8571]=1/[0.2199,0.35001] */ 4.37741014089738620906e-09, /* 0x3E32CD03, 0x6ADECB82 */ 7.32411180042911447163e-02, /* 0x3FB2BFEE, 0x0E8D0842 */ 3.34423137516170720929e+00, /* 0x400AC0FC, 0x61149CF5 */ 4.26218440745412650017e+01, /* 0x40454F98, 0x962DAEDD */ 1.70808091340565596283e+02, /* 0x406559DB, 0xE25EFD1F */ 1.66733948696651168575e+02, /* 0x4064D77C, 0x81FA21E0 */ ]; const QS3: [f64; 6] = [ 4.87588729724587182091e+01, /* 0x40486122, 0xBFE343A6 */ 7.09689221056606015736e+02, /* 0x40862D83, 0x86544EB3 */ 3.70414822620111362994e+03, /* 0x40ACF04B, 0xE44DFC63 */ 6.46042516752568917582e+03, /* 0x40B93C6C, 0xD7C76A28 */ 2.51633368920368957333e+03, /* 0x40A3A8AA, 0xD94FB1C0 */ -1.49247451836156386662e+02, /* 0xC062A7EB, 0x201CF40F */ ]; const QR2: [f64; 6] = [ /* for x in [2.8570,2]=1/[0.3499,0.5] */ 1.50444444886983272379e-07, /* 0x3E84313B, 0x54F76BDB */ 7.32234265963079278272e-02, /* 0x3FB2BEC5, 0x3E883E34 */ 1.99819174093815998816e+00, /* 0x3FFFF897, 0xE727779C */ 1.44956029347885735348e+01, /* 0x402CFDBF, 0xAAF96FE5 */ 3.16662317504781540833e+01, /* 0x403FAA8E, 0x29FBDC4A */ 1.62527075710929267416e+01, /* 0x403040B1, 0x71814BB4 */ ]; const QS2: [f64; 6] = [ 3.03655848355219184498e+01, /* 0x403E5D96, 0xF7C07AED */ 2.69348118608049844624e+02, /* 0x4070D591, 0xE4D14B40 */ 8.44783757595320139444e+02, /* 0x408A6645, 0x22B3BF22 */ 8.82935845112488550512e+02, /* 0x408B977C, 0x9C5CC214 */ 2.12666388511798828631e+02, /* 0x406A9553, 0x0E001365 */ -5.31095493882666946917e+00, /* 0xC0153E6A, 0xF8B32931 */ ]; fn qzero(x: f64) -> f64 { let p: &[f64; 6]; let q: &[f64; 6]; let s: f64; let r: f64; let z: f64; let mut ix: u32; ix = get_high_word(x); ix &= 0x7fffffff; if ix >= 0x40200000 { p = &QR8; q = &QS8; } else if ix >= 0x40122E8B { p = &QR5; q = &QS5; } else if ix >= 0x4006DB6D { p = &QR3; q = &QS3; } else /*ix >= 0x40000000*/ { p = &QR2; q = &QS2; } z = 1.0 / (x * x); r = p[0] + z * (p[1] + z * (p[2] + z * (p[3] + z * (p[4] + z * p[5])))); s = 1.0 + z * (q[0] + z * (q[1] + z * (q[2] + z * (q[3] + z * (q[4] + z * q[5]))))); return (-0.125 + r / s) / x; }
rust
github
https://github.com/nodejs/node
deps/crates/vendor/libm/src/math/j0.rs
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndex; import static com.google.common.base.Preconditions.checkState; import static java.util.Collections.unmodifiableList; import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.j2objc.annotations.Weak; import com.google.j2objc.annotations.WeakOuter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.AbstractMap.SimpleEntry; import java.util.AbstractSequentialList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; import java.util.function.Consumer; import org.jspecify.annotations.Nullable; /** * An implementation of {@code ListMultimap} that supports deterministic iteration order for both * keys and values. The iteration order is preserved across non-distinct key values. For example, * for the following multimap definition: * * {@snippet : * Multimap<K, V> multimap = LinkedListMultimap.create(); * multimap.put(key1, foo); * multimap.put(key2, bar); * multimap.put(key1, baz); * } * * ... the iteration order for {@link #keys()} is {@code [key1, key2, key1]}, and similarly for * {@link #entries()}. Unlike {@link LinkedHashMultimap}, the iteration order is kept consistent * between keys, entries and values. For example, calling: * * {@snippet : * multimap.remove(key1, foo); * } * * <p>changes the entries iteration order to {@code [key2=bar, key1=baz]} and the key iteration * order to {@code [key2, key1]}. The {@link #entries()} iterator returns mutable map entries, and * {@link #replaceValues} attempts to preserve iteration order as much as possible. * * <p>The collections returned by {@link #keySet()} and {@link #asMap()} iterate through the keys in * the order they were first added to the multimap. Similarly, {@link #get}, {@link #removeAll}, and * {@link #replaceValues} return collections that iterate through the values in the order they were * added. The collections generated by {@link #entries()}, {@link #keys()}, and {@link #values} * iterate across the key-value mappings in the order they were added to the multimap. * * <p>The {@link #values()} and {@link #entries()} methods both return a {@code List}, instead of * the {@code Collection} specified by the {@link ListMultimap} interface. * * <p>The methods {@link #get}, {@link #keySet()}, {@link #keys()}, {@link #values()}, {@link * #entries()}, and {@link #asMap()} return collections that are views of the multimap. If the * multimap is modified while an iteration over any of those collections is in progress, except * through the iterator's methods, the results of the iteration are undefined. * * <p>Keys and values may be null. All optional multimap methods are supported, and all returned * views are modifiable. * * <p>This class is not threadsafe when any concurrent operations update the multimap. Concurrent * read operations will work correctly. To allow concurrent update operations, wrap your multimap * with a call to {@link Multimaps#synchronizedListMultimap}. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#multimap">{@code Multimap}</a>. * * @author Mike Bostock * @since 2.0 */ @GwtCompatible @SuppressWarnings("WrongCommentType") // false positive public class LinkedListMultimap<K extends @Nullable Object, V extends @Nullable Object> extends AbstractMultimap<K, V> implements ListMultimap<K, V>, Serializable { /* * Order is maintained using a linked list containing all key-value pairs. In * addition, a series of disjoint linked lists of "siblings", each containing * the values for a specific key, is used to implement {@link * ValueForKeyIterator} in constant time. */ static final class Node<K extends @Nullable Object, V extends @Nullable Object> extends SimpleEntry<K, V> { @Nullable Node<K, V> next; // the next node (with any key) @Weak @Nullable Node<K, V> previous; // the previous node (with any key) @Nullable Node<K, V> nextSibling; // the next node with the same key @Weak @Nullable Node<K, V> previousSibling; // the previous node with the same key Node(@ParametricNullness K key, @ParametricNullness V value) { super(key, value); } } private static final class KeyList<K extends @Nullable Object, V extends @Nullable Object> { Node<K, V> head; Node<K, V> tail; int count; KeyList(Node<K, V> firstNode) { this.head = firstNode; this.tail = firstNode; firstNode.previousSibling = null; firstNode.nextSibling = null; this.count = 1; } } private transient @Nullable Node<K, V> head; // the head for all keys private transient @Nullable Node<K, V> tail; // the tail for all keys private transient Map<K, KeyList<K, V>> keyToKeyList; private transient int size; /* * Tracks modifications to keyToKeyList so that addition or removal of keys invalidates * preexisting iterators. This does *not* track simple additions and removals of values * that are not the first to be added or last to be removed for their key. */ private transient int modCount; /** Creates a new, empty {@code LinkedListMultimap} with the default initial capacity. */ public static <K extends @Nullable Object, V extends @Nullable Object> LinkedListMultimap<K, V> create() { return new LinkedListMultimap<>(); } /** * Constructs an empty {@code LinkedListMultimap} with enough capacity to hold the specified * number of keys without rehashing. * * @param expectedKeys the expected number of distinct keys * @throws IllegalArgumentException if {@code expectedKeys} is negative */ public static <K extends @Nullable Object, V extends @Nullable Object> LinkedListMultimap<K, V> create(int expectedKeys) { return new LinkedListMultimap<>(expectedKeys); } /** * Constructs a {@code LinkedListMultimap} with the same mappings as the specified {@code * Multimap}. The new multimap has the same {@link Multimap#entries()} iteration order as the * input multimap. * * @param multimap the multimap whose contents are copied to this multimap */ public static <K extends @Nullable Object, V extends @Nullable Object> LinkedListMultimap<K, V> create(Multimap<? extends K, ? extends V> multimap) { return new LinkedListMultimap<>(multimap); } LinkedListMultimap() { this(12); } private LinkedListMultimap(int expectedKeys) { keyToKeyList = Platform.newHashMapWithExpectedSize(expectedKeys); } private LinkedListMultimap(Multimap<? extends K, ? extends V> multimap) { this(multimap.keySet().size()); putAll(multimap); } /** * Adds a new node for the specified key-value pair before the specified {@code nextSibling} * element, or at the end of the list if {@code nextSibling} is null. Note: if {@code nextSibling} * is specified, it MUST be for a node for the same {@code key}! */ @CanIgnoreReturnValue private Node<K, V> addNode( @ParametricNullness K key, @ParametricNullness V value, @Nullable Node<K, V> nextSibling) { Node<K, V> node = new Node<>(key, value); if (head == null) { // empty list head = tail = node; keyToKeyList.put(key, new KeyList<K, V>(node)); modCount++; } else if (nextSibling == null) { // non-empty list, add to tail // requireNonNull is safe because the list is non-empty. requireNonNull(tail).next = node; node.previous = tail; tail = node; KeyList<K, V> keyList = keyToKeyList.get(key); if (keyList == null) { keyToKeyList.put(key, keyList = new KeyList<>(node)); modCount++; } else { keyList.count++; Node<K, V> keyTail = keyList.tail; keyTail.nextSibling = node; node.previousSibling = keyTail; keyList.tail = node; } } else { // non-empty list, insert before nextSibling /* * requireNonNull is safe as long as callers pass a nextSibling that (a) has the same key and * (b) is present in the multimap. (And they do, except maybe in case of concurrent * modification, in which case all bets are off.) */ KeyList<K, V> keyList = requireNonNull(keyToKeyList.get(key)); keyList.count++; node.previous = nextSibling.previous; node.previousSibling = nextSibling.previousSibling; node.next = nextSibling; node.nextSibling = nextSibling; if (nextSibling.previousSibling == null) { // nextSibling was key head keyList.head = node; } else { nextSibling.previousSibling.nextSibling = node; } if (nextSibling.previous == null) { // nextSibling was head head = node; } else { nextSibling.previous.next = node; } nextSibling.previous = node; nextSibling.previousSibling = node; } size++; return node; } /** * Removes the specified node from the linked list. This method is only intended to be used from * the {@code Iterator} classes. See also {@link LinkedListMultimap#removeAllNodes(Object)}. */ private void removeNode(Node<K, V> node) { if (node.previous != null) { node.previous.next = node.next; } else { // node was head head = node.next; } if (node.next != null) { node.next.previous = node.previous; } else { // node was tail tail = node.previous; } if (node.previousSibling == null && node.nextSibling == null) { /* * requireNonNull is safe as long as we call removeNode only for nodes that are still in the * Multimap. This should be the case (except in case of concurrent modification, when all bets * are off). */ KeyList<K, V> keyList = requireNonNull(keyToKeyList.remove(node.getKey())); keyList.count = 0; modCount++; } else { // requireNonNull is safe (under the conditions listed in the comment in the branch above). KeyList<K, V> keyList = requireNonNull(keyToKeyList.get(node.getKey())); keyList.count--; if (node.previousSibling == null) { // requireNonNull is safe because we checked that not *both* siblings were null. keyList.head = requireNonNull(node.nextSibling); } else { node.previousSibling.nextSibling = node.nextSibling; } if (node.nextSibling == null) { // requireNonNull is safe because we checked that not *both* siblings were null. keyList.tail = requireNonNull(node.previousSibling); } else { node.nextSibling.previousSibling = node.previousSibling; } } size--; } /** Removes all nodes for the specified key. */ private void removeAllNodes(@ParametricNullness K key) { Iterators.clear(new ValueForKeyIterator(key)); } /** An {@code Iterator} over all nodes. */ private final class NodeIterator implements ListIterator<Entry<K, V>> { int nextIndex; @Nullable Node<K, V> next; @Nullable Node<K, V> current; @Nullable Node<K, V> previous; int expectedModCount = modCount; NodeIterator(int index) { int size = size(); checkPositionIndex(index, size); if (index >= (size / 2)) { previous = tail; nextIndex = size; while (index++ < size) { previous(); } } else { next = head; while (index-- > 0) { next(); } } current = null; } private void checkForConcurrentModification() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } @Override public boolean hasNext() { checkForConcurrentModification(); return next != null; } @CanIgnoreReturnValue @Override public Node<K, V> next() { checkForConcurrentModification(); if (next == null) { throw new NoSuchElementException(); } previous = current = next; next = next.next; nextIndex++; return current; } @Override public void remove() { checkForConcurrentModification(); checkState(current != null, "no calls to next() since the last call to remove()"); if (current != next) { // after call to next() previous = current.previous; nextIndex--; } else { // after call to previous() next = current.next; } removeNode(current); current = null; expectedModCount = modCount; } @Override public boolean hasPrevious() { checkForConcurrentModification(); return previous != null; } @CanIgnoreReturnValue @Override public Node<K, V> previous() { checkForConcurrentModification(); if (previous == null) { throw new NoSuchElementException(); } next = current = previous; previous = previous.previous; nextIndex--; return current; } @Override public int nextIndex() { return nextIndex; } @Override public int previousIndex() { return nextIndex - 1; } @Override public void set(Entry<K, V> e) { throw new UnsupportedOperationException(); } @Override public void add(Entry<K, V> e) { throw new UnsupportedOperationException(); } void setValue(@ParametricNullness V value) { checkState(current != null); current.setValue(value); } } /** An {@code Iterator} over distinct keys in key head order. */ private final class DistinctKeyIterator implements Iterator<K> { final Set<K> seenKeys = Sets.newHashSetWithExpectedSize(keySet().size()); @Nullable Node<K, V> next = head; @Nullable Node<K, V> current; int expectedModCount = modCount; private void checkForConcurrentModification() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } @Override public boolean hasNext() { checkForConcurrentModification(); return next != null; } @Override @ParametricNullness public K next() { checkForConcurrentModification(); if (next == null) { throw new NoSuchElementException(); } current = next; seenKeys.add(current.getKey()); do { // skip ahead to next unseen key next = next.next; } while ((next != null) && !seenKeys.add(next.getKey())); return current.getKey(); } @Override public void remove() { checkForConcurrentModification(); checkState(current != null, "no calls to next() since the last call to remove()"); removeAllNodes(current.getKey()); current = null; expectedModCount = modCount; } } /** A {@code ListIterator} over values for a specified key. */ private final class ValueForKeyIterator implements ListIterator<V> { @ParametricNullness final K key; int nextIndex; @Nullable Node<K, V> next; @Nullable Node<K, V> current; @Nullable Node<K, V> previous; /** Constructs a new iterator over all values for the specified key. */ ValueForKeyIterator(@ParametricNullness K key) { this.key = key; KeyList<K, V> keyList = keyToKeyList.get(key); next = (keyList == null) ? null : keyList.head; } /** * Constructs a new iterator over all values for the specified key starting at the specified * index. This constructor is optimized so that it starts at either the head or the tail, * depending on which is closer to the specified index. This allows adds to the tail to be done * in constant time. * * @throws IndexOutOfBoundsException if index is invalid */ ValueForKeyIterator(@ParametricNullness K key, int index) { KeyList<K, V> keyList = keyToKeyList.get(key); int size = (keyList == null) ? 0 : keyList.count; checkPositionIndex(index, size); if (index >= (size / 2)) { previous = (keyList == null) ? null : keyList.tail; nextIndex = size; while (index++ < size) { previous(); } } else { next = (keyList == null) ? null : keyList.head; while (index-- > 0) { next(); } } this.key = key; current = null; } @Override public boolean hasNext() { return next != null; } @CanIgnoreReturnValue @Override @ParametricNullness public V next() { if (next == null) { throw new NoSuchElementException(); } previous = current = next; next = next.nextSibling; nextIndex++; return current.getValue(); } @Override public boolean hasPrevious() { return previous != null; } @CanIgnoreReturnValue @Override @ParametricNullness public V previous() { if (previous == null) { throw new NoSuchElementException(); } next = current = previous; previous = previous.previousSibling; nextIndex--; return current.getValue(); } @Override public int nextIndex() { return nextIndex; } @Override public int previousIndex() { return nextIndex - 1; } @Override public void remove() { checkState(current != null, "no calls to next() since the last call to remove()"); if (current != next) { // after call to next() previous = current.previousSibling; nextIndex--; } else { // after call to previous() next = current.nextSibling; } removeNode(current); current = null; } @Override public void set(@ParametricNullness V value) { checkState(current != null); current.setValue(value); } @Override public void add(@ParametricNullness V value) { previous = addNode(key, value, next); nextIndex++; current = null; } } // Query Operations @Override public int size() { return size; } @Override public boolean isEmpty() { return head == null; } @Override public boolean containsKey(@Nullable Object key) { return keyToKeyList.containsKey(key); } @Override public boolean containsValue(@Nullable Object value) { return values().contains(value); } // Modification Operations /** * Stores a key-value pair in the multimap. * * @param key key to store in the multimap * @param value value to store in the multimap * @return {@code true} always */ @CanIgnoreReturnValue @Override public boolean put(@ParametricNullness K key, @ParametricNullness V value) { addNode(key, value, null); return true; } // Bulk Operations /** * {@inheritDoc} * * <p>If any entries for the specified {@code key} already exist in the multimap, their values are * changed in-place without affecting the iteration order. * * <p>The returned list is immutable and implements {@link java.util.RandomAccess}. */ @CanIgnoreReturnValue @Override public List<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) { List<V> oldValues = getCopy(key); ListIterator<V> keyValues = new ValueForKeyIterator(key); Iterator<? extends V> newValues = values.iterator(); // Replace existing values, if any. while (keyValues.hasNext() && newValues.hasNext()) { keyValues.next(); keyValues.set(newValues.next()); } // Remove remaining old values, if any. while (keyValues.hasNext()) { keyValues.next(); keyValues.remove(); } // Add remaining new values, if any. while (newValues.hasNext()) { keyValues.add(newValues.next()); } return oldValues; } private List<V> getCopy(@ParametricNullness K key) { return unmodifiableList(Lists.newArrayList(new ValueForKeyIterator(key))); } /** * {@inheritDoc} * * <p>The returned list is immutable and implements {@link java.util.RandomAccess}. */ @CanIgnoreReturnValue @Override public List<V> removeAll(@Nullable Object key) { /* * Safe because all we do is remove values for the key, not add them. (If we wanted to make sure * to call getCopy and removeAllNodes only with a true K, then we could check containsKey first. * But that check wouldn't eliminate the warnings.) */ @SuppressWarnings({"unchecked", "nullness"}) K castKey = (K) key; List<V> oldValues = getCopy(castKey); removeAllNodes(castKey); return oldValues; } @Override public void clear() { head = null; tail = null; keyToKeyList.clear(); size = 0; modCount++; } // Views /** * {@inheritDoc} * * <p>If the multimap is modified while an iteration over the list is in progress (except through * the iterator's own {@code add}, {@code set} or {@code remove} operations) the results of the * iteration are undefined. * * <p>The returned list is not serializable and does not have random access. */ @Override public List<V> get(@ParametricNullness K key) { return new AbstractSequentialList<V>() { @Override public int size() { KeyList<K, V> keyList = keyToKeyList.get(key); return (keyList == null) ? 0 : keyList.count; } @Override public ListIterator<V> listIterator(int index) { return new ValueForKeyIterator(key, index); } }; } @Override Set<K> createKeySet() { @WeakOuter final class KeySetImpl extends Sets.ImprovedAbstractSet<K> { @Override public int size() { return keyToKeyList.size(); } @Override public Iterator<K> iterator() { return new DistinctKeyIterator(); } @Override public boolean contains(@Nullable Object key) { // for performance return containsKey(key); } @Override public boolean remove(@Nullable Object o) { // for performance return !LinkedListMultimap.this.removeAll(o).isEmpty(); } } return new KeySetImpl(); } @Override Multiset<K> createKeys() { return new Multimaps.Keys<K, V>(this); } /** * {@inheritDoc} * * <p>The iterator generated by the returned collection traverses the values in the order they * were added to the multimap. Because the values may have duplicates and follow the insertion * ordering, this method returns a {@link List}, instead of the {@link Collection} specified in * the {@link ListMultimap} interface. */ @Override public List<V> values() { return (List<V>) super.values(); } @Override List<V> createValues() { @WeakOuter final class ValuesImpl extends AbstractSequentialList<V> { @Override public int size() { return size; } @Override public ListIterator<V> listIterator(int index) { NodeIterator nodeItr = new NodeIterator(index); return new TransformedListIterator<Entry<K, V>, V>(nodeItr) { @Override @ParametricNullness V transform(Entry<K, V> entry) { return entry.getValue(); } @Override public void set(@ParametricNullness V value) { nodeItr.setValue(value); } }; } } return new ValuesImpl(); } /** * {@inheritDoc} * * <p>The iterator generated by the returned collection traverses the entries in the order they * were added to the multimap. Because the entries may have duplicates and follow the insertion * ordering, this method returns a {@link List}, instead of the {@link Collection} specified in * the {@link ListMultimap} interface. * * <p>An entry's {@link Entry#getKey} method always returns the same key, regardless of what * happens subsequently. As long as the corresponding key-value mapping is not removed from the * multimap, {@link Entry#getValue} returns the value from the multimap, which may change over * time, and {@link Entry#setValue} modifies that value. Removing the mapping from the multimap * does not alter the value returned by {@code getValue()}, though a subsequent {@code setValue()} * call won't update the multimap but will lead to a revised value being returned by {@code * getValue()}. */ @Override public List<Entry<K, V>> entries() { return (List<Entry<K, V>>) super.entries(); } @Override List<Entry<K, V>> createEntries() { @WeakOuter final class EntriesImpl extends AbstractSequentialList<Entry<K, V>> { @Override public int size() { return size; } @Override public ListIterator<Entry<K, V>> listIterator(int index) { return new NodeIterator(index); } @Override public void forEach(Consumer<? super Entry<K, V>> action) { checkNotNull(action); for (Node<K, V> node = head; node != null; node = node.next) { action.accept(node); } } } return new EntriesImpl(); } @Override Iterator<Entry<K, V>> entryIterator() { throw new AssertionError("should never be called"); } @Override Map<K, Collection<V>> createAsMap() { return new Multimaps.AsMap<>(this); } /** * @serialData the number of distinct keys, and then for each distinct key: the first key, the * number of values for that key, and the key's values, followed by successive keys and values * from the entries() ordering */ @GwtIncompatible @J2ktIncompatible private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeInt(size()); for (Entry<K, V> entry : entries()) { stream.writeObject(entry.getKey()); stream.writeObject(entry.getValue()); } } @GwtIncompatible @J2ktIncompatible private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); keyToKeyList = new LinkedHashMap<>(); int size = stream.readInt(); for (int i = 0; i < size; i++) { @SuppressWarnings("unchecked") // reading data stored by writeObject K key = (K) stream.readObject(); @SuppressWarnings("unchecked") // reading data stored by writeObject V value = (V) stream.readObject(); put(key, value); } } @GwtIncompatible @J2ktIncompatible private static final long serialVersionUID = 0; }
java
github
https://github.com/google/guava
guava/src/com/google/common/collect/LinkedListMultimap.java
#!/usr/bin/python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import MySQLdb as mdb import sys import os if len(sys.argv) < 6: sys.exit("usage: %s <job_name> <build_number> <workload> <iteration> <runtime>" % sys.argv[0]) host = os.environ["MYSQLHOST"] user = os.environ["MYSQLUSER"] pwd = os.environ["MYSQLPWD"] db = os.environ["MYSQLDB"] con = mdb.connect(host, user, pwd, db) print "Connected to mysql" with con: cur = con.cursor() job_name = sys.argv[1] build_number = sys.argv[2] workload = sys.argv[3] iteration = sys.argv[4] runtime = sys.argv[5] cur.execute("INSERT INTO kudu_perf_tpch VALUES(%s, %s, %s, %s, %s, DEFAULT)", (job_name, build_number, workload, iteration, runtime)) rows = cur.fetchall()
unknown
codeparrot/codeparrot-clean
# Copyright 2011 Marco Conti # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Thanks to grt for the fixes import odf.opendocument from odf.table import Table, TableRow, TableCell from odf.text import P # http://stackoverflow.com/a/4544699/1846474 class GrowingList(list): def __setitem__(self, index, value): if index >= len(self): self.extend([None]*(index + 1 - len(self))) list.__setitem__(self, index, value) class ODSReader(object): """Loads ODS file""" def __init__(self, file, clonespannedcolumns=None): self.clonespannedcolumns = clonespannedcolumns self.doc = odf.opendocument.load(file) self.sheets = [] self.sheet_names = [] for sheet in self.doc.spreadsheet.getElementsByType(Table): self.readSheet(sheet) # reads a sheet in the sheet dictionary, storing each sheet as an # array (rows) of arrays (columns) def readSheet(self, sheet): """Reads a sheet in the sheet dictionary Stores each sheet as an array (rows) of arrays (columns) """ name = sheet.getAttribute("name") rows = sheet.getElementsByType(TableRow) arrRows = [] # for each row for row in rows: row_comment = "" arrCells = GrowingList() cells = row.getElementsByType(TableCell) # for each cell count = 0 for cell in cells: # repeated value? repeat = cell.getAttribute("numbercolumnsrepeated") if(not repeat): repeat = 1 spanned = \ int(cell.getAttribute('numbercolumnsspanned') or 0) # clone spanned cells if self.clonespannedcolumns is not None and spanned > 1: repeat = spanned ps = cell.getElementsByType(P) textContent = "" # for each text/text:span node for p in ps: for n in p.childNodes: if (n.nodeType == 1 and n.tagName == "text:span"): for c in n.childNodes: if (c.nodeType == 3): textContent = u'{}{}'.format(textContent, n.data) if (n.nodeType == 3): textContent = u'{}{}'.format(textContent, n.data) if(textContent): if(textContent[0] != "#"): # ignore comments cells for rr in xrange(int(repeat)): # repeated? arrCells[count]=textContent count+=1 else: row_comment = row_comment + textContent + " " else: for rr in xrange(int(repeat)): count+=1 # if row contained something if(len(arrCells)): arrRows.append(arrCells) #else: # print ("Empty or commented row (", row_comment, ")") self.sheets.append(arrRows) self.sheet_names.append(name) def getSheet(self, name): """Returns first sheet with the name name as array (rows, columns)""" return self.sheets[self.sheet_names.index(name)]
unknown
codeparrot/codeparrot-clean
// #docregion import {Directive, forwardRef} from '@angular/core'; import { AbstractControl, NG_VALIDATORS, ValidationErrors, Validator, ValidatorFn, } from '@angular/forms'; // #docregion cross-validation-validator /** An actor's name can't match the actor's role */ export const unambiguousRoleValidator: ValidatorFn = ( control: AbstractControl, ): ValidationErrors | null => { const name = control.get('name'); const role = control.get('role'); return name && role && name.value === role.value ? {identityRevealed: true} : null; }; // #enddocregion cross-validation-validator // #docregion cross-validation-directive @Directive({ selector: '[appUnambiguousRole]', providers: [ { provide: NG_VALIDATORS, useExisting: forwardRef(() => UnambiguousRoleValidatorDirective), multi: true, }, ], }) export class UnambiguousRoleValidatorDirective implements Validator { validate(control: AbstractControl): ValidationErrors | null { return unambiguousRoleValidator(control); } } // #enddocregion cross-validation-directive
typescript
github
https://github.com/angular/angular
adev/src/content/examples/form-validation/src/app/shared/unambiguous-role.ts
#!/usr/bin/python # (c) 2013, Paul Durivage <paul.durivage@rackspace.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: rax_files_objects short_description: Upload, download, and delete objects in Rackspace Cloud Files description: - Upload, download, and delete objects in Rackspace Cloud Files version_added: "1.5" options: clear_meta: description: - Optionally clear existing metadata when applying metadata to existing objects. Selecting this option is only appropriate when setting type=meta type: bool default: 'no' container: description: - The container to use for file object operations. required: true dest: description: - The destination of a "get" operation; i.e. a local directory, "/home/user/myfolder". Used to specify the destination of an operation on a remote object; i.e. a file name, "file1", or a comma-separated list of remote objects, "file1,file2,file17" expires: description: - Used to set an expiration on a file or folder uploaded to Cloud Files. Requires an integer, specifying expiration in seconds meta: description: - A hash of items to set as metadata values on an uploaded file or folder method: description: - The method of operation to be performed. For example, put to upload files to Cloud Files, get to download files from Cloud Files or delete to delete remote objects in Cloud Files choices: - get - put - delete default: get src: description: - Source from which to upload files. Used to specify a remote object as a source for an operation, i.e. a file name, "file1", or a comma-separated list of remote objects, "file1,file2,file17". src and dest are mutually exclusive on remote-only object operations structure: description: - Used to specify whether to maintain nested directory structure when downloading objects from Cloud Files. Setting to false downloads the contents of a container to a single, flat directory type: bool default: 'yes' state: description: - Indicate desired state of the resource choices: ['present', 'absent'] default: present type: description: - Type of object to do work on - Metadata object or a file object choices: - file - meta default: file author: "Paul Durivage (@angstwad)" extends_documentation_fragment: - rackspace - rackspace.openstack ''' EXAMPLES = ''' - name: "Test Cloud Files Objects" hosts: local gather_facts: False tasks: - name: "Get objects from test container" rax_files_objects: container: testcont dest: ~/Downloads/testcont - name: "Get single object from test container" rax_files_objects: container: testcont src: file1 dest: ~/Downloads/testcont - name: "Get several objects from test container" rax_files_objects: container: testcont src: file1,file2,file3 dest: ~/Downloads/testcont - name: "Delete one object in test container" rax_files_objects: container: testcont method: delete dest: file1 - name: "Delete several objects in test container" rax_files_objects: container: testcont method: delete dest: file2,file3,file4 - name: "Delete all objects in test container" rax_files_objects: container: testcont method: delete - name: "Upload all files to test container" rax_files_objects: container: testcont method: put src: ~/Downloads/onehundred - name: "Upload one file to test container" rax_files_objects: container: testcont method: put src: ~/Downloads/testcont/file1 - name: "Upload one file to test container with metadata" rax_files_objects: container: testcont src: ~/Downloads/testcont/file2 method: put meta: testkey: testdata who_uploaded_this: someuser@example.com - name: "Upload one file to test container with TTL of 60 seconds" rax_files_objects: container: testcont method: put src: ~/Downloads/testcont/file3 expires: 60 - name: "Attempt to get remote object that does not exist" rax_files_objects: container: testcont method: get src: FileThatDoesNotExist.jpg dest: ~/Downloads/testcont ignore_errors: yes - name: "Attempt to delete remote object that does not exist" rax_files_objects: container: testcont method: delete dest: FileThatDoesNotExist.jpg ignore_errors: yes - name: "Test Cloud Files Objects Metadata" hosts: local gather_facts: false tasks: - name: "Get metadata on one object" rax_files_objects: container: testcont type: meta dest: file2 - name: "Get metadata on several objects" rax_files_objects: container: testcont type: meta src: file2,file1 - name: "Set metadata on an object" rax_files_objects: container: testcont type: meta dest: file17 method: put meta: key1: value1 key2: value2 clear_meta: true - name: "Verify metadata is set" rax_files_objects: container: testcont type: meta src: file17 - name: "Delete metadata" rax_files_objects: container: testcont type: meta dest: file17 method: delete meta: key1: '' key2: '' - name: "Get metadata on all objects" rax_files_objects: container: testcont type: meta ''' import os try: import pyrax HAS_PYRAX = True except ImportError: HAS_PYRAX = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.rax import rax_argument_spec, rax_required_together, setup_rax_module EXIT_DICT = dict(success=False) META_PREFIX = 'x-object-meta-' def _get_container(module, cf, container): try: return cf.get_container(container) except pyrax.exc.NoSuchContainer as e: module.fail_json(msg=e.message) def _upload_folder(cf, folder, container, ttl=None, headers=None): """ Uploads a folder to Cloud Files. """ total_bytes = 0 for root, dirs, files in os.walk(folder): for fname in files: full_path = os.path.join(root, fname) obj_name = os.path.relpath(full_path, folder) obj_size = os.path.getsize(full_path) cf.upload_file(container, full_path, obj_name=obj_name, return_none=True, ttl=ttl, headers=headers) total_bytes += obj_size return total_bytes def upload(module, cf, container, src, dest, meta, expires): """ Uploads a single object or a folder to Cloud Files Optionally sets an metadata, TTL value (expires), or Content-Disposition and Content-Encoding headers. """ if not src: module.fail_json(msg='src must be specified when uploading') c = _get_container(module, cf, container) src = os.path.abspath(os.path.expanduser(src)) is_dir = os.path.isdir(src) if not is_dir and not os.path.isfile(src) or not os.path.exists(src): module.fail_json(msg='src must be a file or a directory') if dest and is_dir: module.fail_json(msg='dest cannot be set when whole ' 'directories are uploaded') cont_obj = None total_bytes = 0 if dest and not is_dir: try: cont_obj = c.upload_file(src, obj_name=dest, ttl=expires, headers=meta) except Exception as e: module.fail_json(msg=e.message) elif is_dir: try: total_bytes = _upload_folder(cf, src, c, ttl=expires, headers=meta) except Exception as e: module.fail_json(msg=e.message) else: try: cont_obj = c.upload_file(src, ttl=expires, headers=meta) except Exception as e: module.fail_json(msg=e.message) EXIT_DICT['success'] = True EXIT_DICT['container'] = c.name EXIT_DICT['msg'] = "Uploaded %s to container: %s" % (src, c.name) if cont_obj or total_bytes > 0: EXIT_DICT['changed'] = True if meta: EXIT_DICT['meta'] = dict(updated=True) if cont_obj: EXIT_DICT['bytes'] = cont_obj.total_bytes EXIT_DICT['etag'] = cont_obj.etag else: EXIT_DICT['bytes'] = total_bytes module.exit_json(**EXIT_DICT) def download(module, cf, container, src, dest, structure): """ Download objects from Cloud Files to a local path specified by "dest". Optionally disable maintaining a directory structure by by passing a false value to "structure". """ # Looking for an explicit destination if not dest: module.fail_json(msg='dest is a required argument when ' 'downloading from Cloud Files') # Attempt to fetch the container by name c = _get_container(module, cf, container) # Accept a single object name or a comma-separated list of objs # If not specified, get the entire container if src: objs = src.split(',') objs = map(str.strip, objs) else: objs = c.get_object_names() dest = os.path.abspath(os.path.expanduser(dest)) is_dir = os.path.isdir(dest) if not is_dir: module.fail_json(msg='dest must be a directory') results = [] for obj in objs: try: c.download_object(obj, dest, structure=structure) except Exception as e: module.fail_json(msg=e.message) else: results.append(obj) len_results = len(results) len_objs = len(objs) EXIT_DICT['container'] = c.name EXIT_DICT['requested_downloaded'] = results if results: EXIT_DICT['changed'] = True if len_results == len_objs: EXIT_DICT['success'] = True EXIT_DICT['msg'] = "%s objects downloaded to %s" % (len_results, dest) else: EXIT_DICT['msg'] = "Error: only %s of %s objects were " \ "downloaded" % (len_results, len_objs) module.exit_json(**EXIT_DICT) def delete(module, cf, container, src, dest): """ Delete specific objects by proving a single file name or a comma-separated list to src OR dest (but not both). Omitting file name(s) assumes the entire container is to be deleted. """ objs = None if src and dest: module.fail_json(msg="Error: ambiguous instructions; files to be deleted " "have been specified on both src and dest args") elif dest: objs = dest else: objs = src c = _get_container(module, cf, container) if objs: objs = objs.split(',') objs = map(str.strip, objs) else: objs = c.get_object_names() num_objs = len(objs) results = [] for obj in objs: try: result = c.delete_object(obj) except Exception as e: module.fail_json(msg=e.message) else: results.append(result) num_deleted = results.count(True) EXIT_DICT['container'] = c.name EXIT_DICT['deleted'] = num_deleted EXIT_DICT['requested_deleted'] = objs if num_deleted: EXIT_DICT['changed'] = True if num_objs == num_deleted: EXIT_DICT['success'] = True EXIT_DICT['msg'] = "%s objects deleted" % num_deleted else: EXIT_DICT['msg'] = ("Error: only %s of %s objects " "deleted" % (num_deleted, num_objs)) module.exit_json(**EXIT_DICT) def get_meta(module, cf, container, src, dest): """ Get metadata for a single file, comma-separated list, or entire container """ c = _get_container(module, cf, container) objs = None if src and dest: module.fail_json(msg="Error: ambiguous instructions; files to be deleted " "have been specified on both src and dest args") elif dest: objs = dest else: objs = src if objs: objs = objs.split(',') objs = map(str.strip, objs) else: objs = c.get_object_names() results = dict() for obj in objs: try: meta = c.get_object(obj).get_metadata() except Exception as e: module.fail_json(msg=e.message) else: results[obj] = dict() for k, v in meta.items(): meta_key = k.split(META_PREFIX)[-1] results[obj][meta_key] = v EXIT_DICT['container'] = c.name if results: EXIT_DICT['meta_results'] = results EXIT_DICT['success'] = True module.exit_json(**EXIT_DICT) def put_meta(module, cf, container, src, dest, meta, clear_meta): """ Set metadata on a container, single file, or comma-separated list. Passing a true value to clear_meta clears the metadata stored in Cloud Files before setting the new metadata to the value of "meta". """ objs = None if src and dest: module.fail_json(msg="Error: ambiguous instructions; files to set meta" " have been specified on both src and dest args") elif dest: objs = dest else: objs = src objs = objs.split(',') objs = map(str.strip, objs) c = _get_container(module, cf, container) results = [] for obj in objs: try: result = c.get_object(obj).set_metadata(meta, clear=clear_meta) except Exception as e: module.fail_json(msg=e.message) else: results.append(result) EXIT_DICT['container'] = c.name EXIT_DICT['success'] = True if results: EXIT_DICT['changed'] = True EXIT_DICT['num_changed'] = True module.exit_json(**EXIT_DICT) def delete_meta(module, cf, container, src, dest, meta): """ Removes metadata keys and values specified in meta, if any. Deletes on all objects specified by src or dest (but not both), if any; otherwise it deletes keys on all objects in the container """ objs = None if src and dest: module.fail_json(msg="Error: ambiguous instructions; meta keys to be " "deleted have been specified on both src and dest" " args") elif dest: objs = dest else: objs = src objs = objs.split(',') objs = map(str.strip, objs) c = _get_container(module, cf, container) results = [] # Num of metadata keys removed, not objects affected for obj in objs: if meta: for k, v in meta.items(): try: result = c.get_object(obj).remove_metadata_key(k) except Exception as e: module.fail_json(msg=e.message) else: results.append(result) else: try: o = c.get_object(obj) except pyrax.exc.NoSuchObject as e: module.fail_json(msg=e.message) for k, v in o.get_metadata().items(): try: result = o.remove_metadata_key(k) except Exception as e: module.fail_json(msg=e.message) results.append(result) EXIT_DICT['container'] = c.name EXIT_DICT['success'] = True if results: EXIT_DICT['changed'] = True EXIT_DICT['num_deleted'] = len(results) module.exit_json(**EXIT_DICT) def cloudfiles(module, container, src, dest, method, typ, meta, clear_meta, structure, expires): """ Dispatch from here to work with metadata or file objects """ cf = pyrax.cloudfiles if cf is None: module.fail_json(msg='Failed to instantiate client. This ' 'typically indicates an invalid region or an ' 'incorrectly capitalized region name.') if typ == "file": if method == 'put': upload(module, cf, container, src, dest, meta, expires) elif method == 'get': download(module, cf, container, src, dest, structure) elif method == 'delete': delete(module, cf, container, src, dest) else: if method == 'get': get_meta(module, cf, container, src, dest) if method == 'put': put_meta(module, cf, container, src, dest, meta, clear_meta) if method == 'delete': delete_meta(module, cf, container, src, dest, meta) def main(): argument_spec = rax_argument_spec() argument_spec.update( dict( container=dict(required=True), src=dict(), dest=dict(), method=dict(default='get', choices=['put', 'get', 'delete']), type=dict(default='file', choices=['file', 'meta']), meta=dict(type='dict', default=dict()), clear_meta=dict(default=False, type='bool'), structure=dict(default=True, type='bool'), expires=dict(type='int'), ) ) module = AnsibleModule( argument_spec=argument_spec, required_together=rax_required_together() ) if not HAS_PYRAX: module.fail_json(msg='pyrax is required for this module') container = module.params.get('container') src = module.params.get('src') dest = module.params.get('dest') method = module.params.get('method') typ = module.params.get('type') meta = module.params.get('meta') clear_meta = module.params.get('clear_meta') structure = module.params.get('structure') expires = module.params.get('expires') if clear_meta and not typ == 'meta': module.fail_json(msg='clear_meta can only be used when setting metadata') setup_rax_module(module, pyrax) cloudfiles(module, container, src, dest, method, typ, meta, clear_meta, structure, expires) if __name__ == '__main__': main()
unknown
codeparrot/codeparrot-clean
from __future__ import division, absolute_import, print_function import sys import warnings import numpy as np from numpy import array, arange, nditer, all from numpy.compat import asbytes, sixu from numpy.core.multiarray_tests import test_nditer_too_large from numpy.testing import ( run_module_suite, assert_, assert_equal, assert_array_equal, assert_raises, assert_warns, dec, HAS_REFCOUNT, suppress_warnings ) def iter_multi_index(i): ret = [] while not i.finished: ret.append(i.multi_index) i.iternext() return ret def iter_indices(i): ret = [] while not i.finished: ret.append(i.index) i.iternext() return ret def iter_iterindices(i): ret = [] while not i.finished: ret.append(i.iterindex) i.iternext() return ret @dec.skipif(not HAS_REFCOUNT, "python does not have sys.getrefcount") def test_iter_refcount(): # Make sure the iterator doesn't leak # Basic a = arange(6) dt = np.dtype('f4').newbyteorder() rc_a = sys.getrefcount(a) rc_dt = sys.getrefcount(dt) it = nditer(a, [], [['readwrite', 'updateifcopy']], casting='unsafe', op_dtypes=[dt]) assert_(not it.iterationneedsapi) assert_(sys.getrefcount(a) > rc_a) assert_(sys.getrefcount(dt) > rc_dt) it = None assert_equal(sys.getrefcount(a), rc_a) assert_equal(sys.getrefcount(dt), rc_dt) # With a copy a = arange(6, dtype='f4') dt = np.dtype('f4') rc_a = sys.getrefcount(a) rc_dt = sys.getrefcount(dt) it = nditer(a, [], [['readwrite']], op_dtypes=[dt]) rc2_a = sys.getrefcount(a) rc2_dt = sys.getrefcount(dt) it2 = it.copy() assert_(sys.getrefcount(a) > rc2_a) assert_(sys.getrefcount(dt) > rc2_dt) it = None assert_equal(sys.getrefcount(a), rc2_a) assert_equal(sys.getrefcount(dt), rc2_dt) it2 = None assert_equal(sys.getrefcount(a), rc_a) assert_equal(sys.getrefcount(dt), rc_dt) del it2 # avoid pyflakes unused variable warning def test_iter_best_order(): # The iterator should always find the iteration order # with increasing memory addresses # Test the ordering for 1-D to 5-D shapes for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]: a = arange(np.prod(shape)) # Test each combination of positive and negative strides for dirs in range(2**len(shape)): dirs_index = [slice(None)]*len(shape) for bit in range(len(shape)): if ((2**bit) & dirs): dirs_index[bit] = slice(None, None, -1) dirs_index = tuple(dirs_index) aview = a.reshape(shape)[dirs_index] # C-order i = nditer(aview, [], [['readonly']]) assert_equal([x for x in i], a) # Fortran-order i = nditer(aview.T, [], [['readonly']]) assert_equal([x for x in i], a) # Other order if len(shape) > 2: i = nditer(aview.swapaxes(0, 1), [], [['readonly']]) assert_equal([x for x in i], a) def test_iter_c_order(): # Test forcing C order # Test the ordering for 1-D to 5-D shapes for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]: a = arange(np.prod(shape)) # Test each combination of positive and negative strides for dirs in range(2**len(shape)): dirs_index = [slice(None)]*len(shape) for bit in range(len(shape)): if ((2**bit) & dirs): dirs_index[bit] = slice(None, None, -1) dirs_index = tuple(dirs_index) aview = a.reshape(shape)[dirs_index] # C-order i = nditer(aview, order='C') assert_equal([x for x in i], aview.ravel(order='C')) # Fortran-order i = nditer(aview.T, order='C') assert_equal([x for x in i], aview.T.ravel(order='C')) # Other order if len(shape) > 2: i = nditer(aview.swapaxes(0, 1), order='C') assert_equal([x for x in i], aview.swapaxes(0, 1).ravel(order='C')) def test_iter_f_order(): # Test forcing F order # Test the ordering for 1-D to 5-D shapes for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]: a = arange(np.prod(shape)) # Test each combination of positive and negative strides for dirs in range(2**len(shape)): dirs_index = [slice(None)]*len(shape) for bit in range(len(shape)): if ((2**bit) & dirs): dirs_index[bit] = slice(None, None, -1) dirs_index = tuple(dirs_index) aview = a.reshape(shape)[dirs_index] # C-order i = nditer(aview, order='F') assert_equal([x for x in i], aview.ravel(order='F')) # Fortran-order i = nditer(aview.T, order='F') assert_equal([x for x in i], aview.T.ravel(order='F')) # Other order if len(shape) > 2: i = nditer(aview.swapaxes(0, 1), order='F') assert_equal([x for x in i], aview.swapaxes(0, 1).ravel(order='F')) def test_iter_c_or_f_order(): # Test forcing any contiguous (C or F) order # Test the ordering for 1-D to 5-D shapes for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]: a = arange(np.prod(shape)) # Test each combination of positive and negative strides for dirs in range(2**len(shape)): dirs_index = [slice(None)]*len(shape) for bit in range(len(shape)): if ((2**bit) & dirs): dirs_index[bit] = slice(None, None, -1) dirs_index = tuple(dirs_index) aview = a.reshape(shape)[dirs_index] # C-order i = nditer(aview, order='A') assert_equal([x for x in i], aview.ravel(order='A')) # Fortran-order i = nditer(aview.T, order='A') assert_equal([x for x in i], aview.T.ravel(order='A')) # Other order if len(shape) > 2: i = nditer(aview.swapaxes(0, 1), order='A') assert_equal([x for x in i], aview.swapaxes(0, 1).ravel(order='A')) def test_iter_best_order_multi_index_1d(): # The multi-indices should be correct with any reordering a = arange(4) # 1D order i = nditer(a, ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0,), (1,), (2,), (3,)]) # 1D reversed order i = nditer(a[::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(3,), (2,), (1,), (0,)]) def test_iter_best_order_multi_index_2d(): # The multi-indices should be correct with any reordering a = arange(6) # 2D C-order i = nditer(a.reshape(2, 3), ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]) # 2D Fortran-order i = nditer(a.reshape(2, 3).copy(order='F'), ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 0), (1, 0), (0, 1), (1, 1), (0, 2), (1, 2)]) # 2D reversed C-order i = nditer(a.reshape(2, 3)[::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(1, 0), (1, 1), (1, 2), (0, 0), (0, 1), (0, 2)]) i = nditer(a.reshape(2, 3)[:, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 2), (0, 1), (0, 0), (1, 2), (1, 1), (1, 0)]) i = nditer(a.reshape(2, 3)[::-1, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(1, 2), (1, 1), (1, 0), (0, 2), (0, 1), (0, 0)]) # 2D reversed Fortran-order i = nditer(a.reshape(2, 3).copy(order='F')[::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(1, 0), (0, 0), (1, 1), (0, 1), (1, 2), (0, 2)]) i = nditer(a.reshape(2, 3).copy(order='F')[:, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 2), (1, 2), (0, 1), (1, 1), (0, 0), (1, 0)]) i = nditer(a.reshape(2, 3).copy(order='F')[::-1, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(1, 2), (0, 2), (1, 1), (0, 1), (1, 0), (0, 0)]) def test_iter_best_order_multi_index_3d(): # The multi-indices should be correct with any reordering a = arange(12) # 3D C-order i = nditer(a.reshape(2, 3, 2), ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (0, 2, 0), (0, 2, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1), (1, 2, 0), (1, 2, 1)]) # 3D Fortran-order i = nditer(a.reshape(2, 3, 2).copy(order='F'), ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 2, 0), (1, 2, 0), (0, 0, 1), (1, 0, 1), (0, 1, 1), (1, 1, 1), (0, 2, 1), (1, 2, 1)]) # 3D reversed C-order i = nditer(a.reshape(2, 3, 2)[::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1), (1, 2, 0), (1, 2, 1), (0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (0, 2, 0), (0, 2, 1)]) i = nditer(a.reshape(2, 3, 2)[:, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 2, 0), (0, 2, 1), (0, 1, 0), (0, 1, 1), (0, 0, 0), (0, 0, 1), (1, 2, 0), (1, 2, 1), (1, 1, 0), (1, 1, 1), (1, 0, 0), (1, 0, 1)]) i = nditer(a.reshape(2, 3, 2)[:,:, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 0, 1), (0, 0, 0), (0, 1, 1), (0, 1, 0), (0, 2, 1), (0, 2, 0), (1, 0, 1), (1, 0, 0), (1, 1, 1), (1, 1, 0), (1, 2, 1), (1, 2, 0)]) # 3D reversed Fortran-order i = nditer(a.reshape(2, 3, 2).copy(order='F')[::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(1, 0, 0), (0, 0, 0), (1, 1, 0), (0, 1, 0), (1, 2, 0), (0, 2, 0), (1, 0, 1), (0, 0, 1), (1, 1, 1), (0, 1, 1), (1, 2, 1), (0, 2, 1)]) i = nditer(a.reshape(2, 3, 2).copy(order='F')[:, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 2, 0), (1, 2, 0), (0, 1, 0), (1, 1, 0), (0, 0, 0), (1, 0, 0), (0, 2, 1), (1, 2, 1), (0, 1, 1), (1, 1, 1), (0, 0, 1), (1, 0, 1)]) i = nditer(a.reshape(2, 3, 2).copy(order='F')[:,:, ::-1], ['multi_index'], [['readonly']]) assert_equal(iter_multi_index(i), [(0, 0, 1), (1, 0, 1), (0, 1, 1), (1, 1, 1), (0, 2, 1), (1, 2, 1), (0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 2, 0), (1, 2, 0)]) def test_iter_best_order_c_index_1d(): # The C index should be correct with any reordering a = arange(4) # 1D order i = nditer(a, ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 1, 2, 3]) # 1D reversed order i = nditer(a[::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [3, 2, 1, 0]) def test_iter_best_order_c_index_2d(): # The C index should be correct with any reordering a = arange(6) # 2D C-order i = nditer(a.reshape(2, 3), ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 1, 2, 3, 4, 5]) # 2D Fortran-order i = nditer(a.reshape(2, 3).copy(order='F'), ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 3, 1, 4, 2, 5]) # 2D reversed C-order i = nditer(a.reshape(2, 3)[::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [3, 4, 5, 0, 1, 2]) i = nditer(a.reshape(2, 3)[:, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [2, 1, 0, 5, 4, 3]) i = nditer(a.reshape(2, 3)[::-1, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [5, 4, 3, 2, 1, 0]) # 2D reversed Fortran-order i = nditer(a.reshape(2, 3).copy(order='F')[::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [3, 0, 4, 1, 5, 2]) i = nditer(a.reshape(2, 3).copy(order='F')[:, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [2, 5, 1, 4, 0, 3]) i = nditer(a.reshape(2, 3).copy(order='F')[::-1, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [5, 2, 4, 1, 3, 0]) def test_iter_best_order_c_index_3d(): # The C index should be correct with any reordering a = arange(12) # 3D C-order i = nditer(a.reshape(2, 3, 2), ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) # 3D Fortran-order i = nditer(a.reshape(2, 3, 2).copy(order='F'), ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 6, 2, 8, 4, 10, 1, 7, 3, 9, 5, 11]) # 3D reversed C-order i = nditer(a.reshape(2, 3, 2)[::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5]) i = nditer(a.reshape(2, 3, 2)[:, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [4, 5, 2, 3, 0, 1, 10, 11, 8, 9, 6, 7]) i = nditer(a.reshape(2, 3, 2)[:,:, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10]) # 3D reversed Fortran-order i = nditer(a.reshape(2, 3, 2).copy(order='F')[::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [6, 0, 8, 2, 10, 4, 7, 1, 9, 3, 11, 5]) i = nditer(a.reshape(2, 3, 2).copy(order='F')[:, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [4, 10, 2, 8, 0, 6, 5, 11, 3, 9, 1, 7]) i = nditer(a.reshape(2, 3, 2).copy(order='F')[:,:, ::-1], ['c_index'], [['readonly']]) assert_equal(iter_indices(i), [1, 7, 3, 9, 5, 11, 0, 6, 2, 8, 4, 10]) def test_iter_best_order_f_index_1d(): # The Fortran index should be correct with any reordering a = arange(4) # 1D order i = nditer(a, ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 1, 2, 3]) # 1D reversed order i = nditer(a[::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [3, 2, 1, 0]) def test_iter_best_order_f_index_2d(): # The Fortran index should be correct with any reordering a = arange(6) # 2D C-order i = nditer(a.reshape(2, 3), ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 2, 4, 1, 3, 5]) # 2D Fortran-order i = nditer(a.reshape(2, 3).copy(order='F'), ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 1, 2, 3, 4, 5]) # 2D reversed C-order i = nditer(a.reshape(2, 3)[::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [1, 3, 5, 0, 2, 4]) i = nditer(a.reshape(2, 3)[:, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [4, 2, 0, 5, 3, 1]) i = nditer(a.reshape(2, 3)[::-1, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [5, 3, 1, 4, 2, 0]) # 2D reversed Fortran-order i = nditer(a.reshape(2, 3).copy(order='F')[::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [1, 0, 3, 2, 5, 4]) i = nditer(a.reshape(2, 3).copy(order='F')[:, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [4, 5, 2, 3, 0, 1]) i = nditer(a.reshape(2, 3).copy(order='F')[::-1, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [5, 4, 3, 2, 1, 0]) def test_iter_best_order_f_index_3d(): # The Fortran index should be correct with any reordering a = arange(12) # 3D C-order i = nditer(a.reshape(2, 3, 2), ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 6, 2, 8, 4, 10, 1, 7, 3, 9, 5, 11]) # 3D Fortran-order i = nditer(a.reshape(2, 3, 2).copy(order='F'), ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) # 3D reversed C-order i = nditer(a.reshape(2, 3, 2)[::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [1, 7, 3, 9, 5, 11, 0, 6, 2, 8, 4, 10]) i = nditer(a.reshape(2, 3, 2)[:, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [4, 10, 2, 8, 0, 6, 5, 11, 3, 9, 1, 7]) i = nditer(a.reshape(2, 3, 2)[:,:, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [6, 0, 8, 2, 10, 4, 7, 1, 9, 3, 11, 5]) # 3D reversed Fortran-order i = nditer(a.reshape(2, 3, 2).copy(order='F')[::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10]) i = nditer(a.reshape(2, 3, 2).copy(order='F')[:, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [4, 5, 2, 3, 0, 1, 10, 11, 8, 9, 6, 7]) i = nditer(a.reshape(2, 3, 2).copy(order='F')[:,:, ::-1], ['f_index'], [['readonly']]) assert_equal(iter_indices(i), [6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5]) def test_iter_no_inner_full_coalesce(): # Check no_inner iterators which coalesce into a single inner loop for shape in [(5,), (3, 4), (2, 3, 4), (2, 3, 4, 3), (2, 3, 2, 2, 3)]: size = np.prod(shape) a = arange(size) # Test each combination of forward and backwards indexing for dirs in range(2**len(shape)): dirs_index = [slice(None)]*len(shape) for bit in range(len(shape)): if ((2**bit) & dirs): dirs_index[bit] = slice(None, None, -1) dirs_index = tuple(dirs_index) aview = a.reshape(shape)[dirs_index] # C-order i = nditer(aview, ['external_loop'], [['readonly']]) assert_equal(i.ndim, 1) assert_equal(i[0].shape, (size,)) # Fortran-order i = nditer(aview.T, ['external_loop'], [['readonly']]) assert_equal(i.ndim, 1) assert_equal(i[0].shape, (size,)) # Other order if len(shape) > 2: i = nditer(aview.swapaxes(0, 1), ['external_loop'], [['readonly']]) assert_equal(i.ndim, 1) assert_equal(i[0].shape, (size,)) def test_iter_no_inner_dim_coalescing(): # Check no_inner iterators whose dimensions may not coalesce completely # Skipping the last element in a dimension prevents coalescing # with the next-bigger dimension a = arange(24).reshape(2, 3, 4)[:,:, :-1] i = nditer(a, ['external_loop'], [['readonly']]) assert_equal(i.ndim, 2) assert_equal(i[0].shape, (3,)) a = arange(24).reshape(2, 3, 4)[:, :-1,:] i = nditer(a, ['external_loop'], [['readonly']]) assert_equal(i.ndim, 2) assert_equal(i[0].shape, (8,)) a = arange(24).reshape(2, 3, 4)[:-1,:,:] i = nditer(a, ['external_loop'], [['readonly']]) assert_equal(i.ndim, 1) assert_equal(i[0].shape, (12,)) # Even with lots of 1-sized dimensions, should still coalesce a = arange(24).reshape(1, 1, 2, 1, 1, 3, 1, 1, 4, 1, 1) i = nditer(a, ['external_loop'], [['readonly']]) assert_equal(i.ndim, 1) assert_equal(i[0].shape, (24,)) def test_iter_dim_coalescing(): # Check that the correct number of dimensions are coalesced # Tracking a multi-index disables coalescing a = arange(24).reshape(2, 3, 4) i = nditer(a, ['multi_index'], [['readonly']]) assert_equal(i.ndim, 3) # A tracked index can allow coalescing if it's compatible with the array a3d = arange(24).reshape(2, 3, 4) i = nditer(a3d, ['c_index'], [['readonly']]) assert_equal(i.ndim, 1) i = nditer(a3d.swapaxes(0, 1), ['c_index'], [['readonly']]) assert_equal(i.ndim, 3) i = nditer(a3d.T, ['c_index'], [['readonly']]) assert_equal(i.ndim, 3) i = nditer(a3d.T, ['f_index'], [['readonly']]) assert_equal(i.ndim, 1) i = nditer(a3d.T.swapaxes(0, 1), ['f_index'], [['readonly']]) assert_equal(i.ndim, 3) # When C or F order is forced, coalescing may still occur a3d = arange(24).reshape(2, 3, 4) i = nditer(a3d, order='C') assert_equal(i.ndim, 1) i = nditer(a3d.T, order='C') assert_equal(i.ndim, 3) i = nditer(a3d, order='F') assert_equal(i.ndim, 3) i = nditer(a3d.T, order='F') assert_equal(i.ndim, 1) i = nditer(a3d, order='A') assert_equal(i.ndim, 1) i = nditer(a3d.T, order='A') assert_equal(i.ndim, 1) def test_iter_broadcasting(): # Standard NumPy broadcasting rules # 1D with scalar i = nditer([arange(6), np.int32(2)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 6) assert_equal(i.shape, (6,)) # 2D with scalar i = nditer([arange(6).reshape(2, 3), np.int32(2)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 6) assert_equal(i.shape, (2, 3)) # 2D with 1D i = nditer([arange(6).reshape(2, 3), arange(3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 6) assert_equal(i.shape, (2, 3)) i = nditer([arange(2).reshape(2, 1), arange(3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 6) assert_equal(i.shape, (2, 3)) # 2D with 2D i = nditer([arange(2).reshape(2, 1), arange(3).reshape(1, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 6) assert_equal(i.shape, (2, 3)) # 3D with scalar i = nditer([np.int32(2), arange(24).reshape(4, 2, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) # 3D with 1D i = nditer([arange(3), arange(24).reshape(4, 2, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) i = nditer([arange(3), arange(8).reshape(4, 2, 1)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) # 3D with 2D i = nditer([arange(6).reshape(2, 3), arange(24).reshape(4, 2, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) i = nditer([arange(2).reshape(2, 1), arange(24).reshape(4, 2, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) i = nditer([arange(3).reshape(1, 3), arange(8).reshape(4, 2, 1)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) # 3D with 3D i = nditer([arange(2).reshape(1, 2, 1), arange(3).reshape(1, 1, 3), arange(4).reshape(4, 1, 1)], ['multi_index'], [['readonly']]*3) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) i = nditer([arange(6).reshape(1, 2, 3), arange(4).reshape(4, 1, 1)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) i = nditer([arange(24).reshape(4, 2, 3), arange(12).reshape(4, 1, 3)], ['multi_index'], [['readonly']]*2) assert_equal(i.itersize, 24) assert_equal(i.shape, (4, 2, 3)) def test_iter_itershape(): # Check that allocated outputs work with a specified shape a = np.arange(6, dtype='i2').reshape(2, 3) i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']], op_axes=[[0, 1, None], None], itershape=(-1, -1, 4)) assert_equal(i.operands[1].shape, (2, 3, 4)) assert_equal(i.operands[1].strides, (24, 8, 2)) i = nditer([a.T, None], [], [['readonly'], ['writeonly', 'allocate']], op_axes=[[0, 1, None], None], itershape=(-1, -1, 4)) assert_equal(i.operands[1].shape, (3, 2, 4)) assert_equal(i.operands[1].strides, (8, 24, 2)) i = nditer([a.T, None], [], [['readonly'], ['writeonly', 'allocate']], order='F', op_axes=[[0, 1, None], None], itershape=(-1, -1, 4)) assert_equal(i.operands[1].shape, (3, 2, 4)) assert_equal(i.operands[1].strides, (2, 6, 12)) # If we specify 1 in the itershape, it shouldn't allow broadcasting # of that dimension to a bigger value assert_raises(ValueError, nditer, [a, None], [], [['readonly'], ['writeonly', 'allocate']], op_axes=[[0, 1, None], None], itershape=(-1, 1, 4)) # Test bug that for no op_axes but itershape, they are NULLed correctly i = np.nditer([np.ones(2), None, None], itershape=(2,)) def test_iter_broadcasting_errors(): # Check that errors are thrown for bad broadcasting shapes # 1D with 1D assert_raises(ValueError, nditer, [arange(2), arange(3)], [], [['readonly']]*2) # 2D with 1D assert_raises(ValueError, nditer, [arange(6).reshape(2, 3), arange(2)], [], [['readonly']]*2) # 2D with 2D assert_raises(ValueError, nditer, [arange(6).reshape(2, 3), arange(9).reshape(3, 3)], [], [['readonly']]*2) assert_raises(ValueError, nditer, [arange(6).reshape(2, 3), arange(4).reshape(2, 2)], [], [['readonly']]*2) # 3D with 3D assert_raises(ValueError, nditer, [arange(36).reshape(3, 3, 4), arange(24).reshape(2, 3, 4)], [], [['readonly']]*2) assert_raises(ValueError, nditer, [arange(8).reshape(2, 4, 1), arange(24).reshape(2, 3, 4)], [], [['readonly']]*2) # Verify that the error message mentions the right shapes try: nditer([arange(2).reshape(1, 2, 1), arange(3).reshape(1, 3), arange(6).reshape(2, 3)], [], [['readonly'], ['readonly'], ['writeonly', 'no_broadcast']]) raise AssertionError('Should have raised a broadcast error') except ValueError as e: msg = str(e) # The message should contain the shape of the 3rd operand assert_(msg.find('(2,3)') >= 0, 'Message "%s" doesn\'t contain operand shape (2,3)' % msg) # The message should contain the broadcast shape assert_(msg.find('(1,2,3)') >= 0, 'Message "%s" doesn\'t contain broadcast shape (1,2,3)' % msg) try: nditer([arange(6).reshape(2, 3), arange(2)], [], [['readonly'], ['readonly']], op_axes=[[0, 1], [0, np.newaxis]], itershape=(4, 3)) raise AssertionError('Should have raised a broadcast error') except ValueError as e: msg = str(e) # The message should contain "shape->remappedshape" for each operand assert_(msg.find('(2,3)->(2,3)') >= 0, 'Message "%s" doesn\'t contain operand shape (2,3)->(2,3)' % msg) assert_(msg.find('(2,)->(2,newaxis)') >= 0, ('Message "%s" doesn\'t contain remapped operand shape' + '(2,)->(2,newaxis)') % msg) # The message should contain the itershape parameter assert_(msg.find('(4,3)') >= 0, 'Message "%s" doesn\'t contain itershape parameter (4,3)' % msg) try: nditer([np.zeros((2, 1, 1)), np.zeros((2,))], [], [['writeonly', 'no_broadcast'], ['readonly']]) raise AssertionError('Should have raised a broadcast error') except ValueError as e: msg = str(e) # The message should contain the shape of the bad operand assert_(msg.find('(2,1,1)') >= 0, 'Message "%s" doesn\'t contain operand shape (2,1,1)' % msg) # The message should contain the broadcast shape assert_(msg.find('(2,1,2)') >= 0, 'Message "%s" doesn\'t contain the broadcast shape (2,1,2)' % msg) def test_iter_flags_errors(): # Check that bad combinations of flags produce errors a = arange(6) # Not enough operands assert_raises(ValueError, nditer, [], [], []) # Too many operands assert_raises(ValueError, nditer, [a]*100, [], [['readonly']]*100) # Bad global flag assert_raises(ValueError, nditer, [a], ['bad flag'], [['readonly']]) # Bad op flag assert_raises(ValueError, nditer, [a], [], [['readonly', 'bad flag']]) # Bad order parameter assert_raises(ValueError, nditer, [a], [], [['readonly']], order='G') # Bad casting parameter assert_raises(ValueError, nditer, [a], [], [['readonly']], casting='noon') # op_flags must match ops assert_raises(ValueError, nditer, [a]*3, [], [['readonly']]*2) # Cannot track both a C and an F index assert_raises(ValueError, nditer, a, ['c_index', 'f_index'], [['readonly']]) # Inner iteration and multi-indices/indices are incompatible assert_raises(ValueError, nditer, a, ['external_loop', 'multi_index'], [['readonly']]) assert_raises(ValueError, nditer, a, ['external_loop', 'c_index'], [['readonly']]) assert_raises(ValueError, nditer, a, ['external_loop', 'f_index'], [['readonly']]) # Must specify exactly one of readwrite/readonly/writeonly per operand assert_raises(ValueError, nditer, a, [], [[]]) assert_raises(ValueError, nditer, a, [], [['readonly', 'writeonly']]) assert_raises(ValueError, nditer, a, [], [['readonly', 'readwrite']]) assert_raises(ValueError, nditer, a, [], [['writeonly', 'readwrite']]) assert_raises(ValueError, nditer, a, [], [['readonly', 'writeonly', 'readwrite']]) # Python scalars are always readonly assert_raises(TypeError, nditer, 1.5, [], [['writeonly']]) assert_raises(TypeError, nditer, 1.5, [], [['readwrite']]) # Array scalars are always readonly assert_raises(TypeError, nditer, np.int32(1), [], [['writeonly']]) assert_raises(TypeError, nditer, np.int32(1), [], [['readwrite']]) # Check readonly array a.flags.writeable = False assert_raises(ValueError, nditer, a, [], [['writeonly']]) assert_raises(ValueError, nditer, a, [], [['readwrite']]) a.flags.writeable = True # Multi-indices available only with the multi_index flag i = nditer(arange(6), [], [['readonly']]) assert_raises(ValueError, lambda i:i.multi_index, i) # Index available only with an index flag assert_raises(ValueError, lambda i:i.index, i) # GotoCoords and GotoIndex incompatible with buffering or no_inner def assign_multi_index(i): i.multi_index = (0,) def assign_index(i): i.index = 0 def assign_iterindex(i): i.iterindex = 0 def assign_iterrange(i): i.iterrange = (0, 1) i = nditer(arange(6), ['external_loop']) assert_raises(ValueError, assign_multi_index, i) assert_raises(ValueError, assign_index, i) assert_raises(ValueError, assign_iterindex, i) assert_raises(ValueError, assign_iterrange, i) i = nditer(arange(6), ['buffered']) assert_raises(ValueError, assign_multi_index, i) assert_raises(ValueError, assign_index, i) assert_raises(ValueError, assign_iterrange, i) # Can't iterate if size is zero assert_raises(ValueError, nditer, np.array([])) def test_iter_slice(): a, b, c = np.arange(3), np.arange(3), np.arange(3.) i = nditer([a, b, c], [], ['readwrite']) i[0:2] = (3, 3) assert_equal(a, [3, 1, 2]) assert_equal(b, [3, 1, 2]) assert_equal(c, [0, 1, 2]) i[1] = 12 assert_equal(i[0:2], [3, 12]) def test_iter_nbo_align_contig(): # Check that byte order, alignment, and contig changes work # Byte order change by requesting a specific dtype a = np.arange(6, dtype='f4') au = a.byteswap().newbyteorder() assert_(a.dtype.byteorder != au.dtype.byteorder) i = nditer(au, [], [['readwrite', 'updateifcopy']], casting='equiv', op_dtypes=[np.dtype('f4')]) assert_equal(i.dtypes[0].byteorder, a.dtype.byteorder) assert_equal(i.operands[0].dtype.byteorder, a.dtype.byteorder) assert_equal(i.operands[0], a) i.operands[0][:] = 2 i = None assert_equal(au, [2]*6) # Byte order change by requesting NBO a = np.arange(6, dtype='f4') au = a.byteswap().newbyteorder() assert_(a.dtype.byteorder != au.dtype.byteorder) i = nditer(au, [], [['readwrite', 'updateifcopy', 'nbo']], casting='equiv') assert_equal(i.dtypes[0].byteorder, a.dtype.byteorder) assert_equal(i.operands[0].dtype.byteorder, a.dtype.byteorder) assert_equal(i.operands[0], a) i.operands[0][:] = 2 i = None assert_equal(au, [2]*6) # Unaligned input a = np.zeros((6*4+1,), dtype='i1')[1:] a.dtype = 'f4' a[:] = np.arange(6, dtype='f4') assert_(not a.flags.aligned) # Without 'aligned', shouldn't copy i = nditer(a, [], [['readonly']]) assert_(not i.operands[0].flags.aligned) assert_equal(i.operands[0], a) # With 'aligned', should make a copy i = nditer(a, [], [['readwrite', 'updateifcopy', 'aligned']]) assert_(i.operands[0].flags.aligned) assert_equal(i.operands[0], a) i.operands[0][:] = 3 i = None assert_equal(a, [3]*6) # Discontiguous input a = arange(12) # If it is contiguous, shouldn't copy i = nditer(a[:6], [], [['readonly']]) assert_(i.operands[0].flags.contiguous) assert_equal(i.operands[0], a[:6]) # If it isn't contiguous, should buffer i = nditer(a[::2], ['buffered', 'external_loop'], [['readonly', 'contig']], buffersize=10) assert_(i[0].flags.contiguous) assert_equal(i[0], a[::2]) def test_iter_array_cast(): # Check that arrays are cast as requested # No cast 'f4' -> 'f4' a = np.arange(6, dtype='f4').reshape(2, 3) i = nditer(a, [], [['readwrite']], op_dtypes=[np.dtype('f4')]) assert_equal(i.operands[0], a) assert_equal(i.operands[0].dtype, np.dtype('f4')) # Byte-order cast '<f4' -> '>f4' a = np.arange(6, dtype='<f4').reshape(2, 3) i = nditer(a, [], [['readwrite', 'updateifcopy']], casting='equiv', op_dtypes=[np.dtype('>f4')]) assert_equal(i.operands[0], a) assert_equal(i.operands[0].dtype, np.dtype('>f4')) # Safe case 'f4' -> 'f8' a = np.arange(24, dtype='f4').reshape(2, 3, 4).swapaxes(1, 2) i = nditer(a, [], [['readonly', 'copy']], casting='safe', op_dtypes=[np.dtype('f8')]) assert_equal(i.operands[0], a) assert_equal(i.operands[0].dtype, np.dtype('f8')) # The memory layout of the temporary should match a (a is (48,4,16)) # except negative strides get flipped to positive strides. assert_equal(i.operands[0].strides, (96, 8, 32)) a = a[::-1,:, ::-1] i = nditer(a, [], [['readonly', 'copy']], casting='safe', op_dtypes=[np.dtype('f8')]) assert_equal(i.operands[0], a) assert_equal(i.operands[0].dtype, np.dtype('f8')) assert_equal(i.operands[0].strides, (96, 8, 32)) # Same-kind cast 'f8' -> 'f4' -> 'f8' a = np.arange(24, dtype='f8').reshape(2, 3, 4).T i = nditer(a, [], [['readwrite', 'updateifcopy']], casting='same_kind', op_dtypes=[np.dtype('f4')]) assert_equal(i.operands[0], a) assert_equal(i.operands[0].dtype, np.dtype('f4')) assert_equal(i.operands[0].strides, (4, 16, 48)) # Check that UPDATEIFCOPY is activated i.operands[0][2, 1, 1] = -12.5 assert_(a[2, 1, 1] != -12.5) i = None assert_equal(a[2, 1, 1], -12.5) a = np.arange(6, dtype='i4')[::-2] i = nditer(a, [], [['writeonly', 'updateifcopy']], casting='unsafe', op_dtypes=[np.dtype('f4')]) assert_equal(i.operands[0].dtype, np.dtype('f4')) # Even though the stride was negative in 'a', it # becomes positive in the temporary assert_equal(i.operands[0].strides, (4,)) i.operands[0][:] = [1, 2, 3] i = None assert_equal(a, [1, 2, 3]) def test_iter_array_cast_errors(): # Check that invalid casts are caught # Need to enable copying for casts to occur assert_raises(TypeError, nditer, arange(2, dtype='f4'), [], [['readonly']], op_dtypes=[np.dtype('f8')]) # Also need to allow casting for casts to occur assert_raises(TypeError, nditer, arange(2, dtype='f4'), [], [['readonly', 'copy']], casting='no', op_dtypes=[np.dtype('f8')]) assert_raises(TypeError, nditer, arange(2, dtype='f4'), [], [['readonly', 'copy']], casting='equiv', op_dtypes=[np.dtype('f8')]) assert_raises(TypeError, nditer, arange(2, dtype='f8'), [], [['writeonly', 'updateifcopy']], casting='no', op_dtypes=[np.dtype('f4')]) assert_raises(TypeError, nditer, arange(2, dtype='f8'), [], [['writeonly', 'updateifcopy']], casting='equiv', op_dtypes=[np.dtype('f4')]) # '<f4' -> '>f4' should not work with casting='no' assert_raises(TypeError, nditer, arange(2, dtype='<f4'), [], [['readonly', 'copy']], casting='no', op_dtypes=[np.dtype('>f4')]) # 'f4' -> 'f8' is a safe cast, but 'f8' -> 'f4' isn't assert_raises(TypeError, nditer, arange(2, dtype='f4'), [], [['readwrite', 'updateifcopy']], casting='safe', op_dtypes=[np.dtype('f8')]) assert_raises(TypeError, nditer, arange(2, dtype='f8'), [], [['readwrite', 'updateifcopy']], casting='safe', op_dtypes=[np.dtype('f4')]) # 'f4' -> 'i4' is neither a safe nor a same-kind cast assert_raises(TypeError, nditer, arange(2, dtype='f4'), [], [['readonly', 'copy']], casting='same_kind', op_dtypes=[np.dtype('i4')]) assert_raises(TypeError, nditer, arange(2, dtype='i4'), [], [['writeonly', 'updateifcopy']], casting='same_kind', op_dtypes=[np.dtype('f4')]) def test_iter_scalar_cast(): # Check that scalars are cast as requested # No cast 'f4' -> 'f4' i = nditer(np.float32(2.5), [], [['readonly']], op_dtypes=[np.dtype('f4')]) assert_equal(i.dtypes[0], np.dtype('f4')) assert_equal(i.value.dtype, np.dtype('f4')) assert_equal(i.value, 2.5) # Safe cast 'f4' -> 'f8' i = nditer(np.float32(2.5), [], [['readonly', 'copy']], casting='safe', op_dtypes=[np.dtype('f8')]) assert_equal(i.dtypes[0], np.dtype('f8')) assert_equal(i.value.dtype, np.dtype('f8')) assert_equal(i.value, 2.5) # Same-kind cast 'f8' -> 'f4' i = nditer(np.float64(2.5), [], [['readonly', 'copy']], casting='same_kind', op_dtypes=[np.dtype('f4')]) assert_equal(i.dtypes[0], np.dtype('f4')) assert_equal(i.value.dtype, np.dtype('f4')) assert_equal(i.value, 2.5) # Unsafe cast 'f8' -> 'i4' i = nditer(np.float64(3.0), [], [['readonly', 'copy']], casting='unsafe', op_dtypes=[np.dtype('i4')]) assert_equal(i.dtypes[0], np.dtype('i4')) assert_equal(i.value.dtype, np.dtype('i4')) assert_equal(i.value, 3) # Readonly scalars may be cast even without setting COPY or BUFFERED i = nditer(3, [], [['readonly']], op_dtypes=[np.dtype('f8')]) assert_equal(i[0].dtype, np.dtype('f8')) assert_equal(i[0], 3.) def test_iter_scalar_cast_errors(): # Check that invalid casts are caught # Need to allow copying/buffering for write casts of scalars to occur assert_raises(TypeError, nditer, np.float32(2), [], [['readwrite']], op_dtypes=[np.dtype('f8')]) assert_raises(TypeError, nditer, 2.5, [], [['readwrite']], op_dtypes=[np.dtype('f4')]) # 'f8' -> 'f4' isn't a safe cast if the value would overflow assert_raises(TypeError, nditer, np.float64(1e60), [], [['readonly']], casting='safe', op_dtypes=[np.dtype('f4')]) # 'f4' -> 'i4' is neither a safe nor a same-kind cast assert_raises(TypeError, nditer, np.float32(2), [], [['readonly']], casting='same_kind', op_dtypes=[np.dtype('i4')]) def test_iter_object_arrays_basic(): # Check that object arrays work obj = {'a':3,'b':'d'} a = np.array([[1, 2, 3], None, obj, None], dtype='O') if HAS_REFCOUNT: rc = sys.getrefcount(obj) # Need to allow references for object arrays assert_raises(TypeError, nditer, a) if HAS_REFCOUNT: assert_equal(sys.getrefcount(obj), rc) i = nditer(a, ['refs_ok'], ['readonly']) vals = [x_[()] for x_ in i] assert_equal(np.array(vals, dtype='O'), a) vals, i, x = [None]*3 if HAS_REFCOUNT: assert_equal(sys.getrefcount(obj), rc) i = nditer(a.reshape(2, 2).T, ['refs_ok', 'buffered'], ['readonly'], order='C') assert_(i.iterationneedsapi) vals = [x_[()] for x_ in i] assert_equal(np.array(vals, dtype='O'), a.reshape(2, 2).ravel(order='F')) vals, i, x = [None]*3 if HAS_REFCOUNT: assert_equal(sys.getrefcount(obj), rc) i = nditer(a.reshape(2, 2).T, ['refs_ok', 'buffered'], ['readwrite'], order='C') for x in i: x[...] = None vals, i, x = [None]*3 if HAS_REFCOUNT: assert_(sys.getrefcount(obj) == rc-1) assert_equal(a, np.array([None]*4, dtype='O')) def test_iter_object_arrays_conversions(): # Conversions to/from objects a = np.arange(6, dtype='O') i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'], casting='unsafe', op_dtypes='i4') for x in i: x[...] += 1 assert_equal(a, np.arange(6)+1) a = np.arange(6, dtype='i4') i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'], casting='unsafe', op_dtypes='O') for x in i: x[...] += 1 assert_equal(a, np.arange(6)+1) # Non-contiguous object array a = np.zeros((6,), dtype=[('p', 'i1'), ('a', 'O')]) a = a['a'] a[:] = np.arange(6) i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'], casting='unsafe', op_dtypes='i4') for x in i: x[...] += 1 assert_equal(a, np.arange(6)+1) #Non-contiguous value array a = np.zeros((6,), dtype=[('p', 'i1'), ('a', 'i4')]) a = a['a'] a[:] = np.arange(6) + 98172488 i = nditer(a, ['refs_ok', 'buffered'], ['readwrite'], casting='unsafe', op_dtypes='O') ob = i[0][()] if HAS_REFCOUNT: rc = sys.getrefcount(ob) for x in i: x[...] += 1 if HAS_REFCOUNT: assert_(sys.getrefcount(ob) == rc-1) assert_equal(a, np.arange(6)+98172489) def test_iter_common_dtype(): # Check that the iterator finds a common data type correctly i = nditer([array([3], dtype='f4'), array([0], dtype='f8')], ['common_dtype'], [['readonly', 'copy']]*2, casting='safe') assert_equal(i.dtypes[0], np.dtype('f8')) assert_equal(i.dtypes[1], np.dtype('f8')) i = nditer([array([3], dtype='i4'), array([0], dtype='f4')], ['common_dtype'], [['readonly', 'copy']]*2, casting='safe') assert_equal(i.dtypes[0], np.dtype('f8')) assert_equal(i.dtypes[1], np.dtype('f8')) i = nditer([array([3], dtype='f4'), array(0, dtype='f8')], ['common_dtype'], [['readonly', 'copy']]*2, casting='same_kind') assert_equal(i.dtypes[0], np.dtype('f4')) assert_equal(i.dtypes[1], np.dtype('f4')) i = nditer([array([3], dtype='u4'), array(0, dtype='i4')], ['common_dtype'], [['readonly', 'copy']]*2, casting='safe') assert_equal(i.dtypes[0], np.dtype('u4')) assert_equal(i.dtypes[1], np.dtype('u4')) i = nditer([array([3], dtype='u4'), array(-12, dtype='i4')], ['common_dtype'], [['readonly', 'copy']]*2, casting='safe') assert_equal(i.dtypes[0], np.dtype('i8')) assert_equal(i.dtypes[1], np.dtype('i8')) i = nditer([array([3], dtype='u4'), array(-12, dtype='i4'), array([2j], dtype='c8'), array([9], dtype='f8')], ['common_dtype'], [['readonly', 'copy']]*4, casting='safe') assert_equal(i.dtypes[0], np.dtype('c16')) assert_equal(i.dtypes[1], np.dtype('c16')) assert_equal(i.dtypes[2], np.dtype('c16')) assert_equal(i.dtypes[3], np.dtype('c16')) assert_equal(i.value, (3, -12, 2j, 9)) # When allocating outputs, other outputs aren't factored in i = nditer([array([3], dtype='i4'), None, array([2j], dtype='c16')], [], [['readonly', 'copy'], ['writeonly', 'allocate'], ['writeonly']], casting='safe') assert_equal(i.dtypes[0], np.dtype('i4')) assert_equal(i.dtypes[1], np.dtype('i4')) assert_equal(i.dtypes[2], np.dtype('c16')) # But, if common data types are requested, they are i = nditer([array([3], dtype='i4'), None, array([2j], dtype='c16')], ['common_dtype'], [['readonly', 'copy'], ['writeonly', 'allocate'], ['writeonly']], casting='safe') assert_equal(i.dtypes[0], np.dtype('c16')) assert_equal(i.dtypes[1], np.dtype('c16')) assert_equal(i.dtypes[2], np.dtype('c16')) def test_iter_op_axes(): # Check that custom axes work # Reverse the axes a = arange(6).reshape(2, 3) i = nditer([a, a.T], [], [['readonly']]*2, op_axes=[[0, 1], [1, 0]]) assert_(all([x == y for (x, y) in i])) a = arange(24).reshape(2, 3, 4) i = nditer([a.T, a], [], [['readonly']]*2, op_axes=[[2, 1, 0], None]) assert_(all([x == y for (x, y) in i])) # Broadcast 1D to any dimension a = arange(1, 31).reshape(2, 3, 5) b = arange(1, 3) i = nditer([a, b], [], [['readonly']]*2, op_axes=[None, [0, -1, -1]]) assert_equal([x*y for (x, y) in i], (a*b.reshape(2, 1, 1)).ravel()) b = arange(1, 4) i = nditer([a, b], [], [['readonly']]*2, op_axes=[None, [-1, 0, -1]]) assert_equal([x*y for (x, y) in i], (a*b.reshape(1, 3, 1)).ravel()) b = arange(1, 6) i = nditer([a, b], [], [['readonly']]*2, op_axes=[None, [np.newaxis, np.newaxis, 0]]) assert_equal([x*y for (x, y) in i], (a*b.reshape(1, 1, 5)).ravel()) # Inner product-style broadcasting a = arange(24).reshape(2, 3, 4) b = arange(40).reshape(5, 2, 4) i = nditer([a, b], ['multi_index'], [['readonly']]*2, op_axes=[[0, 1, -1, -1], [-1, -1, 0, 1]]) assert_equal(i.shape, (2, 3, 5, 2)) # Matrix product-style broadcasting a = arange(12).reshape(3, 4) b = arange(20).reshape(4, 5) i = nditer([a, b], ['multi_index'], [['readonly']]*2, op_axes=[[0, -1], [-1, 1]]) assert_equal(i.shape, (3, 5)) def test_iter_op_axes_errors(): # Check that custom axes throws errors for bad inputs # Wrong number of items in op_axes a = arange(6).reshape(2, 3) assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, op_axes=[[0], [1], [0]]) # Out of bounds items in op_axes assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, op_axes=[[2, 1], [0, 1]]) assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, op_axes=[[0, 1], [2, -1]]) # Duplicate items in op_axes assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, op_axes=[[0, 0], [0, 1]]) assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, op_axes=[[0, 1], [1, 1]]) # Different sized arrays in op_axes assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, op_axes=[[0, 1], [0, 1, 0]]) # Non-broadcastable dimensions in the result assert_raises(ValueError, nditer, [a, a], [], [['readonly']]*2, op_axes=[[0, 1], [1, 0]]) def test_iter_copy(): # Check that copying the iterator works correctly a = arange(24).reshape(2, 3, 4) # Simple iterator i = nditer(a) j = i.copy() assert_equal([x[()] for x in i], [x[()] for x in j]) i.iterindex = 3 j = i.copy() assert_equal([x[()] for x in i], [x[()] for x in j]) # Buffered iterator i = nditer(a, ['buffered', 'ranged'], order='F', buffersize=3) j = i.copy() assert_equal([x[()] for x in i], [x[()] for x in j]) i.iterindex = 3 j = i.copy() assert_equal([x[()] for x in i], [x[()] for x in j]) i.iterrange = (3, 9) j = i.copy() assert_equal([x[()] for x in i], [x[()] for x in j]) i.iterrange = (2, 18) next(i) next(i) j = i.copy() assert_equal([x[()] for x in i], [x[()] for x in j]) # Casting iterator i = nditer(a, ['buffered'], order='F', casting='unsafe', op_dtypes='f8', buffersize=5) j = i.copy() i = None assert_equal([x[()] for x in j], a.ravel(order='F')) a = arange(24, dtype='<i4').reshape(2, 3, 4) i = nditer(a, ['buffered'], order='F', casting='unsafe', op_dtypes='>f8', buffersize=5) j = i.copy() i = None assert_equal([x[()] for x in j], a.ravel(order='F')) def test_iter_allocate_output_simple(): # Check that the iterator will properly allocate outputs # Simple case a = arange(6) i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']], op_dtypes=[None, np.dtype('f4')]) assert_equal(i.operands[1].shape, a.shape) assert_equal(i.operands[1].dtype, np.dtype('f4')) def test_iter_allocate_output_buffered_readwrite(): # Allocated output with buffering + delay_bufalloc a = arange(6) i = nditer([a, None], ['buffered', 'delay_bufalloc'], [['readonly'], ['allocate', 'readwrite']]) i.operands[1][:] = 1 i.reset() for x in i: x[1][...] += x[0][...] assert_equal(i.operands[1], a+1) def test_iter_allocate_output_itorder(): # The allocated output should match the iteration order # C-order input, best iteration order a = arange(6, dtype='i4').reshape(2, 3) i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']], op_dtypes=[None, np.dtype('f4')]) assert_equal(i.operands[1].shape, a.shape) assert_equal(i.operands[1].strides, a.strides) assert_equal(i.operands[1].dtype, np.dtype('f4')) # F-order input, best iteration order a = arange(24, dtype='i4').reshape(2, 3, 4).T i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']], op_dtypes=[None, np.dtype('f4')]) assert_equal(i.operands[1].shape, a.shape) assert_equal(i.operands[1].strides, a.strides) assert_equal(i.operands[1].dtype, np.dtype('f4')) # Non-contiguous input, C iteration order a = arange(24, dtype='i4').reshape(2, 3, 4).swapaxes(0, 1) i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']], order='C', op_dtypes=[None, np.dtype('f4')]) assert_equal(i.operands[1].shape, a.shape) assert_equal(i.operands[1].strides, (32, 16, 4)) assert_equal(i.operands[1].dtype, np.dtype('f4')) def test_iter_allocate_output_opaxes(): # Specifing op_axes should work a = arange(24, dtype='i4').reshape(2, 3, 4) i = nditer([None, a], [], [['writeonly', 'allocate'], ['readonly']], op_dtypes=[np.dtype('u4'), None], op_axes=[[1, 2, 0], None]) assert_equal(i.operands[0].shape, (4, 2, 3)) assert_equal(i.operands[0].strides, (4, 48, 16)) assert_equal(i.operands[0].dtype, np.dtype('u4')) def test_iter_allocate_output_types_promotion(): # Check type promotion of automatic outputs i = nditer([array([3], dtype='f4'), array([0], dtype='f8'), None], [], [['readonly']]*2+[['writeonly', 'allocate']]) assert_equal(i.dtypes[2], np.dtype('f8')) i = nditer([array([3], dtype='i4'), array([0], dtype='f4'), None], [], [['readonly']]*2+[['writeonly', 'allocate']]) assert_equal(i.dtypes[2], np.dtype('f8')) i = nditer([array([3], dtype='f4'), array(0, dtype='f8'), None], [], [['readonly']]*2+[['writeonly', 'allocate']]) assert_equal(i.dtypes[2], np.dtype('f4')) i = nditer([array([3], dtype='u4'), array(0, dtype='i4'), None], [], [['readonly']]*2+[['writeonly', 'allocate']]) assert_equal(i.dtypes[2], np.dtype('u4')) i = nditer([array([3], dtype='u4'), array(-12, dtype='i4'), None], [], [['readonly']]*2+[['writeonly', 'allocate']]) assert_equal(i.dtypes[2], np.dtype('i8')) def test_iter_allocate_output_types_byte_order(): # Verify the rules for byte order changes # When there's just one input, the output type exactly matches a = array([3], dtype='u4').newbyteorder() i = nditer([a, None], [], [['readonly'], ['writeonly', 'allocate']]) assert_equal(i.dtypes[0], i.dtypes[1]) # With two or more inputs, the output type is in native byte order i = nditer([a, a, None], [], [['readonly'], ['readonly'], ['writeonly', 'allocate']]) assert_(i.dtypes[0] != i.dtypes[2]) assert_equal(i.dtypes[0].newbyteorder('='), i.dtypes[2]) def test_iter_allocate_output_types_scalar(): # If the inputs are all scalars, the output should be a scalar i = nditer([None, 1, 2.3, np.float32(12), np.complex128(3)], [], [['writeonly', 'allocate']] + [['readonly']]*4) assert_equal(i.operands[0].dtype, np.dtype('complex128')) assert_equal(i.operands[0].ndim, 0) def test_iter_allocate_output_subtype(): # Make sure that the subtype with priority wins # matrix vs ndarray a = np.matrix([[1, 2], [3, 4]]) b = np.arange(4).reshape(2, 2).T i = nditer([a, b, None], [], [['readonly'], ['readonly'], ['writeonly', 'allocate']]) assert_equal(type(a), type(i.operands[2])) assert_(type(b) != type(i.operands[2])) assert_equal(i.operands[2].shape, (2, 2)) # matrix always wants things to be 2D b = np.arange(4).reshape(1, 2, 2) assert_raises(RuntimeError, nditer, [a, b, None], [], [['readonly'], ['readonly'], ['writeonly', 'allocate']]) # but if subtypes are disabled, the result can still work i = nditer([a, b, None], [], [['readonly'], ['readonly'], ['writeonly', 'allocate', 'no_subtype']]) assert_equal(type(b), type(i.operands[2])) assert_(type(a) != type(i.operands[2])) assert_equal(i.operands[2].shape, (1, 2, 2)) def test_iter_allocate_output_errors(): # Check that the iterator will throw errors for bad output allocations # Need an input if no output data type is specified a = arange(6) assert_raises(TypeError, nditer, [a, None], [], [['writeonly'], ['writeonly', 'allocate']]) # Allocated output should be flagged for writing assert_raises(ValueError, nditer, [a, None], [], [['readonly'], ['allocate', 'readonly']]) # Allocated output can't have buffering without delayed bufalloc assert_raises(ValueError, nditer, [a, None], ['buffered'], ['allocate', 'readwrite']) # Must specify at least one input assert_raises(ValueError, nditer, [None, None], [], [['writeonly', 'allocate'], ['writeonly', 'allocate']], op_dtypes=[np.dtype('f4'), np.dtype('f4')]) # If using op_axes, must specify all the axes a = arange(24, dtype='i4').reshape(2, 3, 4) assert_raises(ValueError, nditer, [a, None], [], [['readonly'], ['writeonly', 'allocate']], op_dtypes=[None, np.dtype('f4')], op_axes=[None, [0, np.newaxis, 1]]) # If using op_axes, the axes must be within bounds assert_raises(ValueError, nditer, [a, None], [], [['readonly'], ['writeonly', 'allocate']], op_dtypes=[None, np.dtype('f4')], op_axes=[None, [0, 3, 1]]) # If using op_axes, there can't be duplicates assert_raises(ValueError, nditer, [a, None], [], [['readonly'], ['writeonly', 'allocate']], op_dtypes=[None, np.dtype('f4')], op_axes=[None, [0, 2, 1, 0]]) def test_iter_remove_axis(): a = arange(24).reshape(2, 3, 4) i = nditer(a, ['multi_index']) i.remove_axis(1) assert_equal([x for x in i], a[:, 0,:].ravel()) a = a[::-1,:,:] i = nditer(a, ['multi_index']) i.remove_axis(0) assert_equal([x for x in i], a[0,:,:].ravel()) def test_iter_remove_multi_index_inner_loop(): # Check that removing multi-index support works a = arange(24).reshape(2, 3, 4) i = nditer(a, ['multi_index']) assert_equal(i.ndim, 3) assert_equal(i.shape, (2, 3, 4)) assert_equal(i.itviews[0].shape, (2, 3, 4)) # Removing the multi-index tracking causes all dimensions to coalesce before = [x for x in i] i.remove_multi_index() after = [x for x in i] assert_equal(before, after) assert_equal(i.ndim, 1) assert_raises(ValueError, lambda i:i.shape, i) assert_equal(i.itviews[0].shape, (24,)) # Removing the inner loop means there's just one iteration i.reset() assert_equal(i.itersize, 24) assert_equal(i[0].shape, tuple()) i.enable_external_loop() assert_equal(i.itersize, 24) assert_equal(i[0].shape, (24,)) assert_equal(i.value, arange(24)) def test_iter_iterindex(): # Make sure iterindex works buffersize = 5 a = arange(24).reshape(4, 3, 2) for flags in ([], ['buffered']): i = nditer(a, flags, buffersize=buffersize) assert_equal(iter_iterindices(i), list(range(24))) i.iterindex = 2 assert_equal(iter_iterindices(i), list(range(2, 24))) i = nditer(a, flags, order='F', buffersize=buffersize) assert_equal(iter_iterindices(i), list(range(24))) i.iterindex = 5 assert_equal(iter_iterindices(i), list(range(5, 24))) i = nditer(a[::-1], flags, order='F', buffersize=buffersize) assert_equal(iter_iterindices(i), list(range(24))) i.iterindex = 9 assert_equal(iter_iterindices(i), list(range(9, 24))) i = nditer(a[::-1, ::-1], flags, order='C', buffersize=buffersize) assert_equal(iter_iterindices(i), list(range(24))) i.iterindex = 13 assert_equal(iter_iterindices(i), list(range(13, 24))) i = nditer(a[::1, ::-1], flags, buffersize=buffersize) assert_equal(iter_iterindices(i), list(range(24))) i.iterindex = 23 assert_equal(iter_iterindices(i), list(range(23, 24))) i.reset() i.iterindex = 2 assert_equal(iter_iterindices(i), list(range(2, 24))) def test_iter_iterrange(): # Make sure getting and resetting the iterrange works buffersize = 5 a = arange(24, dtype='i4').reshape(4, 3, 2) a_fort = a.ravel(order='F') i = nditer(a, ['ranged'], ['readonly'], order='F', buffersize=buffersize) assert_equal(i.iterrange, (0, 24)) assert_equal([x[()] for x in i], a_fort) for r in [(0, 24), (1, 2), (3, 24), (5, 5), (0, 20), (23, 24)]: i.iterrange = r assert_equal(i.iterrange, r) assert_equal([x[()] for x in i], a_fort[r[0]:r[1]]) i = nditer(a, ['ranged', 'buffered'], ['readonly'], order='F', op_dtypes='f8', buffersize=buffersize) assert_equal(i.iterrange, (0, 24)) assert_equal([x[()] for x in i], a_fort) for r in [(0, 24), (1, 2), (3, 24), (5, 5), (0, 20), (23, 24)]: i.iterrange = r assert_equal(i.iterrange, r) assert_equal([x[()] for x in i], a_fort[r[0]:r[1]]) def get_array(i): val = np.array([], dtype='f8') for x in i: val = np.concatenate((val, x)) return val i = nditer(a, ['ranged', 'buffered', 'external_loop'], ['readonly'], order='F', op_dtypes='f8', buffersize=buffersize) assert_equal(i.iterrange, (0, 24)) assert_equal(get_array(i), a_fort) for r in [(0, 24), (1, 2), (3, 24), (5, 5), (0, 20), (23, 24)]: i.iterrange = r assert_equal(i.iterrange, r) assert_equal(get_array(i), a_fort[r[0]:r[1]]) def test_iter_buffering(): # Test buffering with several buffer sizes and types arrays = [] # F-order swapped array arrays.append(np.arange(24, dtype='c16').reshape(2, 3, 4).T.newbyteorder().byteswap()) # Contiguous 1-dimensional array arrays.append(np.arange(10, dtype='f4')) # Unaligned array a = np.zeros((4*16+1,), dtype='i1')[1:] a.dtype = 'i4' a[:] = np.arange(16, dtype='i4') arrays.append(a) # 4-D F-order array arrays.append(np.arange(120, dtype='i4').reshape(5, 3, 2, 4).T) for a in arrays: for buffersize in (1, 2, 3, 5, 8, 11, 16, 1024): vals = [] i = nditer(a, ['buffered', 'external_loop'], [['readonly', 'nbo', 'aligned']], order='C', casting='equiv', buffersize=buffersize) while not i.finished: assert_(i[0].size <= buffersize) vals.append(i[0].copy()) i.iternext() assert_equal(np.concatenate(vals), a.ravel(order='C')) def test_iter_write_buffering(): # Test that buffering of writes is working # F-order swapped array a = np.arange(24).reshape(2, 3, 4).T.newbyteorder().byteswap() i = nditer(a, ['buffered'], [['readwrite', 'nbo', 'aligned']], casting='equiv', order='C', buffersize=16) x = 0 while not i.finished: i[0] = x x += 1 i.iternext() assert_equal(a.ravel(order='C'), np.arange(24)) def test_iter_buffering_delayed_alloc(): # Test that delaying buffer allocation works a = np.arange(6) b = np.arange(1, dtype='f4') i = nditer([a, b], ['buffered', 'delay_bufalloc', 'multi_index', 'reduce_ok'], ['readwrite'], casting='unsafe', op_dtypes='f4') assert_(i.has_delayed_bufalloc) assert_raises(ValueError, lambda i:i.multi_index, i) assert_raises(ValueError, lambda i:i[0], i) assert_raises(ValueError, lambda i:i[0:2], i) def assign_iter(i): i[0] = 0 assert_raises(ValueError, assign_iter, i) i.reset() assert_(not i.has_delayed_bufalloc) assert_equal(i.multi_index, (0,)) assert_equal(i[0], 0) i[1] = 1 assert_equal(i[0:2], [0, 1]) assert_equal([[x[0][()], x[1][()]] for x in i], list(zip(range(6), [1]*6))) def test_iter_buffered_cast_simple(): # Test that buffering can handle a simple cast a = np.arange(10, dtype='f4') i = nditer(a, ['buffered', 'external_loop'], [['readwrite', 'nbo', 'aligned']], casting='same_kind', op_dtypes=[np.dtype('f8')], buffersize=3) for v in i: v[...] *= 2 assert_equal(a, 2*np.arange(10, dtype='f4')) def test_iter_buffered_cast_byteswapped(): # Test that buffering can handle a cast which requires swap->cast->swap a = np.arange(10, dtype='f4').newbyteorder().byteswap() i = nditer(a, ['buffered', 'external_loop'], [['readwrite', 'nbo', 'aligned']], casting='same_kind', op_dtypes=[np.dtype('f8').newbyteorder()], buffersize=3) for v in i: v[...] *= 2 assert_equal(a, 2*np.arange(10, dtype='f4')) with suppress_warnings() as sup: sup.filter(np.ComplexWarning) a = np.arange(10, dtype='f8').newbyteorder().byteswap() i = nditer(a, ['buffered', 'external_loop'], [['readwrite', 'nbo', 'aligned']], casting='unsafe', op_dtypes=[np.dtype('c8').newbyteorder()], buffersize=3) for v in i: v[...] *= 2 assert_equal(a, 2*np.arange(10, dtype='f8')) def test_iter_buffered_cast_byteswapped_complex(): # Test that buffering can handle a cast which requires swap->cast->copy a = np.arange(10, dtype='c8').newbyteorder().byteswap() a += 2j i = nditer(a, ['buffered', 'external_loop'], [['readwrite', 'nbo', 'aligned']], casting='same_kind', op_dtypes=[np.dtype('c16')], buffersize=3) for v in i: v[...] *= 2 assert_equal(a, 2*np.arange(10, dtype='c8') + 4j) a = np.arange(10, dtype='c8') a += 2j i = nditer(a, ['buffered', 'external_loop'], [['readwrite', 'nbo', 'aligned']], casting='same_kind', op_dtypes=[np.dtype('c16').newbyteorder()], buffersize=3) for v in i: v[...] *= 2 assert_equal(a, 2*np.arange(10, dtype='c8') + 4j) a = np.arange(10, dtype=np.clongdouble).newbyteorder().byteswap() a += 2j i = nditer(a, ['buffered', 'external_loop'], [['readwrite', 'nbo', 'aligned']], casting='same_kind', op_dtypes=[np.dtype('c16')], buffersize=3) for v in i: v[...] *= 2 assert_equal(a, 2*np.arange(10, dtype=np.clongdouble) + 4j) a = np.arange(10, dtype=np.longdouble).newbyteorder().byteswap() i = nditer(a, ['buffered', 'external_loop'], [['readwrite', 'nbo', 'aligned']], casting='same_kind', op_dtypes=[np.dtype('f4')], buffersize=7) for v in i: v[...] *= 2 assert_equal(a, 2*np.arange(10, dtype=np.longdouble)) def test_iter_buffered_cast_structured_type(): # Tests buffering of structured types # simple -> struct type (duplicates the value) sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2, 3)), ('d', 'O')] a = np.arange(3, dtype='f4') + 0.5 i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt) vals = [np.array(x) for x in i] assert_equal(vals[0]['a'], 0.5) assert_equal(vals[0]['b'], 0) assert_equal(vals[0]['c'], [[(0.5)]*3]*2) assert_equal(vals[0]['d'], 0.5) assert_equal(vals[1]['a'], 1.5) assert_equal(vals[1]['b'], 1) assert_equal(vals[1]['c'], [[(1.5)]*3]*2) assert_equal(vals[1]['d'], 1.5) assert_equal(vals[0].dtype, np.dtype(sdt)) # object -> struct type sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2, 3)), ('d', 'O')] a = np.zeros((3,), dtype='O') a[0] = (0.5, 0.5, [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5]], 0.5) a[1] = (1.5, 1.5, [[1.5, 1.5, 1.5], [1.5, 1.5, 1.5]], 1.5) a[2] = (2.5, 2.5, [[2.5, 2.5, 2.5], [2.5, 2.5, 2.5]], 2.5) if HAS_REFCOUNT: rc = sys.getrefcount(a[0]) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt) vals = [x.copy() for x in i] assert_equal(vals[0]['a'], 0.5) assert_equal(vals[0]['b'], 0) assert_equal(vals[0]['c'], [[(0.5)]*3]*2) assert_equal(vals[0]['d'], 0.5) assert_equal(vals[1]['a'], 1.5) assert_equal(vals[1]['b'], 1) assert_equal(vals[1]['c'], [[(1.5)]*3]*2) assert_equal(vals[1]['d'], 1.5) assert_equal(vals[0].dtype, np.dtype(sdt)) vals, i, x = [None]*3 if HAS_REFCOUNT: assert_equal(sys.getrefcount(a[0]), rc) # struct type -> simple (takes the first value) sdt = [('a', 'f4'), ('b', 'i8'), ('d', 'O')] a = np.array([(5.5, 7, 'test'), (8, 10, 11)], dtype=sdt) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes='i4') assert_equal([x_[()] for x_ in i], [5, 8]) # struct type -> struct type (field-wise copy) sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', 'O')] sdt2 = [('d', 'u2'), ('a', 'O'), ('b', 'f8')] a = np.array([(1, 2, 3), (4, 5, 6)], dtype=sdt1) # New in 1.12: This behavior changes in 1.13, test for dep warning with assert_warns(FutureWarning): i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) assert_equal([np.array(x_) for x_ in i], [np.array((3, 1, 2), dtype=sdt2), np.array((6, 4, 5), dtype=sdt2)]) # struct type -> struct type (field gets discarded) sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', 'O')] sdt2 = [('b', 'O'), ('a', 'f8')] a = np.array([(1, 2, 3), (4, 5, 6)], dtype=sdt1) # New in 1.12: This behavior changes in 1.13, test for dep warning with assert_warns(FutureWarning): i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) vals = [] for x in i: vals.append(np.array(x)) x['a'] = x['b']+3 assert_equal(vals, [np.array((2, 1), dtype=sdt2), np.array((5, 4), dtype=sdt2)]) assert_equal(a, np.array([(5, 2, None), (8, 5, None)], dtype=sdt1)) # struct type -> struct type (structured field gets discarded) sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', [('a', 'i2'), ('b', 'i4')])] sdt2 = [('b', 'O'), ('a', 'f8')] a = np.array([(1, 2, (0, 9)), (4, 5, (20, 21))], dtype=sdt1) # New in 1.12: This behavior changes in 1.13, test for dep warning with assert_warns(FutureWarning): i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) vals = [] for x in i: vals.append(np.array(x)) x['a'] = x['b']+3 assert_equal(vals, [np.array((2, 1), dtype=sdt2), np.array((5, 4), dtype=sdt2)]) assert_equal(a, np.array([(5, 2, (0, 0)), (8, 5, (0, 0))], dtype=sdt1)) # struct type -> struct type (structured field w/ ref gets discarded) sdt1 = [('a', 'f4'), ('b', 'i8'), ('d', [('a', 'i2'), ('b', 'O')])] sdt2 = [('b', 'O'), ('a', 'f8')] a = np.array([(1, 2, (0, 9)), (4, 5, (20, 21))], dtype=sdt1) # New in 1.12: This behavior changes in 1.13, test for dep warning with assert_warns(FutureWarning): i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) vals = [] for x in i: vals.append(np.array(x)) x['a'] = x['b']+3 assert_equal(vals, [np.array((2, 1), dtype=sdt2), np.array((5, 4), dtype=sdt2)]) assert_equal(a, np.array([(5, 2, (0, None)), (8, 5, (0, None))], dtype=sdt1)) # struct type -> struct type back (structured field w/ ref gets discarded) sdt1 = [('b', 'O'), ('a', 'f8')] sdt2 = [('a', 'f4'), ('b', 'i8'), ('d', [('a', 'i2'), ('b', 'O')])] a = np.array([(1, 2), (4, 5)], dtype=sdt1) # New in 1.12: This behavior changes in 1.13, test for dep warning with assert_warns(FutureWarning): i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) vals = [] for x in i: vals.append(np.array(x)) assert_equal(x['d'], np.array((0, None), dtype=[('a', 'i2'), ('b', 'O')])) x['a'] = x['b']+3 assert_equal(vals, [np.array((2, 1, (0, None)), dtype=sdt2), np.array((5, 4, (0, None)), dtype=sdt2)]) assert_equal(a, np.array([(1, 4), (4, 7)], dtype=sdt1)) def test_iter_buffered_cast_subarray(): # Tests buffering of subarrays # one element -> many (copies it to all) sdt1 = [('a', 'f4')] sdt2 = [('a', 'f8', (3, 2, 2))] a = np.zeros((6,), dtype=sdt1) a['a'] = np.arange(6) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) for x, count in zip(i, list(range(6))): assert_(np.all(x['a'] == count)) # one element -> many -> back (copies it to all) sdt1 = [('a', 'O', (1, 1))] sdt2 = [('a', 'O', (3, 2, 2))] a = np.zeros((6,), dtype=sdt1) a['a'][:, 0, 0] = np.arange(6) i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_(np.all(x['a'] == count)) x['a'][0] += 2 count += 1 assert_equal(a['a'], np.arange(6).reshape(6, 1, 1)+2) # many -> one element -> back (copies just element 0) sdt1 = [('a', 'O', (3, 2, 2))] sdt2 = [('a', 'O', (1,))] a = np.zeros((6,), dtype=sdt1) a['a'][:, 0, 0, 0] = np.arange(6) i = nditer(a, ['buffered', 'refs_ok'], ['readwrite'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'], count) x['a'] += 2 count += 1 assert_equal(a['a'], np.arange(6).reshape(6, 1, 1, 1)*np.ones((1, 3, 2, 2))+2) # many -> one element -> back (copies just element 0) sdt1 = [('a', 'f8', (3, 2, 2))] sdt2 = [('a', 'O', (1,))] a = np.zeros((6,), dtype=sdt1) a['a'][:, 0, 0, 0] = np.arange(6) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'], count) count += 1 # many -> one element (copies just element 0) sdt1 = [('a', 'O', (3, 2, 2))] sdt2 = [('a', 'f4', (1,))] a = np.zeros((6,), dtype=sdt1) a['a'][:, 0, 0, 0] = np.arange(6) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'], count) count += 1 # many -> matching shape (straightforward copy) sdt1 = [('a', 'O', (3, 2, 2))] sdt2 = [('a', 'f4', (3, 2, 2))] a = np.zeros((6,), dtype=sdt1) a['a'] = np.arange(6*3*2*2).reshape(6, 3, 2, 2) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'], a[count]['a']) count += 1 # vector -> smaller vector (truncates) sdt1 = [('a', 'f8', (6,))] sdt2 = [('a', 'f4', (2,))] a = np.zeros((6,), dtype=sdt1) a['a'] = np.arange(6*6).reshape(6, 6) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'], a[count]['a'][:2]) count += 1 # vector -> bigger vector (pads with zeros) sdt1 = [('a', 'f8', (2,))] sdt2 = [('a', 'f4', (6,))] a = np.zeros((6,), dtype=sdt1) a['a'] = np.arange(6*2).reshape(6, 2) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'][:2], a[count]['a']) assert_equal(x['a'][2:], [0, 0, 0, 0]) count += 1 # vector -> matrix (broadcasts) sdt1 = [('a', 'f8', (2,))] sdt2 = [('a', 'f4', (2, 2))] a = np.zeros((6,), dtype=sdt1) a['a'] = np.arange(6*2).reshape(6, 2) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'][0], a[count]['a']) assert_equal(x['a'][1], a[count]['a']) count += 1 # vector -> matrix (broadcasts and zero-pads) sdt1 = [('a', 'f8', (2, 1))] sdt2 = [('a', 'f4', (3, 2))] a = np.zeros((6,), dtype=sdt1) a['a'] = np.arange(6*2).reshape(6, 2, 1) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'][:2, 0], a[count]['a'][:, 0]) assert_equal(x['a'][:2, 1], a[count]['a'][:, 0]) assert_equal(x['a'][2,:], [0, 0]) count += 1 # matrix -> matrix (truncates and zero-pads) sdt1 = [('a', 'f8', (2, 3))] sdt2 = [('a', 'f4', (3, 2))] a = np.zeros((6,), dtype=sdt1) a['a'] = np.arange(6*2*3).reshape(6, 2, 3) i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt2) assert_equal(i[0].dtype, np.dtype(sdt2)) count = 0 for x in i: assert_equal(x['a'][:2, 0], a[count]['a'][:, 0]) assert_equal(x['a'][:2, 1], a[count]['a'][:, 1]) assert_equal(x['a'][2,:], [0, 0]) count += 1 def test_iter_buffering_badwriteback(): # Writing back from a buffer cannot combine elements # a needs write buffering, but had a broadcast dimension a = np.arange(6).reshape(2, 3, 1) b = np.arange(12).reshape(2, 3, 2) assert_raises(ValueError, nditer, [a, b], ['buffered', 'external_loop'], [['readwrite'], ['writeonly']], order='C') # But if a is readonly, it's fine nditer([a, b], ['buffered', 'external_loop'], [['readonly'], ['writeonly']], order='C') # If a has just one element, it's fine too (constant 0 stride, a reduction) a = np.arange(1).reshape(1, 1, 1) nditer([a, b], ['buffered', 'external_loop', 'reduce_ok'], [['readwrite'], ['writeonly']], order='C') # check that it fails on other dimensions too a = np.arange(6).reshape(1, 3, 2) assert_raises(ValueError, nditer, [a, b], ['buffered', 'external_loop'], [['readwrite'], ['writeonly']], order='C') a = np.arange(4).reshape(2, 1, 2) assert_raises(ValueError, nditer, [a, b], ['buffered', 'external_loop'], [['readwrite'], ['writeonly']], order='C') def test_iter_buffering_string(): # Safe casting disallows shrinking strings a = np.array(['abc', 'a', 'abcd'], dtype=np.bytes_) assert_equal(a.dtype, np.dtype('S4')) assert_raises(TypeError, nditer, a, ['buffered'], ['readonly'], op_dtypes='S2') i = nditer(a, ['buffered'], ['readonly'], op_dtypes='S6') assert_equal(i[0], asbytes('abc')) assert_equal(i[0].dtype, np.dtype('S6')) a = np.array(['abc', 'a', 'abcd'], dtype=np.unicode) assert_equal(a.dtype, np.dtype('U4')) assert_raises(TypeError, nditer, a, ['buffered'], ['readonly'], op_dtypes='U2') i = nditer(a, ['buffered'], ['readonly'], op_dtypes='U6') assert_equal(i[0], sixu('abc')) assert_equal(i[0].dtype, np.dtype('U6')) def test_iter_buffering_growinner(): # Test that the inner loop grows when no buffering is needed a = np.arange(30) i = nditer(a, ['buffered', 'growinner', 'external_loop'], buffersize=5) # Should end up with just one inner loop here assert_equal(i[0].size, a.size) @dec.slow def test_iter_buffered_reduce_reuse(): # large enough array for all views, including negative strides. a = np.arange(2*3**5)[3**5:3**5+1] flags = ['buffered', 'delay_bufalloc', 'multi_index', 'reduce_ok', 'refs_ok'] op_flags = [('readonly',), ('readwrite', 'allocate')] op_axes_list = [[(0, 1, 2), (0, 1, -1)], [(0, 1, 2), (0, -1, -1)]] # wrong dtype to force buffering op_dtypes = [np.float, a.dtype] def get_params(): for xs in range(-3**2, 3**2 + 1): for ys in range(xs, 3**2 + 1): for op_axes in op_axes_list: # last stride is reduced and because of that not # important for this test, as it is the inner stride. strides = (xs * a.itemsize, ys * a.itemsize, a.itemsize) arr = np.lib.stride_tricks.as_strided(a, (3, 3, 3), strides) for skip in [0, 1]: yield arr, op_axes, skip for arr, op_axes, skip in get_params(): nditer2 = np.nditer([arr.copy(), None], op_axes=op_axes, flags=flags, op_flags=op_flags, op_dtypes=op_dtypes) nditer2.operands[-1][...] = 0 nditer2.reset() nditer2.iterindex = skip for (a2_in, b2_in) in nditer2: b2_in += a2_in.astype(np.int_) comp_res = nditer2.operands[-1] for bufsize in range(0, 3**3): nditer1 = np.nditer([arr, None], op_axes=op_axes, flags=flags, op_flags=op_flags, buffersize=bufsize, op_dtypes=op_dtypes) nditer1.operands[-1][...] = 0 nditer1.reset() nditer1.iterindex = skip for (a1_in, b1_in) in nditer1: b1_in += a1_in.astype(np.int_) res = nditer1.operands[-1] assert_array_equal(res, comp_res) def test_iter_no_broadcast(): # Test that the no_broadcast flag works a = np.arange(24).reshape(2, 3, 4) b = np.arange(6).reshape(2, 3, 1) c = np.arange(12).reshape(3, 4) nditer([a, b, c], [], [['readonly', 'no_broadcast'], ['readonly'], ['readonly']]) assert_raises(ValueError, nditer, [a, b, c], [], [['readonly'], ['readonly', 'no_broadcast'], ['readonly']]) assert_raises(ValueError, nditer, [a, b, c], [], [['readonly'], ['readonly'], ['readonly', 'no_broadcast']]) def test_iter_nested_iters_basic(): # Test nested iteration basic usage a = arange(12).reshape(2, 3, 2) i, j = np.nested_iters(a, [[0], [1, 2]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]) i, j = np.nested_iters(a, [[0, 1], [2]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]) i, j = np.nested_iters(a, [[0, 2], [1]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]]) def test_iter_nested_iters_reorder(): # Test nested iteration basic usage a = arange(12).reshape(2, 3, 2) # In 'K' order (default), it gets reordered i, j = np.nested_iters(a, [[0], [2, 1]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]) i, j = np.nested_iters(a, [[1, 0], [2]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]) i, j = np.nested_iters(a, [[2, 0], [1]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]]) # In 'C' order, it doesn't i, j = np.nested_iters(a, [[0], [2, 1]], order='C') vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 2, 4, 1, 3, 5], [6, 8, 10, 7, 9, 11]]) i, j = np.nested_iters(a, [[1, 0], [2]], order='C') vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1], [6, 7], [2, 3], [8, 9], [4, 5], [10, 11]]) i, j = np.nested_iters(a, [[2, 0], [1]], order='C') vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 2, 4], [6, 8, 10], [1, 3, 5], [7, 9, 11]]) def test_iter_nested_iters_flip_axes(): # Test nested iteration with negative axes a = arange(12).reshape(2, 3, 2)[::-1, ::-1, ::-1] # In 'K' order (default), the axes all get flipped i, j = np.nested_iters(a, [[0], [1, 2]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]) i, j = np.nested_iters(a, [[0, 1], [2]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11]]) i, j = np.nested_iters(a, [[0, 2], [1]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]]) # In 'C' order, flipping axes is disabled i, j = np.nested_iters(a, [[0], [1, 2]], order='C') vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[11, 10, 9, 8, 7, 6], [5, 4, 3, 2, 1, 0]]) i, j = np.nested_iters(a, [[0, 1], [2]], order='C') vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[11, 10], [9, 8], [7, 6], [5, 4], [3, 2], [1, 0]]) i, j = np.nested_iters(a, [[0, 2], [1]], order='C') vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[11, 9, 7], [10, 8, 6], [5, 3, 1], [4, 2, 0]]) def test_iter_nested_iters_broadcast(): # Test nested iteration with broadcasting a = arange(2).reshape(2, 1) b = arange(3).reshape(1, 3) i, j = np.nested_iters([a, b], [[0], [1]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]]]) i, j = np.nested_iters([a, b], [[1], [0]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[[0, 0], [1, 0]], [[0, 1], [1, 1]], [[0, 2], [1, 2]]]) def test_iter_nested_iters_dtype_copy(): # Test nested iteration with a copy to change dtype # copy a = arange(6, dtype='i4').reshape(2, 3) i, j = np.nested_iters(a, [[0], [1]], op_flags=['readonly', 'copy'], op_dtypes='f8') assert_equal(j[0].dtype, np.dtype('f8')) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1, 2], [3, 4, 5]]) vals = None # updateifcopy a = arange(6, dtype='f4').reshape(2, 3) i, j = np.nested_iters(a, [[0], [1]], op_flags=['readwrite', 'updateifcopy'], casting='same_kind', op_dtypes='f8') assert_equal(j[0].dtype, np.dtype('f8')) for x in i: for y in j: y[...] += 1 assert_equal(a, [[0, 1, 2], [3, 4, 5]]) i, j, x, y = (None,)*4 # force the updateifcopy assert_equal(a, [[1, 2, 3], [4, 5, 6]]) def test_iter_nested_iters_dtype_buffered(): # Test nested iteration with buffering to change dtype a = arange(6, dtype='f4').reshape(2, 3) i, j = np.nested_iters(a, [[0], [1]], flags=['buffered'], op_flags=['readwrite'], casting='same_kind', op_dtypes='f8') assert_equal(j[0].dtype, np.dtype('f8')) for x in i: for y in j: y[...] += 1 assert_equal(a, [[1, 2, 3], [4, 5, 6]]) def test_iter_reduction_error(): a = np.arange(6) assert_raises(ValueError, nditer, [a, None], [], [['readonly'], ['readwrite', 'allocate']], op_axes=[[0], [-1]]) a = np.arange(6).reshape(2, 3) assert_raises(ValueError, nditer, [a, None], ['external_loop'], [['readonly'], ['readwrite', 'allocate']], op_axes=[[0, 1], [-1, -1]]) def test_iter_reduction(): # Test doing reductions with the iterator a = np.arange(6) i = nditer([a, None], ['reduce_ok'], [['readonly'], ['readwrite', 'allocate']], op_axes=[[0], [-1]]) # Need to initialize the output operand to the addition unit i.operands[1][...] = 0 # Do the reduction for x, y in i: y[...] += x # Since no axes were specified, should have allocated a scalar assert_equal(i.operands[1].ndim, 0) assert_equal(i.operands[1], np.sum(a)) a = np.arange(6).reshape(2, 3) i = nditer([a, None], ['reduce_ok', 'external_loop'], [['readonly'], ['readwrite', 'allocate']], op_axes=[[0, 1], [-1, -1]]) # Need to initialize the output operand to the addition unit i.operands[1][...] = 0 # Reduction shape/strides for the output assert_equal(i[1].shape, (6,)) assert_equal(i[1].strides, (0,)) # Do the reduction for x, y in i: y[...] += x # Since no axes were specified, should have allocated a scalar assert_equal(i.operands[1].ndim, 0) assert_equal(i.operands[1], np.sum(a)) # This is a tricky reduction case for the buffering double loop # to handle a = np.ones((2, 3, 5)) it1 = nditer([a, None], ['reduce_ok', 'external_loop'], [['readonly'], ['readwrite', 'allocate']], op_axes=[None, [0, -1, 1]]) it2 = nditer([a, None], ['reduce_ok', 'external_loop', 'buffered', 'delay_bufalloc'], [['readonly'], ['readwrite', 'allocate']], op_axes=[None, [0, -1, 1]], buffersize=10) it1.operands[1].fill(0) it2.operands[1].fill(0) it2.reset() for x in it1: x[1][...] += x[0] for x in it2: x[1][...] += x[0] assert_equal(it1.operands[1], it2.operands[1]) assert_equal(it2.operands[1].sum(), a.size) def test_iter_buffering_reduction(): # Test doing buffered reductions with the iterator a = np.arange(6) b = np.array(0., dtype='f8').byteswap().newbyteorder() i = nditer([a, b], ['reduce_ok', 'buffered'], [['readonly'], ['readwrite', 'nbo']], op_axes=[[0], [-1]]) assert_equal(i[1].dtype, np.dtype('f8')) assert_(i[1].dtype != b.dtype) # Do the reduction for x, y in i: y[...] += x # Since no axes were specified, should have allocated a scalar assert_equal(b, np.sum(a)) a = np.arange(6).reshape(2, 3) b = np.array([0, 0], dtype='f8').byteswap().newbyteorder() i = nditer([a, b], ['reduce_ok', 'external_loop', 'buffered'], [['readonly'], ['readwrite', 'nbo']], op_axes=[[0, 1], [0, -1]]) # Reduction shape/strides for the output assert_equal(i[1].shape, (3,)) assert_equal(i[1].strides, (0,)) # Do the reduction for x, y in i: y[...] += x assert_equal(b, np.sum(a, axis=1)) # Iterator inner double loop was wrong on this one p = np.arange(2) + 1 it = np.nditer([p, None], ['delay_bufalloc', 'reduce_ok', 'buffered', 'external_loop'], [['readonly'], ['readwrite', 'allocate']], op_axes=[[-1, 0], [-1, -1]], itershape=(2, 2)) it.operands[1].fill(0) it.reset() assert_equal(it[0], [1, 2, 1, 2]) # Iterator inner loop should take argument contiguity into account x = np.ones((7, 13, 8), np.int8)[4:6,1:11:6,1:5].transpose(1, 2, 0) x[...] = np.arange(x.size).reshape(x.shape) y_base = np.arange(4*4, dtype=np.int8).reshape(4, 4) y_base_copy = y_base.copy() y = y_base[::2,:,None] it = np.nditer([y, x], ['buffered', 'external_loop', 'reduce_ok'], [['readwrite'], ['readonly']]) for a, b in it: a.fill(2) assert_equal(y_base[1::2], y_base_copy[1::2]) assert_equal(y_base[::2], 2) def test_iter_buffering_reduction_reuse_reduce_loops(): # There was a bug triggering reuse of the reduce loop inappropriately, # which caused processing to happen in unnecessarily small chunks # and overran the buffer. a = np.zeros((2, 7)) b = np.zeros((1, 7)) it = np.nditer([a, b], flags=['reduce_ok', 'external_loop', 'buffered'], op_flags=[['readonly'], ['readwrite']], buffersize=5) bufsizes = [] for x, y in it: bufsizes.append(x.shape[0]) assert_equal(bufsizes, [5, 2, 5, 2]) assert_equal(sum(bufsizes), a.size) def test_iter_writemasked_badinput(): a = np.zeros((2, 3)) b = np.zeros((3,)) m = np.array([[True, True, False], [False, True, False]]) m2 = np.array([True, True, False]) m3 = np.array([0, 1, 1], dtype='u1') mbad1 = np.array([0, 1, 1], dtype='i1') mbad2 = np.array([0, 1, 1], dtype='f4') # Need an 'arraymask' if any operand is 'writemasked' assert_raises(ValueError, nditer, [a, m], [], [['readwrite', 'writemasked'], ['readonly']]) # A 'writemasked' operand must not be readonly assert_raises(ValueError, nditer, [a, m], [], [['readonly', 'writemasked'], ['readonly', 'arraymask']]) # 'writemasked' and 'arraymask' may not be used together assert_raises(ValueError, nditer, [a, m], [], [['readonly'], ['readwrite', 'arraymask', 'writemasked']]) # 'arraymask' may only be specified once assert_raises(ValueError, nditer, [a, m, m2], [], [['readwrite', 'writemasked'], ['readonly', 'arraymask'], ['readonly', 'arraymask']]) # An 'arraymask' with nothing 'writemasked' also doesn't make sense assert_raises(ValueError, nditer, [a, m], [], [['readwrite'], ['readonly', 'arraymask']]) # A writemasked reduction requires a similarly smaller mask assert_raises(ValueError, nditer, [a, b, m], ['reduce_ok'], [['readonly'], ['readwrite', 'writemasked'], ['readonly', 'arraymask']]) # But this should work with a smaller/equal mask to the reduction operand np.nditer([a, b, m2], ['reduce_ok'], [['readonly'], ['readwrite', 'writemasked'], ['readonly', 'arraymask']]) # The arraymask itself cannot be a reduction assert_raises(ValueError, nditer, [a, b, m2], ['reduce_ok'], [['readonly'], ['readwrite', 'writemasked'], ['readwrite', 'arraymask']]) # A uint8 mask is ok too np.nditer([a, m3], ['buffered'], [['readwrite', 'writemasked'], ['readonly', 'arraymask']], op_dtypes=['f4', None], casting='same_kind') # An int8 mask isn't ok assert_raises(TypeError, np.nditer, [a, mbad1], ['buffered'], [['readwrite', 'writemasked'], ['readonly', 'arraymask']], op_dtypes=['f4', None], casting='same_kind') # A float32 mask isn't ok assert_raises(TypeError, np.nditer, [a, mbad2], ['buffered'], [['readwrite', 'writemasked'], ['readonly', 'arraymask']], op_dtypes=['f4', None], casting='same_kind') def test_iter_writemasked(): a = np.zeros((3,), dtype='f8') msk = np.array([True, True, False]) # When buffering is unused, 'writemasked' effectively does nothing. # It's up to the user of the iterator to obey the requested semantics. it = np.nditer([a, msk], [], [['readwrite', 'writemasked'], ['readonly', 'arraymask']]) for x, m in it: x[...] = 1 # Because we violated the semantics, all the values became 1 assert_equal(a, [1, 1, 1]) # Even if buffering is enabled, we still may be accessing the array # directly. it = np.nditer([a, msk], ['buffered'], [['readwrite', 'writemasked'], ['readonly', 'arraymask']]) for x, m in it: x[...] = 2.5 # Because we violated the semantics, all the values became 2.5 assert_equal(a, [2.5, 2.5, 2.5]) # If buffering will definitely happening, for instance because of # a cast, only the items selected by the mask will be copied back from # the buffer. it = np.nditer([a, msk], ['buffered'], [['readwrite', 'writemasked'], ['readonly', 'arraymask']], op_dtypes=['i8', None], casting='unsafe') for x, m in it: x[...] = 3 # Even though we violated the semantics, only the selected values # were copied back assert_equal(a, [3, 3, 2.5]) def test_iter_non_writable_attribute_deletion(): it = np.nditer(np.ones(2)) attr = ["value", "shape", "operands", "itviews", "has_delayed_bufalloc", "iterationneedsapi", "has_multi_index", "has_index", "dtypes", "ndim", "nop", "itersize", "finished"] for s in attr: assert_raises(AttributeError, delattr, it, s) def test_iter_writable_attribute_deletion(): it = np.nditer(np.ones(2)) attr = [ "multi_index", "index", "iterrange", "iterindex"] for s in attr: assert_raises(AttributeError, delattr, it, s) def test_iter_element_deletion(): it = np.nditer(np.ones(3)) try: del it[1] del it[1:2] except TypeError: pass except: raise AssertionError def test_iter_allocated_array_dtypes(): # If the dtype of an allocated output has a shape, the shape gets # tacked onto the end of the result. it = np.nditer(([1, 3, 20], None), op_dtypes=[None, ('i4', (2,))]) for a, b in it: b[0] = a - 1 b[1] = a + 1 assert_equal(it.operands[1], [[0, 2], [2, 4], [19, 21]]) # Make sure this works for scalars too it = np.nditer((10, 2, None), op_dtypes=[None, None, ('i4', (2, 2))]) for a, b, c in it: c[0, 0] = a - b c[0, 1] = a + b c[1, 0] = a * b c[1, 1] = a / b assert_equal(it.operands[2], [[8, 12], [20, 5]]) def test_0d_iter(): # Basic test for iteration of 0-d arrays: i = nditer([2, 3], ['multi_index'], [['readonly']]*2) assert_equal(i.ndim, 0) assert_equal(next(i), (2, 3)) assert_equal(i.multi_index, ()) assert_equal(i.iterindex, 0) assert_raises(StopIteration, next, i) # test reset: i.reset() assert_equal(next(i), (2, 3)) assert_raises(StopIteration, next, i) # test forcing to 0-d i = nditer(np.arange(5), ['multi_index'], [['readonly']], op_axes=[()]) assert_equal(i.ndim, 0) assert_equal(len(i), 1) # note that itershape=(), still behaves like None due to the conversions # Test a more complex buffered casting case (same as another test above) sdt = [('a', 'f4'), ('b', 'i8'), ('c', 'c8', (2, 3)), ('d', 'O')] a = np.array(0.5, dtype='f4') i = nditer(a, ['buffered', 'refs_ok'], ['readonly'], casting='unsafe', op_dtypes=sdt) vals = next(i) assert_equal(vals['a'], 0.5) assert_equal(vals['b'], 0) assert_equal(vals['c'], [[(0.5)]*3]*2) assert_equal(vals['d'], 0.5) def test_0d_nested_iter(): a = np.arange(12).reshape(2, 3, 2) i, j = np.nested_iters(a, [[], [1, 0, 2]]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]) i, j = np.nested_iters(a, [[1, 0, 2], []]) vals = [] for x in i: vals.append([y for y in j]) assert_equal(vals, [[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]]) i, j, k = np.nested_iters(a, [[2, 0], [], [1]]) vals = [] for x in i: for y in j: vals.append([z for z in k]) assert_equal(vals, [[0, 2, 4], [1, 3, 5], [6, 8, 10], [7, 9, 11]]) def test_iter_too_large(): # The total size of the iterator must not exceed the maximum intp due # to broadcasting. Dividing by 1024 will keep it small enough to # give a legal array. size = np.iinfo(np.intp).max // 1024 arr = np.lib.stride_tricks.as_strided(np.zeros(1), (size,), (0,)) assert_raises(ValueError, nditer, (arr, arr[:, None])) # test the same for multiindex. That may get more interesting when # removing 0 dimensional axis is allowed (since an iterator can grow then) assert_raises(ValueError, nditer, (arr, arr[:, None]), flags=['multi_index']) def test_iter_too_large_with_multiindex(): # When a multi index is being tracked, the error is delayed this # checks the delayed error messages and getting below that by # removing an axis. base_size = 2**10 num = 1 while base_size**num < np.iinfo(np.intp).max: num += 1 shape_template = [1, 1] * num arrays = [] for i in range(num): shape = shape_template[:] shape[i * 2] = 2**10 arrays.append(np.empty(shape)) arrays = tuple(arrays) # arrays are now too large to be broadcast. The different modes test # different nditer functionality with or without GIL. for mode in range(6): assert_raises(ValueError, test_nditer_too_large, arrays, -1, mode) # but if we do nothing with the nditer, it can be constructed: test_nditer_too_large(arrays, -1, 7) # When an axis is removed, things should work again (half the time): for i in range(num): for mode in range(6): # an axis with size 1024 is removed: test_nditer_too_large(arrays, i*2, mode) # an axis with size 1 is removed: assert_raises(ValueError, test_nditer_too_large, arrays, i*2 + 1, mode) if __name__ == "__main__": run_module_suite()
unknown
codeparrot/codeparrot-clean
import numpy as np from tf import transformations bbetData = np.loadtxt('bb23.txt', delimiter=',') bbhtData = np.loadtxt('bb21.txt', delimiter=',') hcetData = np.loadtxt('hc23.txt', delimiter=',') bbetIds = bbetData[:, 0] bbhtIds = bbhtData[:, 0] hcetIds = hcetData[:, 0] validIds = np.intersect1d(bbetIds, np.intersect1d(bbhtIds, hcetIds)) bbetValidIndices = np.in1d(bbetIds, validIds) bbhtValidIndices = np.in1d(bbhtIds, validIds) hcetValidIndices = np.in1d(hcetIds, validIds) bbetData = bbetData[bbetValidIndices, 1:] bbhtData = bbhtData[bbhtValidIndices, 1:] hcetData = hcetData[hcetValidIndices, 1:] numTransforms = len(validIds) bbHets = np.reshape(bbetData.T, (4, 4, -1), 3) bbHhts = np.reshape(bbhtData.T, (4, 4, -1), 3) hcHets = np.reshape(hcetData.T, (4, 4, -1), 3) rlfHhc = np.zeros([4, 4, numTransforms]) bbHhcs = np.zeros([4, 4, numTransforms]) for i in xrange(numTransforms): bbHhcs[:, :, i] = np.dot(bbHets[:, :, i], np.linalg.inv(hcHets[:, :, i])) htHhcs = np.zeros([4, 4, numTransforms]) for i in xrange(numTransforms): htHhcs[:, :, i] = np.dot(np.linalg.inv(bbHhts[:, :, i]), bbHhcs[:, :, i]) avgT = np.zeros([3, 1]) avgR = np.zeros([3, 3]) baselineT = htHhcs[0:3, 3, 4].reshape(3, 1) skipped = 0 for i in xrange(numTransforms): t = htHhcs[0:3, 3, i].reshape(3, 1) if np.linalg.norm(baselineT - t) > .03: skipped += 1 continue avgT += htHhcs[0:3, 3, i].reshape(3, 1) avgR += htHhcs[0:3, 0:3, i] avgT = avgT / (numTransforms - skipped) avgR = avgR / (numTransforms - skipped) u, s, v = np.linalg.svd(avgR) avgR = np.dot(u, v) paddedR = np.zeros((4, 4)) paddedR[3, 3] = 1 paddedR[0:3, 0:3] = avgR quat = transformations.quaternion_from_matrix(paddedR) print avgT print quat f = open('leftHandCalibration.txt', 'w') np.savetxt(f, avgT, newline='\n') f.write('----------------------\n') np.savetxt(f, quat, newline='\n')
unknown
codeparrot/codeparrot-clean
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package math // Modf returns integer and fractional floating-point numbers // that sum to f. Both values have the same sign as f. // // Special cases are: // // Modf(±Inf) = ±Inf, NaN // Modf(NaN) = NaN, NaN func Modf(f float64) (integer float64, fractional float64) { integer = Trunc(f) fractional = Copysign(f-integer, f) return }
go
github
https://github.com/golang/go
src/math/modf.go
# # Copyright (c) 2014 ThoughtWorks, Inc. # # Pixelated is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pixelated is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Pixelated. If not, see <http://www.gnu.org/licenses/>. import getpass import re from collections import namedtuple from leap.bitmask.bonafide.provider import Api from leap.bitmask.bonafide.session import Session from pixelated.bitmask_libraries.certs import LeapCertificate from pixelated.bitmask_libraries.provider import LeapProvider from pixelated.config import arguments from pixelated.config import leap_config from pixelated.config import logger as logger_config from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks from twisted.logger import Logger Credentials = namedtuple('Credentials', 'username, password') logger = Logger() def _validate(username, password): validate_username(username) validate_password(password) def _set_provider(provider_cert, provider_cert_fingerprint, server_name, leap_home=None): if leap_home: leap_config.set_leap_home(leap_home) LeapCertificate.set_cert_and_fingerprint(provider_cert, provider_cert_fingerprint) provider = LeapProvider(server_name) provider.setup_ca() provider.download_settings() return provider def _set_leap_provider(args): return _set_provider(args.leap_provider_cert, args.leap_provider_cert_fingerprint, args.provider, args.leap_home) def _bonafide_session(username, password, provider): srp_provider = Api(provider.api_uri) credentials = Credentials(username, password) return Session(credentials, srp_provider, provider.local_ca_crt) def log_results(created, username): if created: logger.info('User %s successfully registered' % username) else: logger.error("Register failed") @inlineCallbacks def register(username, password, leap_provider, invite=None): if not password: password = getpass.getpass('Please enter password for %s: ' % username) _validate(username, password) logger.info('password validated...') srp_auth = _bonafide_session(username, password, leap_provider) created, user = yield srp_auth.signup(username, password, invite) log_results(created, username) def validate_username(username): accepted_characters = '^[a-z0-9\-\_\.]*$' if not re.match(accepted_characters, username): raise ValueError('Only lowercase letters, digits, . - and _ allowed.') def validate_password(password): if len(password) < 8: logger.info('password not validated...') raise ValueError('The password must have at least 8 characters') def initialize(): logger_config.init(debug=False) args = arguments.parse_register_args() leap_provider = _set_leap_provider(args) def show_error(err): logger.info('error: %s' % err) def shut_down(_): reactor.stop() def _register(): d = register( args.username, args.password, leap_provider, args.invite_code) d.addErrback(show_error) d.addBoth(shut_down) reactor.callWhenRunning(_register) reactor.run()
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- """ *************************************************************************** SextanteToolsTest.py --------------------- Date : April 2013 Copyright : (C) 2013 by Victor Olaya Email : volayaf at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ __author__ = 'Victor Olaya' __date__ = 'April 2013' __copyright__ = '(C) 2013, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import sextante import unittest from sextante.tests.TestData import points, points2, polygons, polygons2, lines, union,\ table, polygonsGeoJson, raster from sextante.core import Sextante from sextante.tools.vector import values from sextante.tools.general import getfromname class SextanteToolsTest(unittest.TestCase): '''tests the method imported when doing an "import sextante", and also in sextante.tools. They are mostly convenience tools''' def test_getobject(self): layer = sextante.getobject(points()); self.assertIsNotNone(layer) layer = sextante.getobject("points"); self.assertIsNotNone(layer) def test_runandload(self): sextante.runandload("qgis:countpointsinpolygon",polygons(),points(),"NUMPOINTS", None) layer = getfromname("Result") self.assertIsNotNone(layer) def test_featuresWithoutSelection(self): layer = sextante.getobject(points()) features = sextante.getfeatures(layer) self.assertEqual(12, len(features)) def test_featuresWithSelection(self): layer = sextante.getobject(points()) feature = layer.getFeatures().next() selected = [feature.id()] layer.setSelectedFeatures(selected) features = sextante.getfeatures(layer) self.assertEqual(1, len(features)) layer.setSelectedFeatures([]) def test_attributeValues(self): layer = sextante.getobject(points()) attributeValues = values(layer, "ID") i = 1 for value in attributeValues['ID']: self.assertEqual(int(i), int(value)) i+=1 self.assertEquals(13,i) def test_extent(self): pass def suite(): suite = unittest.makeSuite(SextanteToolsTest, 'test') return suite def runtests(): result = unittest.TestResult() testsuite = suite() testsuite.run(result) return result
unknown
codeparrot/codeparrot-clean
// RUN: pp-trace -callbacks '*,-FileChanged,-MacroDefined' %s -- -target x86_64-unknown-windows-msvc -fms-extensions -w | FileCheck --strict-whitespace %s #pragma comment(compiler, "compiler comment") #pragma comment(exestr, "exestr comment") #pragma comment(lib, "lib comment") #pragma comment(linker, "linker comment") #pragma comment(user, "user comment") #pragma detect_mismatch("name argument", "value argument") #pragma __debug(assert) #pragma message("message argument") #pragma warning(push, 1) #pragma warning(pop) #pragma warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9) // CHECK: --- // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "<built-in>:{{.+}}:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "<built-in>:{{.+}}:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:3:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaComment // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:3:9" // CHECK-NEXT: Kind: compiler // CHECK-NEXT: Str: compiler comment // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:4:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaComment // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:4:9" // CHECK-NEXT: Kind: exestr // CHECK-NEXT: Str: exestr comment // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:5:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaComment // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:5:9" // CHECK-NEXT: Kind: lib // CHECK-NEXT: Str: lib comment // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:6:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaComment // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:6:9" // CHECK-NEXT: Kind: linker // CHECK-NEXT: Str: linker comment // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:7:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaComment // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:7:9" // CHECK-NEXT: Kind: user // CHECK-NEXT: Str: user comment // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:9:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaDetectMismatch // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:9:9" // CHECK-NEXT: Name: name argument // CHECK-NEXT: Value: value argument // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:11:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:13:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaMessage // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:13:9" // CHECK-NEXT: Namespace: // CHECK-NEXT: Kind: PMK_Message // CHECK-NEXT: Str: message argument // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:15:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaWarningPush // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:15:9" // CHECK-NEXT: Level: 1 // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:16:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaWarningPop // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:16:9" // CHECK-NEXT: - Callback: PragmaDirective // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:17:1" // CHECK-NEXT: Introducer: PIK_HashPragma // CHECK-NEXT: - Callback: PragmaWarning // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:17:9" // CHECK-NEXT: WarningSpec: PWS_Disable // CHECK-NEXT: Ids: [1, 2, 3] // CHECK-NEXT: - Callback: PragmaWarning // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:17:9" // CHECK-NEXT: WarningSpec: PWS_Error // CHECK-NEXT: Ids: [4, 5, 6] // CHECK-NEXT: - Callback: PragmaWarning // CHECK-NEXT: Loc: "{{.*}}{{[/\\]}}pp-trace-pragma-ms.cpp:17:9" // CHECK-NEXT: WarningSpec: PWS_Suppress // CHECK-NEXT: Ids: [7, 8, 9] // CHECK-NEXT: - Callback: EndOfMainFile // CHECK-NEXT: ...
cpp
github
https://github.com/llvm/llvm-project
clang-tools-extra/test/pp-trace/pp-trace-pragma-ms.cpp
# -*- coding: utf-8 -*- # # packages.py — packages table model # # This file is part of debexpo - https://alioth.debian.org/projects/debexpo/ # # Copyright © 2008 Jonny Lamb <jonny@debian.org> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. """ Holds packages table model. """ __author__ = 'Jonny Lamb' __copyright__ = 'Copyright © 2008 Jonny Lamb' __license__ = 'MIT' import sqlalchemy as sa from sqlalchemy import orm from debexpo.model import meta, OrmObject from debexpo.model.users import User from debexpo.lib.constants import PACKAGE_NEEDS_SPONSOR_UNKNOWN t_packages = sa.Table('packages', meta.metadata, sa.Column('id', sa.types.Integer, primary_key=True), sa.Column('name', sa.types.Text(), nullable=False), sa.Column('user_id', sa.types.Integer, sa.ForeignKey('users.id')), sa.Column('description', sa.types.Text(), nullable=True), sa.Column('watch_counter', sa.types.Integer, default=0), sa.Column('download_counter', sa.types.Integer, default=0), sa.Column('needs_sponsor', sa.types.Integer, nullable=False, default=PACKAGE_NEEDS_SPONSOR_UNKNOWN), ) class Package(OrmObject): foreign = ['user'] def get_description(self): return self.description orm.mapper(Package, t_packages, properties={ 'user' : orm.relation(User, backref='packages') })
unknown
codeparrot/codeparrot-clean
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.ReflectionFreeAssertThrows.assertThrows; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.truth.Truth.assertThat; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.base.Splitter.MapSplitter; import com.google.common.collect.ImmutableMap; import com.google.common.testing.NullPointerTester; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import junit.framework.TestCase; import org.jspecify.annotations.NullMarked; /** * @author Julien Silland */ @NullMarked @GwtCompatible public class SplitterTest extends TestCase { private static final Splitter COMMA_SPLITTER = Splitter.on(','); public void testSplitNullString() { assertThrows(NullPointerException.class, () -> COMMA_SPLITTER.split(null)); } public void testCharacterSimpleSplit() { String simple = "a,b,c"; Iterable<String> letters = COMMA_SPLITTER.split(simple); assertThat(letters).containsExactly("a", "b", "c").inOrder(); } /** * All of the infrastructure of split and splitToString is identical, so we do one test of * splitToString. All other cases should be covered by testing of split. * * <p>TODO(user): It would be good to make all the relevant tests run on both split and * splitToString automatically. */ public void testCharacterSimpleSplitToList() { String simple = "a,b,c"; List<String> letters = COMMA_SPLITTER.splitToList(simple); assertThat(letters).containsExactly("a", "b", "c").inOrder(); } public void testCharacterSimpleSplitToStream() { String simple = "a,b,c"; List<String> letters = COMMA_SPLITTER.splitToStream(simple).collect(toImmutableList()); assertThat(letters).containsExactly("a", "b", "c").inOrder(); } public void testToString() { assertEquals("[]", COMMA_SPLITTER.split("").toString()); assertEquals("[a, b, c]", COMMA_SPLITTER.split("a,b,c").toString()); assertEquals("[yam, bam, jam, ham]", Splitter.on(", ").split("yam, bam, jam, ham").toString()); } public void testCharacterSimpleSplitWithNoDelimiter() { String simple = "a,b,c"; Iterable<String> letters = Splitter.on('.').split(simple); assertThat(letters).containsExactly("a,b,c").inOrder(); } public void testCharacterSplitWithDoubleDelimiter() { String doubled = "a,,b,c"; Iterable<String> letters = COMMA_SPLITTER.split(doubled); assertThat(letters).containsExactly("a", "", "b", "c").inOrder(); } public void testCharacterSplitWithDoubleDelimiterAndSpace() { String doubled = "a,, b,c"; Iterable<String> letters = COMMA_SPLITTER.split(doubled); assertThat(letters).containsExactly("a", "", " b", "c").inOrder(); } public void testCharacterSplitWithTrailingDelimiter() { String trailing = "a,b,c,"; Iterable<String> letters = COMMA_SPLITTER.split(trailing); assertThat(letters).containsExactly("a", "b", "c", "").inOrder(); } public void testCharacterSplitWithLeadingDelimiter() { String leading = ",a,b,c"; Iterable<String> letters = COMMA_SPLITTER.split(leading); assertThat(letters).containsExactly("", "a", "b", "c").inOrder(); } public void testCharacterSplitWithMultipleLetters() { Iterable<String> testCharacteringMotto = Splitter.on('-').split("Testing-rocks-Debugging-sucks"); assertThat(testCharacteringMotto) .containsExactly("Testing", "rocks", "Debugging", "sucks") .inOrder(); } public void testCharacterSplitWithMatcherDelimiter() { Iterable<String> testCharacteringMotto = Splitter.on(CharMatcher.whitespace()).split("Testing\nrocks\tDebugging sucks"); assertThat(testCharacteringMotto) .containsExactly("Testing", "rocks", "Debugging", "sucks") .inOrder(); } public void testCharacterSplitWithDoubleDelimiterOmitEmptyStrings() { String doubled = "a..b.c"; Iterable<String> letters = Splitter.on('.').omitEmptyStrings().split(doubled); assertThat(letters).containsExactly("a", "b", "c").inOrder(); } public void testCharacterSplitEmptyToken() { String emptyToken = "a. .c"; Iterable<String> letters = Splitter.on('.').trimResults().split(emptyToken); assertThat(letters).containsExactly("a", "", "c").inOrder(); } public void testCharacterSplitEmptyTokenOmitEmptyStrings() { String emptyToken = "a. .c"; Iterable<String> letters = Splitter.on('.').omitEmptyStrings().trimResults().split(emptyToken); assertThat(letters).containsExactly("a", "c").inOrder(); } public void testCharacterSplitOnEmptyString() { Iterable<String> nothing = Splitter.on('.').split(""); assertThat(nothing).containsExactly("").inOrder(); } public void testCharacterSplitOnEmptyStringOmitEmptyStrings() { assertThat(Splitter.on('.').omitEmptyStrings().split("")).isEmpty(); } public void testCharacterSplitOnOnlyDelimiter() { Iterable<String> blankblank = Splitter.on('.').split("."); assertThat(blankblank).containsExactly("", "").inOrder(); } public void testCharacterSplitOnOnlyDelimitersOmitEmptyStrings() { Iterable<String> empty = Splitter.on('.').omitEmptyStrings().split("..."); assertThat(empty).isEmpty(); } public void testCharacterSplitWithTrim() { String jacksons = "arfo(Marlon)aorf, (Michael)orfa, afro(Jackie)orfa, ofar(Jemaine), aff(Tito)"; Iterable<String> family = COMMA_SPLITTER .trimResults(CharMatcher.anyOf("afro").or(CharMatcher.whitespace())) .split(jacksons); assertThat(family) .containsExactly("(Marlon)", "(Michael)", "(Jackie)", "(Jemaine)", "(Tito)") .inOrder(); } public void testStringSimpleSplit() { String simple = "a,b,c"; Iterable<String> letters = Splitter.on(",").split(simple); assertThat(letters).containsExactly("a", "b", "c").inOrder(); } public void testStringSimpleSplitWithNoDelimiter() { String simple = "a,b,c"; Iterable<String> letters = Splitter.on(".").split(simple); assertThat(letters).containsExactly("a,b,c").inOrder(); } public void testStringSplitWithDoubleDelimiter() { String doubled = "a,,b,c"; Iterable<String> letters = Splitter.on(",").split(doubled); assertThat(letters).containsExactly("a", "", "b", "c").inOrder(); } public void testStringSplitWithDoubleDelimiterAndSpace() { String doubled = "a,, b,c"; Iterable<String> letters = Splitter.on(",").split(doubled); assertThat(letters).containsExactly("a", "", " b", "c").inOrder(); } public void testStringSplitWithTrailingDelimiter() { String trailing = "a,b,c,"; Iterable<String> letters = Splitter.on(",").split(trailing); assertThat(letters).containsExactly("a", "b", "c", "").inOrder(); } public void testStringSplitWithLeadingDelimiter() { String leading = ",a,b,c"; Iterable<String> letters = Splitter.on(",").split(leading); assertThat(letters).containsExactly("", "a", "b", "c").inOrder(); } public void testStringSplitWithMultipleLetters() { Iterable<String> testStringingMotto = Splitter.on("-").split("Testing-rocks-Debugging-sucks"); assertThat(testStringingMotto) .containsExactly("Testing", "rocks", "Debugging", "sucks") .inOrder(); } public void testStringSplitWithDoubleDelimiterOmitEmptyStrings() { String doubled = "a..b.c"; Iterable<String> letters = Splitter.on(".").omitEmptyStrings().split(doubled); assertThat(letters).containsExactly("a", "b", "c").inOrder(); } public void testStringSplitEmptyToken() { String emptyToken = "a. .c"; Iterable<String> letters = Splitter.on(".").trimResults().split(emptyToken); assertThat(letters).containsExactly("a", "", "c").inOrder(); } public void testStringSplitEmptyTokenOmitEmptyStrings() { String emptyToken = "a. .c"; Iterable<String> letters = Splitter.on(".").omitEmptyStrings().trimResults().split(emptyToken); assertThat(letters).containsExactly("a", "c").inOrder(); } public void testStringSplitWithLongDelimiter() { String longDelimiter = "a, b, c"; Iterable<String> letters = Splitter.on(", ").split(longDelimiter); assertThat(letters).containsExactly("a", "b", "c").inOrder(); } public void testStringSplitWithLongLeadingDelimiter() { String longDelimiter = ", a, b, c"; Iterable<String> letters = Splitter.on(", ").split(longDelimiter); assertThat(letters).containsExactly("", "a", "b", "c").inOrder(); } public void testStringSplitWithLongTrailingDelimiter() { String longDelimiter = "a, b, c, "; Iterable<String> letters = Splitter.on(", ").split(longDelimiter); assertThat(letters).containsExactly("a", "b", "c", "").inOrder(); } public void testStringSplitWithDelimiterSubstringInValue() { String fourCommasAndFourSpaces = ",,,, "; Iterable<String> threeCommasThenThreeSpaces = Splitter.on(", ").split(fourCommasAndFourSpaces); assertThat(threeCommasThenThreeSpaces).containsExactly(",,,", " ").inOrder(); } public void testStringSplitWithEmptyString() { assertThrows(IllegalArgumentException.class, () -> Splitter.on("")); } public void testStringSplitOnEmptyString() { Iterable<String> notMuch = Splitter.on(".").split(""); assertThat(notMuch).containsExactly("").inOrder(); } public void testStringSplitOnEmptyStringOmitEmptyString() { assertThat(Splitter.on(".").omitEmptyStrings().split("")).isEmpty(); } public void testStringSplitOnOnlyDelimiter() { Iterable<String> blankblank = Splitter.on(".").split("."); assertThat(blankblank).containsExactly("", "").inOrder(); } public void testStringSplitOnOnlyDelimitersOmitEmptyStrings() { Iterable<String> empty = Splitter.on(".").omitEmptyStrings().split("..."); assertThat(empty).isEmpty(); } public void testStringSplitWithTrim() { String jacksons = "arfo(Marlon)aorf, (Michael)orfa, afro(Jackie)orfa, ofar(Jemaine), aff(Tito)"; Iterable<String> family = Splitter.on(",") .trimResults(CharMatcher.anyOf("afro").or(CharMatcher.whitespace())) .split(jacksons); assertThat(family) .containsExactly("(Marlon)", "(Michael)", "(Jackie)", "(Jemaine)", "(Tito)") .inOrder(); } @GwtIncompatible // Splitter.onPattern public void testPatternSimpleSplit() { String simple = "a,b,c"; Iterable<String> letters = Splitter.onPattern(",").split(simple); assertThat(letters).containsExactly("a", "b", "c").inOrder(); } @GwtIncompatible // Splitter.onPattern public void testPatternSimpleSplitWithNoDelimiter() { String simple = "a,b,c"; Iterable<String> letters = Splitter.onPattern("foo").split(simple); assertThat(letters).containsExactly("a,b,c").inOrder(); } @GwtIncompatible // Splitter.onPattern public void testPatternSplitWithDoubleDelimiter() { String doubled = "a,,b,c"; Iterable<String> letters = Splitter.onPattern(",").split(doubled); assertThat(letters).containsExactly("a", "", "b", "c").inOrder(); } @GwtIncompatible // Splitter.onPattern public void testPatternSplitWithDoubleDelimiterAndSpace() { String doubled = "a,, b,c"; Iterable<String> letters = Splitter.onPattern(",").split(doubled); assertThat(letters).containsExactly("a", "", " b", "c").inOrder(); } @GwtIncompatible // Splitter.onPattern public void testPatternSplitWithTrailingDelimiter() { String trailing = "a,b,c,"; Iterable<String> letters = Splitter.onPattern(",").split(trailing); assertThat(letters).containsExactly("a", "b", "c", "").inOrder(); } @GwtIncompatible // Splitter.onPattern public void testPatternSplitWithLeadingDelimiter() { String leading = ",a,b,c"; Iterable<String> letters = Splitter.onPattern(",").split(leading); assertThat(letters).containsExactly("", "a", "b", "c").inOrder(); } // TODO(kevinb): the name of this method suggests it might not actually be testing what it // intends to be testing? @GwtIncompatible // Splitter.onPattern public void testPatternSplitWithMultipleLetters() { Iterable<String> testPatterningMotto = Splitter.onPattern("-").split("Testing-rocks-Debugging-sucks"); assertThat(testPatterningMotto) .containsExactly("Testing", "rocks", "Debugging", "sucks") .inOrder(); } @GwtIncompatible // java.util.regex.Pattern private static Pattern literalDotPattern() { return Pattern.compile("\\."); } @GwtIncompatible // java.util.regex.Pattern public void testPatternSplitWithDoubleDelimiterOmitEmptyStrings() { String doubled = "a..b.c"; Iterable<String> letters = Splitter.on(literalDotPattern()).omitEmptyStrings().split(doubled); assertThat(letters).containsExactly("a", "b", "c").inOrder(); } @J2ktIncompatible // Kotlin Native's regex is based on Apache Harmony, like old Android @GwtIncompatible // java.util.regex.Pattern @AndroidIncompatible // Bug in older versions of Android we test against, since fixed. public void testPatternSplitLookBehind() { if (!CommonPattern.isPcreLike()) { return; } String toSplit = ":foo::barbaz:"; String regexPattern = "(?<=:)"; Iterable<String> split = Splitter.onPattern(regexPattern).split(toSplit); assertThat(split).containsExactly(":", "foo:", ":", "barbaz:").inOrder(); // splits into chunks ending in : } @J2ktIncompatible // Kotlin Native's regex is based on Apache Harmony, like old Android @GwtIncompatible // java.util.regex.Pattern @AndroidIncompatible // Bug in older versions of Android we test against, since fixed. public void testPatternSplitWordBoundary() { String string = "foo<bar>bletch"; Iterable<String> words = Splitter.on(Pattern.compile("\\b")).split(string); assertThat(words).containsExactly("foo", "<", "bar", ">", "bletch").inOrder(); } @GwtIncompatible // java.util.regex.Pattern public void testPatternSplitWordBoundary_singleCharInput() { String string = "f"; Iterable<String> words = Splitter.on(Pattern.compile("\\b")).split(string); assertThat(words).containsExactly("f").inOrder(); } @AndroidIncompatible // Apparently Gingerbread's regex API is buggy. @J2ktIncompatible // Kotlin Native's regex is based on Apache Harmony, like old Android @GwtIncompatible // java.util.regex.Pattern public void testPatternSplitWordBoundary_singleWordInput() { String string = "foo"; Iterable<String> words = Splitter.on(Pattern.compile("\\b")).split(string); assertThat(words).containsExactly("foo").inOrder(); } @GwtIncompatible // java.util.regex.Pattern public void testPatternSplitEmptyToken() { String emptyToken = "a. .c"; Iterable<String> letters = Splitter.on(literalDotPattern()).trimResults().split(emptyToken); assertThat(letters).containsExactly("a", "", "c").inOrder(); } @GwtIncompatible // java.util.regex.Pattern public void testPatternSplitEmptyTokenOmitEmptyStrings() { String emptyToken = "a. .c"; Iterable<String> letters = Splitter.on(literalDotPattern()).omitEmptyStrings().trimResults().split(emptyToken); assertThat(letters).containsExactly("a", "c").inOrder(); } @GwtIncompatible // java.util.regex.Pattern public void testPatternSplitOnOnlyDelimiter() { Iterable<String> blankblank = Splitter.on(literalDotPattern()).split("."); assertThat(blankblank).containsExactly("", "").inOrder(); } @GwtIncompatible // java.util.regex.Pattern public void testPatternSplitOnOnlyDelimitersOmitEmptyStrings() { Iterable<String> empty = Splitter.on(literalDotPattern()).omitEmptyStrings().split("..."); assertThat(empty).isEmpty(); } @GwtIncompatible // java.util.regex.Pattern public void testPatternSplitMatchingIsGreedy() { String longDelimiter = "a, b, c"; Iterable<String> letters = Splitter.on(Pattern.compile(",\\s*")).split(longDelimiter); assertThat(letters).containsExactly("a", "b", "c").inOrder(); } @GwtIncompatible // java.util.regex.Pattern public void testPatternSplitWithLongLeadingDelimiter() { String longDelimiter = ", a, b, c"; Iterable<String> letters = Splitter.on(Pattern.compile(", ")).split(longDelimiter); assertThat(letters).containsExactly("", "a", "b", "c").inOrder(); } @GwtIncompatible // java.util.regex.Pattern public void testPatternSplitWithLongTrailingDelimiter() { String longDelimiter = "a, b, c/ "; Iterable<String> letters = Splitter.on(Pattern.compile("[,/]\\s")).split(longDelimiter); assertThat(letters).containsExactly("a", "b", "c", "").inOrder(); } @GwtIncompatible // java.util.regex.Pattern public void testPatternSplitInvalidPattern() { assertThrows(IllegalArgumentException.class, () -> Splitter.on(Pattern.compile("a*"))); } @GwtIncompatible // java.util.regex.Pattern public void testPatternSplitWithTrim() { String jacksons = "arfo(Marlon)aorf, (Michael)orfa, afro(Jackie)orfa, ofar(Jemaine), aff(Tito)"; Iterable<String> family = Splitter.on(Pattern.compile(",")) .trimResults(CharMatcher.anyOf("afro").or(CharMatcher.whitespace())) .split(jacksons); assertThat(family) .containsExactly("(Marlon)", "(Michael)", "(Jackie)", "(Jemaine)", "(Tito)") .inOrder(); } public void testSplitterIterableIsUnmodifiable_char() { assertIteratorIsUnmodifiable(COMMA_SPLITTER.split("a,b").iterator()); } public void testSplitterIterableIsUnmodifiable_string() { assertIteratorIsUnmodifiable(Splitter.on(",").split("a,b").iterator()); } @GwtIncompatible // java.util.regex.Pattern public void testSplitterIterableIsUnmodifiable_pattern() { assertIteratorIsUnmodifiable(Splitter.on(Pattern.compile(",")).split("a,b").iterator()); } private void assertIteratorIsUnmodifiable(Iterator<?> iterator) { iterator.next(); try { iterator.remove(); fail(); } catch (UnsupportedOperationException expected) { } } public void testSplitterIterableIsLazy_char() { assertSplitterIterableIsLazy(COMMA_SPLITTER); } public void testSplitterIterableIsLazy_string() { assertSplitterIterableIsLazy(Splitter.on(",")); } @J2ktIncompatible @GwtIncompatible // java.util.regex.Pattern @AndroidIncompatible // not clear that j.u.r.Matcher promises to handle mutations during use public void testSplitterIterableIsLazy_pattern() { if (!CommonPattern.isPcreLike()) { return; } assertSplitterIterableIsLazy(Splitter.onPattern(",")); } /** * This test really pushes the boundaries of what we support. In general the splitter's behaviour * is not well defined if the char sequence it's splitting is mutated during iteration. */ private void assertSplitterIterableIsLazy(Splitter splitter) { StringBuilder builder = new StringBuilder(); Iterator<String> iterator = splitter.split(builder).iterator(); builder.append("A,"); assertEquals("A", iterator.next()); builder.append("B,"); assertEquals("B", iterator.next()); builder.append("C"); assertEquals("C", iterator.next()); assertFalse(iterator.hasNext()); } public void testFixedLengthSimpleSplit() { String simple = "abcde"; Iterable<String> letters = Splitter.fixedLength(2).split(simple); assertThat(letters).containsExactly("ab", "cd", "e").inOrder(); } public void testFixedLengthSplitEqualChunkLength() { String simple = "abcdef"; Iterable<String> letters = Splitter.fixedLength(2).split(simple); assertThat(letters).containsExactly("ab", "cd", "ef").inOrder(); } public void testFixedLengthSplitOnlyOneChunk() { String simple = "abc"; Iterable<String> letters = Splitter.fixedLength(3).split(simple); assertThat(letters).containsExactly("abc").inOrder(); } public void testFixedLengthSplitSmallerString() { String simple = "ab"; Iterable<String> letters = Splitter.fixedLength(3).split(simple); assertThat(letters).containsExactly("ab").inOrder(); } public void testFixedLengthSplitEmptyString() { String simple = ""; Iterable<String> letters = Splitter.fixedLength(3).split(simple); assertThat(letters).containsExactly("").inOrder(); } public void testFixedLengthSplitEmptyStringWithOmitEmptyStrings() { assertThat(Splitter.fixedLength(3).omitEmptyStrings().split("")).isEmpty(); } public void testFixedLengthSplitIntoChars() { String simple = "abcd"; Iterable<String> letters = Splitter.fixedLength(1).split(simple); assertThat(letters).containsExactly("a", "b", "c", "d").inOrder(); } public void testFixedLengthSplitZeroChunkLen() { assertThrows(IllegalArgumentException.class, () -> Splitter.fixedLength(0)); } public void testFixedLengthSplitNegativeChunkLen() { assertThrows(IllegalArgumentException.class, () -> Splitter.fixedLength(-1)); } public void testLimitLarge() { String simple = "abcd"; Iterable<String> letters = Splitter.fixedLength(1).limit(100).split(simple); assertThat(letters).containsExactly("a", "b", "c", "d").inOrder(); } public void testLimitOne() { String simple = "abcd"; Iterable<String> letters = Splitter.fixedLength(1).limit(1).split(simple); assertThat(letters).containsExactly("abcd").inOrder(); } public void testLimitFixedLength() { String simple = "abcd"; Iterable<String> letters = Splitter.fixedLength(1).limit(2).split(simple); assertThat(letters).containsExactly("a", "bcd").inOrder(); } public void testLimit1Separator() { String simple = "a,b,c,d"; Iterable<String> items = COMMA_SPLITTER.limit(1).split(simple); assertThat(items).containsExactly("a,b,c,d").inOrder(); } public void testLimitSeparator() { String simple = "a,b,c,d"; Iterable<String> items = COMMA_SPLITTER.limit(2).split(simple); assertThat(items).containsExactly("a", "b,c,d").inOrder(); } public void testLimitExtraSeparators() { String text = "a,,,b,,c,d"; Iterable<String> items = COMMA_SPLITTER.limit(2).split(text); assertThat(items).containsExactly("a", ",,b,,c,d").inOrder(); } public void testLimitExtraSeparatorsOmitEmpty() { String text = "a,,,b,,c,d"; Iterable<String> items = COMMA_SPLITTER.limit(2).omitEmptyStrings().split(text); assertThat(items).containsExactly("a", "b,,c,d").inOrder(); } public void testLimitExtraSeparatorsOmitEmpty3() { String text = "a,,,b,,c,d"; Iterable<String> items = COMMA_SPLITTER.limit(3).omitEmptyStrings().split(text); assertThat(items).containsExactly("a", "b", "c,d").inOrder(); } public void testLimitExtraSeparatorsTrim() { String text = ",,a,, , b ,, c,d "; Iterable<String> items = COMMA_SPLITTER.limit(2).omitEmptyStrings().trimResults().split(text); assertThat(items).containsExactly("a", "b ,, c,d").inOrder(); } public void testLimitExtraSeparatorsTrim3() { String text = ",,a,, , b ,, c,d "; Iterable<String> items = COMMA_SPLITTER.limit(3).omitEmptyStrings().trimResults().split(text); assertThat(items).containsExactly("a", "b", "c,d").inOrder(); } public void testLimitExtraSeparatorsTrim1() { String text = ",,a,, , b ,, c,d "; Iterable<String> items = COMMA_SPLITTER.limit(1).omitEmptyStrings().trimResults().split(text); assertThat(items).containsExactly("a,, , b ,, c,d").inOrder(); } public void testLimitExtraSeparatorsTrim1NoOmit() { String text = ",,a,, , b ,, c,d "; Iterable<String> items = COMMA_SPLITTER.limit(1).trimResults().split(text); assertThat(items).containsExactly(",,a,, , b ,, c,d").inOrder(); } public void testLimitExtraSeparatorsTrim1Empty() { String text = ""; Iterable<String> items = COMMA_SPLITTER.limit(1).split(text); assertThat(items).containsExactly("").inOrder(); } public void testLimitExtraSeparatorsTrim1EmptyOmit() { String text = ""; Iterable<String> items = COMMA_SPLITTER.omitEmptyStrings().limit(1).split(text); assertThat(items).isEmpty(); } public void testInvalidZeroLimit() { assertThrows(IllegalArgumentException.class, () -> COMMA_SPLITTER.limit(0)); } @J2ktIncompatible @GwtIncompatible // NullPointerTester public void testNullPointers() { NullPointerTester tester = new NullPointerTester(); tester.testAllPublicStaticMethods(Splitter.class); tester.testAllPublicInstanceMethods(COMMA_SPLITTER); tester.testAllPublicInstanceMethods(COMMA_SPLITTER.trimResults()); } public void testMapSplitter_trimmedBoth() { Map<String, String> m = COMMA_SPLITTER .trimResults() .withKeyValueSeparator(Splitter.on(':').trimResults()) .split("boy : tom , girl: tina , cat : kitty , dog: tommy "); ImmutableMap<String, String> expected = ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy"); assertThat(m).isEqualTo(expected); assertThat(m.entrySet()).containsExactlyElementsIn(expected.entrySet()).inOrder(); } public void testMapSplitter_trimmedEntries() { Map<String, String> m = COMMA_SPLITTER .trimResults() .withKeyValueSeparator(":") .split("boy : tom , girl: tina , cat : kitty , dog: tommy "); ImmutableMap<String, String> expected = ImmutableMap.of("boy ", " tom", "girl", " tina", "cat ", " kitty", "dog", " tommy"); assertThat(m).isEqualTo(expected); assertThat(m.entrySet()).containsExactlyElementsIn(expected.entrySet()).inOrder(); } public void testMapSplitter_trimmedKeyValue() { Map<String, String> m = COMMA_SPLITTER .withKeyValueSeparator(Splitter.on(':').trimResults()) .split("boy : tom , girl: tina , cat : kitty , dog: tommy "); ImmutableMap<String, String> expected = ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy"); assertThat(m).isEqualTo(expected); assertThat(m.entrySet()).containsExactlyElementsIn(expected.entrySet()).inOrder(); } public void testMapSplitter_notTrimmed() { Map<String, String> m = COMMA_SPLITTER .withKeyValueSeparator(":") .split(" boy:tom , girl: tina , cat :kitty , dog: tommy "); ImmutableMap<String, String> expected = ImmutableMap.of(" boy", "tom ", " girl", " tina ", " cat ", "kitty ", " dog", " tommy "); assertThat(m).isEqualTo(expected); assertThat(m.entrySet()).containsExactlyElementsIn(expected.entrySet()).inOrder(); } public void testMapSplitter_characterSeparator() { // try different delimiters. Map<String, String> m = Splitter.on(",").withKeyValueSeparator(':').split("boy:tom,girl:tina,cat:kitty,dog:tommy"); ImmutableMap<String, String> expected = ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy"); assertThat(m).isEqualTo(expected); assertThat(m.entrySet()).containsExactlyElementsIn(expected.entrySet()).inOrder(); } public void testMapSplitter_multiCharacterSeparator() { // try different delimiters. Map<String, String> m = Splitter.on(",") .withKeyValueSeparator(":^&") .split("boy:^&tom,girl:^&tina,cat:^&kitty,dog:^&tommy"); ImmutableMap<String, String> expected = ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy"); assertThat(m).isEqualTo(expected); assertThat(m.entrySet()).containsExactlyElementsIn(expected.entrySet()).inOrder(); } public void testMapSplitter_emptySeparator() { assertThrows(IllegalArgumentException.class, () -> COMMA_SPLITTER.withKeyValueSeparator("")); } public void testMapSplitter_malformedEntry() { assertThrows( IllegalArgumentException.class, () -> COMMA_SPLITTER.withKeyValueSeparator("=").split("a=1,b,c=2")); } /** * Testing the behavior in https://github.com/google/guava/issues/1900 - this behavior may want to * be changed? */ public void testMapSplitter_extraValueDelimiter() { assertThrows( IllegalArgumentException.class, () -> COMMA_SPLITTER.withKeyValueSeparator("=").split("a=1,c=2=")); } public void testMapSplitter_orderedResults() { Map<String, String> m = COMMA_SPLITTER.withKeyValueSeparator(":").split("boy:tom,girl:tina,cat:kitty,dog:tommy"); assertThat(m.keySet()).containsExactly("boy", "girl", "cat", "dog").inOrder(); assertThat(m) .isEqualTo(ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy")); // try in a different order m = COMMA_SPLITTER.withKeyValueSeparator(":").split("girl:tina,boy:tom,dog:tommy,cat:kitty"); assertThat(m.keySet()).containsExactly("girl", "boy", "dog", "cat").inOrder(); assertThat(m) .isEqualTo(ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy")); } public void testMapSplitter_duplicateKeys() { assertThrows( IllegalArgumentException.class, () -> COMMA_SPLITTER.withKeyValueSeparator(":").split("a:1,b:2,a:3")); } public void testMapSplitter_varyingTrimLevels() { MapSplitter splitter = COMMA_SPLITTER.trimResults().withKeyValueSeparator(Splitter.on("->")); Map<String, String> split = splitter.split(" x -> y, z-> a "); assertThat(split).containsEntry("x ", " y"); assertThat(split).containsEntry("z", " a"); } }
java
github
https://github.com/google/guava
android/guava-tests/test/com/google/common/base/SplitterTest.java
from __future__ import print_function, division import decimal import fractions import math import re as regex from collections import defaultdict from .containers import Tuple from .sympify import converter, sympify, _sympify, SympifyError from .singleton import S, Singleton from .expr import Expr, AtomicExpr from .decorators import _sympifyit from .cache import cacheit, clear_cache from .logic import fuzzy_not from sympy.core.compatibility import ( as_int, integer_types, long, string_types, with_metaclass, HAS_GMPY, SYMPY_INTS) import mpmath import mpmath.libmp as mlib from mpmath.libmp import mpf_pow, mpf_pi, mpf_e, phi_fixed from mpmath.ctx_mp import mpnumeric from mpmath.libmp.libmpf import ( finf as _mpf_inf, fninf as _mpf_ninf, fnan as _mpf_nan, fzero as _mpf_zero, _normalize as mpf_normalize, prec_to_dps) from sympy.utilities.misc import debug rnd = mlib.round_nearest _LOG2 = math.log(2) def comp(z1, z2, tol=None): """Return a bool indicating whether the error between z1 and z2 is <= tol. If ``tol`` is None then True will be returned if there is a significant difference between the numbers: ``abs(z1 - z2)*10**p <= 1/2`` where ``p`` is the lower of the precisions of the values. A comparison of strings will be made if ``z1`` is a Number and a) ``z2`` is a string or b) ``tol`` is '' and ``z2`` is a Number. When ``tol`` is a nonzero value, if z2 is non-zero and ``|z1| > 1`` the error is normalized by ``|z1|``, so if you want to see if the absolute error between ``z1`` and ``z2`` is <= ``tol`` then call this as ``comp(z1 - z2, 0, tol)``. """ if type(z2) is str: if not isinstance(z1, Number): raise ValueError('when z2 is a str z1 must be a Number') return str(z1) == z2 if not z1: z1, z2 = z2, z1 if not z1: return True if not tol: if tol is None: if type(z2) is str and getattr(z1, 'is_Number', False): return str(z1) == z2 a, b = Float(z1), Float(z2) return int(abs(a - b)*10**prec_to_dps( min(a._prec, b._prec)))*2 <= 1 elif all(getattr(i, 'is_Number', False) for i in (z1, z2)): return z1._prec == z2._prec and str(z1) == str(z2) raise ValueError('exact comparison requires two Numbers') diff = abs(z1 - z2) az1 = abs(z1) if z2 and az1 > 1: return diff/az1 <= tol else: return diff <= tol def mpf_norm(mpf, prec): """Return the mpf tuple normalized appropriately for the indicated precision after doing a check to see if zero should be returned or not when the mantissa is 0. ``mpf_normlize`` always assumes that this is zero, but it may not be since the mantissa for mpf's values "+inf", "-inf" and "nan" have a mantissa of zero, too. Note: this is not intended to validate a given mpf tuple, so sending mpf tuples that were not created by mpmath may produce bad results. This is only a wrapper to ``mpf_normalize`` which provides the check for non- zero mpfs that have a 0 for the mantissa. """ sign, man, expt, bc = mpf if not man: # hack for mpf_normalize which does not do this; # it assumes that if man is zero the result is 0 # (see issue 6639) if not bc: return _mpf_zero else: # don't change anything; this should already # be a well formed mpf tuple return mpf rv = mpf_normalize(sign, man, expt, bc, prec, rnd) return rv # TODO: we should use the warnings module _errdict = {"divide": False} def seterr(divide=False): """ Should sympy raise an exception on 0/0 or return a nan? divide == True .... raise an exception divide == False ... return nan """ if _errdict["divide"] != divide: clear_cache() _errdict["divide"] = divide def _decimal_to_Rational_prec(dec): """Convert an ordinary decimal instance to a Rational.""" if not dec.is_finite(): raise TypeError("dec must be finite, got %s." % dec) s, d, e = dec.as_tuple() prec = len(d) if e >= 0: # it's an integer rv = Integer(int(dec)) else: s = (-1)**s d = sum([di*10**i for i, di in enumerate(reversed(d))]) rv = Rational(s*d, 10**-e) return rv, prec def _literal_float(f): """Return True if n can be interpreted as a floating point number.""" pat = r"[-+]?((\d*\.\d+)|(\d+\.?))(eE[-+]?\d+)?" return bool(regex.match(pat, f)) # (a,b) -> gcd(a,b) _gcdcache = {} # TODO caching with decorator, but not to degrade performance def igcd(*args): """Computes positive integer greatest common divisor. The algorithm is based on the well known Euclid's algorithm. To improve speed, igcd() has its own caching mechanism implemented. Examples ======== >>> from sympy.core.numbers import igcd >>> igcd(2, 4) 2 >>> igcd(5, 10, 15) 5 """ a = args[0] for b in args[1:]: try: a = _gcdcache[(a, b)] except KeyError: a, b = as_int(a), as_int(b) if a and b: if b < 0: b = -b while b: a, b = b, a % b else: a = abs(a or b) _gcdcache[(a, b)] = a if a == 1 or b == 1: return 1 return a def ilcm(*args): """Computes integer least common multiple. Examples ======== >>> from sympy.core.numbers import ilcm >>> ilcm(5, 10) 10 >>> ilcm(7, 3) 21 >>> ilcm(5, 10, 15) 30 """ if 0 in args: return 0 a = args[0] for b in args[1:]: a = a*b // igcd(a, b) return a def igcdex(a, b): """Returns x, y, g such that g = x*a + y*b = gcd(a, b). >>> from sympy.core.numbers import igcdex >>> igcdex(2, 3) (-1, 1, 1) >>> igcdex(10, 12) (-1, 1, 2) >>> x, y, g = igcdex(100, 2004) >>> x, y, g (-20, 1, 4) >>> x*100 + y*2004 4 """ if (not a) and (not b): return (0, 1, 0) if not a: return (0, b//abs(b), abs(b)) if not b: return (a//abs(a), 0, abs(a)) if a < 0: a, x_sign = -a, -1 else: x_sign = 1 if b < 0: b, y_sign = -b, -1 else: y_sign = 1 x, y, r, s = 1, 0, 0, 1 while b: (c, q) = (a % b, a // b) (a, b, r, s, x, y) = (b, c, x - q*r, y - q*s, r, s) return (x*x_sign, y*y_sign, a) class Number(AtomicExpr): """ Represents any kind of number in sympy. Floating point numbers are represented by the Float class. Integer numbers (of any size), together with rational numbers (again, there is no limit on their size) are represented by the Rational class. If you want to represent, for example, ``1+sqrt(2)``, then you need to do:: Rational(1) + sqrt(Rational(2)) """ is_commutative = True is_number = True is_Number = True __slots__ = [] # Used to make max(x._prec, y._prec) return x._prec when only x is a float _prec = -1 def __new__(cls, *obj): if len(obj) == 1: obj = obj[0] if isinstance(obj, Number): return obj if isinstance(obj, SYMPY_INTS): return Integer(obj) if isinstance(obj, tuple) and len(obj) == 2: return Rational(*obj) if isinstance(obj, (float, mpmath.mpf, decimal.Decimal)): return Float(obj) if isinstance(obj, string_types): val = sympify(obj) if isinstance(val, Number): return val else: raise ValueError('String "%s" does not denote a Number' % obj) if isinstance(obj, Number): return obj msg = "expected str|int|long|float|Decimal|Number object but got %r" raise TypeError(msg % type(obj).__name__) def __divmod__(self, other): from .containers import Tuple from sympy.functions.elementary.complexes import sign try: other = Number(other) except TypeError: msg = "unsupported operand type(s) for divmod(): '%s' and '%s'" raise TypeError(msg % (type(self).__name__, type(other).__name__)) if not other: raise ZeroDivisionError('modulo by zero') if self.is_Integer and other.is_Integer: return Tuple(*divmod(self.p, other.p)) else: rat = self/other w = sign(rat)*int(abs(rat)) # = rat.floor() r = self - other*w return Tuple(w, r) def __rdivmod__(self, other): try: other = Number(other) except TypeError: msg = "unsupported operand type(s) for divmod(): '%s' and '%s'" raise TypeError(msg % (type(other).__name__, type(self).__name__)) return divmod(other, self) def __round__(self, *args): return round(float(self), *args) def _as_mpf_val(self, prec): """Evaluation of mpf tuple accurate to at least prec bits.""" raise NotImplementedError('%s needs ._as_mpf_val() method' % (self.__class__.__name__)) def _eval_evalf(self, prec): return Float._new(self._as_mpf_val(prec), prec) def _as_mpf_op(self, prec): prec = max(prec, self._prec) return self._as_mpf_val(prec), prec def __float__(self): return mlib.to_float(self._as_mpf_val(53)) def _eval_conjugate(self): return self def _eval_order(self, *symbols): from sympy import Order # Order(5, x, y) -> Order(1,x,y) return Order(S.One, *symbols) def _eval_subs(self, old, new): if old == -self: return -new return self # there is no other possibility def _eval_is_finite(self): return True @classmethod def class_key(cls): return 1, 0, 'Number' @cacheit def sort_key(self, order=None): return self.class_key(), (0, ()), (), self @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Number): if other is S.NaN: return S.NaN elif other is S.Infinity: return S.Infinity elif other is S.NegativeInfinity: return S.NegativeInfinity return AtomicExpr.__add__(self, other) @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Number): if other is S.NaN: return S.NaN elif other is S.Infinity: return S.NegativeInfinity elif other is S.NegativeInfinity: return S.Infinity return AtomicExpr.__sub__(self, other) @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Number): if other is S.NaN: return S.NaN elif other is S.Infinity: if self.is_zero: return S.NaN elif self.is_positive: return S.Infinity else: return S.NegativeInfinity elif other is S.NegativeInfinity: if self.is_zero: return S.NaN elif self.is_positive: return S.NegativeInfinity else: return S.Infinity elif isinstance(other, Tuple): return NotImplemented return AtomicExpr.__mul__(self, other) @_sympifyit('other', NotImplemented) def __div__(self, other): if isinstance(other, Number): if other is S.NaN: return S.NaN elif other is S.Infinity or other is S.NegativeInfinity: return S.Zero return AtomicExpr.__div__(self, other) __truediv__ = __div__ def __eq__(self, other): raise NotImplementedError('%s needs .__eq__() method' % (self.__class__.__name__)) def __ne__(self, other): raise NotImplementedError('%s needs .__ne__() method' % (self.__class__.__name__)) def __lt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s < %s" % (self, other)) raise NotImplementedError('%s needs .__lt__() method' % (self.__class__.__name__)) def __le__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s <= %s" % (self, other)) raise NotImplementedError('%s needs .__le__() method' % (self.__class__.__name__)) def __gt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s > %s" % (self, other)) return _sympify(other).__lt__(self) def __ge__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s >= %s" % (self, other)) return _sympify(other).__le__(self) def __hash__(self): return super(Number, self).__hash__() def is_constant(self, *wrt, **flags): return True def as_coeff_mul(self, *deps, **kwargs): # a -> c*t if self.is_Rational or not kwargs.pop('rational', True): return self, tuple() elif self.is_negative: return S.NegativeOne, (-self,) return S.One, (self,) def as_coeff_add(self, *deps): # a -> c + t if self.is_Rational: return self, tuple() return S.Zero, (self,) def as_coeff_Mul(self, rational=False): """Efficiently extract the coefficient of a product. """ if rational and not self.is_Rational: return S.One, self return self, S.One def as_coeff_Add(self): """Efficiently extract the coefficient of a summation. """ return self, S.Zero def gcd(self, other): """Compute GCD of `self` and `other`. """ from sympy.polys import gcd return gcd(self, other) def lcm(self, other): """Compute LCM of `self` and `other`. """ from sympy.polys import lcm return lcm(self, other) def cofactors(self, other): """Compute GCD and cofactors of `self` and `other`. """ from sympy.polys import cofactors return cofactors(self, other) class Float(Number): """Represent a floating-point number of arbitrary precision. Examples ======== >>> from sympy import Float >>> Float(3.5) 3.50000000000000 >>> Float(3) 3.00000000000000 Creating Floats from strings (and Python ``int`` and ``long`` types) will give a minimum precision of 15 digits, but the precision will automatically increase to capture all digits entered. >>> Float(1) 1.00000000000000 >>> Float(10**20) 100000000000000000000. >>> Float('1e20') 100000000000000000000. However, *floating-point* numbers (Python ``float`` types) retain only 15 digits of precision: >>> Float(1e20) 1.00000000000000e+20 >>> Float(1.23456789123456789) 1.23456789123457 It may be preferable to enter high-precision decimal numbers as strings: Float('1.23456789123456789') 1.23456789123456789 The desired number of digits can also be specified: >>> Float('1e-3', 3) 0.00100 >>> Float(100, 4) 100.0 Float can automatically count significant figures if a null string is sent for the precision; space are also allowed in the string. (Auto- counting is only allowed for strings, ints and longs). >>> Float('123 456 789 . 123 456', '') 123456789.123456 >>> Float('12e-3', '') 0.012 >>> Float(3, '') 3. If a number is written in scientific notation, only the digits before the exponent are considered significant if a decimal appears, otherwise the "e" signifies only how to move the decimal: >>> Float('60.e2', '') # 2 digits significant 6.0e+3 >>> Float('60e2', '') # 4 digits significant 6000. >>> Float('600e-2', '') # 3 digits significant 6.00 Notes ===== Floats are inexact by their nature unless their value is a binary-exact value. >>> approx, exact = Float(.1, 1), Float(.125, 1) For calculation purposes, evalf needs to be able to change the precision but this will not increase the accuracy of the inexact value. The following is the most accurate 5-digit approximation of a value of 0.1 that had only 1 digit of precision: >>> approx.evalf(5) 0.099609 By contrast, 0.125 is exact in binary (as it is in base 10) and so it can be passed to Float or evalf to obtain an arbitrary precision with matching accuracy: >>> Float(exact, 5) 0.12500 >>> exact.evalf(20) 0.12500000000000000000 Trying to make a high-precision Float from a float is not disallowed, but one must keep in mind that the *underlying float* (not the apparent decimal value) is being obtained with high precision. For example, 0.3 does not have a finite binary representation. The closest rational is the fraction 5404319552844595/2**54. So if you try to obtain a Float of 0.3 to 20 digits of precision you will not see the same thing as 0.3 followed by 19 zeros: >>> Float(0.3, 20) 0.29999999999999998890 If you want a 20-digit value of the decimal 0.3 (not the floating point approximation of 0.3) you should send the 0.3 as a string. The underlying representation is still binary but a higher precision than Python's float is used: >>> Float('0.3', 20) 0.30000000000000000000 Although you can increase the precision of an existing Float using Float it will not increase the accuracy -- the underlying value is not changed: >>> def show(f): # binary rep of Float ... from sympy import Mul, Pow ... s, m, e, b = f._mpf_ ... v = Mul(int(m), Pow(2, int(e), evaluate=False), evaluate=False) ... print('%s at prec=%s' % (v, f._prec)) ... >>> t = Float('0.3', 3) >>> show(t) 4915/2**14 at prec=13 >>> show(Float(t, 20)) # higher prec, not higher accuracy 4915/2**14 at prec=70 >>> show(Float(t, 2)) # lower prec 307/2**10 at prec=10 The same thing happens when evalf is used on a Float: >>> show(t.evalf(20)) 4915/2**14 at prec=70 >>> show(t.evalf(2)) 307/2**10 at prec=10 Finally, Floats can be instantiated with an mpf tuple (n, c, p) to produce the number (-1)**n*c*2**p: >>> n, c, p = 1, 5, 0 >>> (-1)**n*c*2**p -5 >>> Float((1, 5, 0)) -5.00000000000000 An actual mpf tuple also contains the number of bits in c as the last element of the tuple: >>> _._mpf_ (1, 5, 0, 3) This is not needed for instantiation and is not the same thing as the precision. The mpf tuple and the precision are two separate quantities that Float tracks. """ __slots__ = ['_mpf_', '_prec'] # A Float represents many real numbers, # both rational and irrational. is_rational = None is_irrational = None is_number = True is_real = True is_Float = True def __new__(cls, num, prec=None): if isinstance(num, string_types): num = num.replace(' ', '') if num.startswith('.') and len(num) > 1: num = '0' + num elif num.startswith('-.') and len(num) > 2: num = '-0.' + num[2:] elif isinstance(num, float) and num == 0: num = '0' elif isinstance(num, (SYMPY_INTS, Integer)): num = str(num) # faster than mlib.from_int elif isinstance(num, mpmath.mpf): num = num._mpf_ if prec is None: dps = 15 if isinstance(num, Float): return num if isinstance(num, string_types) and _literal_float(num): try: Num = decimal.Decimal(num) except decimal.InvalidOperation: pass else: isint = '.' not in num num, dps = _decimal_to_Rational_prec(Num) if num.is_Integer and isint: dps = max(dps, len(str(num).lstrip('-'))) dps = max(15, dps) elif prec == '': if not isinstance(num, string_types): raise ValueError('The null string can only be used when ' 'the number to Float is passed as a string or an integer.') ok = None if _literal_float(num): try: Num = decimal.Decimal(num) except decimal.InvalidOperation: pass else: isint = '.' not in num num, dps = _decimal_to_Rational_prec(Num) if num.is_Integer and isint: dps = max(dps, len(str(num).lstrip('-'))) ok = True if ok is None: raise ValueError('string-float not recognized: %s' % num) else: dps = prec prec = mlib.libmpf.dps_to_prec(dps) if isinstance(num, float): _mpf_ = mlib.from_float(num, prec, rnd) elif isinstance(num, str): _mpf_ = mlib.from_str(num, prec, rnd) elif isinstance(num, decimal.Decimal): if num.is_finite(): _mpf_ = mlib.from_str(str(num), prec, rnd) elif num.is_nan(): _mpf_ = _mpf_nan elif num.is_infinite(): if num > 0: _mpf_ = _mpf_inf else: _mpf_ = _mpf_ninf else: raise ValueError("unexpected decimal value %s" % str(num)) elif isinstance(num, Rational): _mpf_ = mlib.from_rational(num.p, num.q, prec, rnd) elif isinstance(num, tuple) and len(num) in (3, 4): if type(num[1]) is str: # it's a hexadecimal (coming from a pickled object) # assume that it is in standard form num = list(num) num[1] = long(num[1], 16) _mpf_ = tuple(num) else: if not num[1] and len(num) == 4: # handle normalization hack return Float._new(num, prec) else: _mpf_ = mpmath.mpf( S.NegativeOne**num[0]*num[1]*2**num[2])._mpf_ elif isinstance(num, Float): _mpf_ = num._mpf_ if prec < num._prec: _mpf_ = mpf_norm(_mpf_, prec) else: _mpf_ = mpmath.mpf(num)._mpf_ # special cases if _mpf_ == _mpf_zero: pass # we want a Float elif _mpf_ == _mpf_nan: return S.NaN obj = Expr.__new__(cls) obj._mpf_ = _mpf_ obj._prec = prec return obj @classmethod def _new(cls, _mpf_, _prec): # special cases if _mpf_ == _mpf_zero: return S.Zero # XXX this is different from Float which gives 0.0 elif _mpf_ == _mpf_nan: return S.NaN obj = Expr.__new__(cls) obj._mpf_ = mpf_norm(_mpf_, _prec) obj._prec = _prec return obj # mpz can't be pickled def __getnewargs__(self): return (mlib.to_pickable(self._mpf_),) def __getstate__(self): return {'_prec': self._prec} def _hashable_content(self): return (self._mpf_, self._prec) def floor(self): return Integer(int(mlib.to_int( mlib.mpf_floor(self._mpf_, self._prec)))) def ceiling(self): return Integer(int(mlib.to_int( mlib.mpf_ceil(self._mpf_, self._prec)))) @property def num(self): return mpmath.mpf(self._mpf_) def _as_mpf_val(self, prec): rv = mpf_norm(self._mpf_, prec) if rv != self._mpf_ and self._prec == prec: debug(self._mpf_, rv) return rv def _as_mpf_op(self, prec): return self._mpf_, max(prec, self._prec) def _eval_is_finite(self): if self._mpf_ in (_mpf_inf, _mpf_ninf): return False return True def _eval_is_infinite(self): if self._mpf_ in (_mpf_inf, _mpf_ninf): return True return False def _eval_is_integer(self): return self._mpf_ == _mpf_zero def _eval_is_negative(self): if self._mpf_ == _mpf_ninf: return True if self._mpf_ == _mpf_inf: return False return self.num < 0 def _eval_is_positive(self): if self._mpf_ == _mpf_inf: return True if self._mpf_ == _mpf_ninf: return False return self.num > 0 def _eval_is_zero(self): return self._mpf_ == _mpf_zero def __nonzero__(self): return self._mpf_ != _mpf_zero __bool__ = __nonzero__ def __neg__(self): return Float._new(mlib.mpf_neg(self._mpf_), self._prec) @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Number): rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_add(self._mpf_, rhs, prec, rnd), prec) return Number.__add__(self, other) @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Number): rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_sub(self._mpf_, rhs, prec, rnd), prec) return Number.__sub__(self, other) @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Number): rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_mul(self._mpf_, rhs, prec, rnd), prec) return Number.__mul__(self, other) @_sympifyit('other', NotImplemented) def __div__(self, other): if isinstance(other, Number) and other != 0: rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_div(self._mpf_, rhs, prec, rnd), prec) return Number.__div__(self, other) __truediv__ = __div__ @_sympifyit('other', NotImplemented) def __mod__(self, other): if isinstance(other, Rational) and other.q != 1: # calculate mod with Rationals, *then* round the result return Float(Rational.__mod__(Rational(self), other), prec_to_dps(self._prec)) if isinstance(other, Float): r = self/other if r == int(r): prec = max([prec_to_dps(i) for i in (self._prec, other._prec)]) return Float(0, prec) if isinstance(other, Number): rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_mod(self._mpf_, rhs, prec, rnd), prec) return Number.__mod__(self, other) @_sympifyit('other', NotImplemented) def __rmod__(self, other): if isinstance(other, Float): return other.__mod__(self) if isinstance(other, Number): rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_mod(rhs, self._mpf_, prec, rnd), prec) return Number.__rmod__(self, other) def _eval_power(self, expt): """ expt is symbolic object but not equal to 0, 1 (-p)**r -> exp(r*log(-p)) -> exp(r*(log(p) + I*Pi)) -> -> p**r*(sin(Pi*r) + cos(Pi*r)*I) """ if self == 0: if expt.is_positive: return S.Zero if expt.is_negative: return Float('inf') if isinstance(expt, Number): if isinstance(expt, Integer): prec = self._prec return Float._new( mlib.mpf_pow_int(self._mpf_, expt.p, prec, rnd), prec) elif isinstance(expt, Rational) and \ expt.p == 1 and expt.q % 2 and self.is_negative: return Pow(S.NegativeOne, expt, evaluate=False)*( -self)._eval_power(expt) expt, prec = expt._as_mpf_op(self._prec) mpfself = self._mpf_ try: y = mpf_pow(mpfself, expt, prec, rnd) return Float._new(y, prec) except mlib.ComplexResult: re, im = mlib.mpc_pow( (mpfself, _mpf_zero), (expt, _mpf_zero), prec, rnd) return Float._new(re, prec) + \ Float._new(im, prec)*S.ImaginaryUnit def __abs__(self): return Float._new(mlib.mpf_abs(self._mpf_), self._prec) def __int__(self): if self._mpf_ == _mpf_zero: return 0 return int(mlib.to_int(self._mpf_)) # uses round_fast = round_down __long__ = __int__ def __eq__(self, other): if isinstance(other, float): # coerce to Float at same precision o = Float(other) try: ompf = o._as_mpf_val(self._prec) except ValueError: return False return bool(mlib.mpf_eq(self._mpf_, ompf)) try: other = _sympify(other) except SympifyError: return False # sympy != other --> not == if isinstance(other, NumberSymbol): if other.is_irrational: return False return other.__eq__(self) if isinstance(other, Float): return bool(mlib.mpf_eq(self._mpf_, other._mpf_)) if isinstance(other, Number): # numbers should compare at the same precision; # all _as_mpf_val routines should be sure to abide # by the request to change the prec if necessary; if # they don't, the equality test will fail since it compares # the mpf tuples ompf = other._as_mpf_val(self._prec) return bool(mlib.mpf_eq(self._mpf_, ompf)) return False # Float != non-Number def __ne__(self, other): return not self.__eq__(other) def __gt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s > %s" % (self, other)) if isinstance(other, NumberSymbol): return other.__le__(self) if other.is_comparable: other = other.evalf() if isinstance(other, Number) and other is not S.NaN: return _sympify(bool( mlib.mpf_gt(self._mpf_, other._as_mpf_val(self._prec)))) return Expr.__gt__(self, other) def __ge__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s >= %s" % (self, other)) if isinstance(other, NumberSymbol): return other.__lt__(self) if other.is_comparable: other = other.evalf() if isinstance(other, Number) and other is not S.NaN: return _sympify(bool( mlib.mpf_ge(self._mpf_, other._as_mpf_val(self._prec)))) return Expr.__ge__(self, other) def __lt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s < %s" % (self, other)) if isinstance(other, NumberSymbol): return other.__ge__(self) if other.is_real and other.is_number: other = other.evalf() if isinstance(other, Number) and other is not S.NaN: return _sympify(bool( mlib.mpf_lt(self._mpf_, other._as_mpf_val(self._prec)))) return Expr.__lt__(self, other) def __le__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s <= %s" % (self, other)) if isinstance(other, NumberSymbol): return other.__gt__(self) if other.is_real and other.is_number: other = other.evalf() if isinstance(other, Number) and other is not S.NaN: return _sympify(bool( mlib.mpf_le(self._mpf_, other._as_mpf_val(self._prec)))) return Expr.__le__(self, other) def __hash__(self): return super(Float, self).__hash__() def epsilon_eq(self, other, epsilon="1e-15"): return abs(self - other) < Float(epsilon) def _sage_(self): import sage.all as sage return sage.RealNumber(str(self)) def __format__(self, format_spec): return format(decimal.Decimal(str(self)), format_spec) # Add sympify converters converter[float] = converter[decimal.Decimal] = Float # this is here to work nicely in Sage RealNumber = Float class Rational(Number): """Represents integers and rational numbers (p/q) of any size. Examples ======== >>> from sympy import Rational, nsimplify, S, pi >>> Rational(3) 3 >>> Rational(1, 2) 1/2 Rational is unprejudiced in accepting input. If a float is passed, the underlying value of the binary representation will be returned: >>> Rational(.5) 1/2 >>> Rational(.2) 3602879701896397/18014398509481984 If the simpler representation of the float is desired then consider limiting the denominator to the desired value or convert the float to a string (which is roughly equivalent to limiting the denominator to 10**12): >>> Rational(str(.2)) 1/5 >>> Rational(.2).limit_denominator(10**12) 1/5 An arbitrarily precise Rational is obtained when a string literal is passed: >>> Rational("1.23") 123/100 >>> Rational('1e-2') 1/100 >>> Rational(".1") 1/10 >>> Rational('1e-2/3.2') 1/320 The conversion of other types of strings can be handled by the sympify() function, and conversion of floats to expressions or simple fractions can be handled with nsimplify: >>> S('.[3]') # repeating digits in brackets 1/3 >>> S('3**2/10') # general expressions 9/10 >>> nsimplify(.3) # numbers that have a simple form 3/10 But if the input does not reduce to a literal Rational, an error will be raised: >>> Rational(pi) Traceback (most recent call last): ... TypeError: invalid input: pi Low-level --------- Access numerator and denominator as .p and .q: >>> r = Rational(3, 4) >>> r 3/4 >>> r.p 3 >>> r.q 4 Note that p and q return integers (not SymPy Integers) so some care is needed when using them in expressions: >>> r.p/r.q 0.75 See Also ======== sympify, sympy.simplify.simplify.nsimplify """ is_real = True is_integer = False is_rational = True is_number = True __slots__ = ['p', 'q'] is_Rational = True @cacheit def __new__(cls, p, q=None): if q is None: if isinstance(p, Rational): return p if isinstance(p, string_types): p = p.replace(' ', '') try: # we might have a Float neg_pow, digits, expt = decimal.Decimal(p).as_tuple() p = [1, -1][neg_pow]*int("".join(str(x) for x in digits)) if expt > 0: # TODO: this branch needs a test return Rational(p*Pow(10, expt), 1) return Rational(p, Pow(10, -expt)) except decimal.InvalidOperation: f = regex.match('^([-+]?[0-9]+)/([0-9]+)$', p) if f: n, d = f.groups() return Rational(int(n), int(d)) elif p.count('/') == 1: p, q = p.split('/') return Rational(Rational(p), Rational(q)) else: pass # error will raise below else: try: if isinstance(p, fractions.Fraction): return Rational(p.numerator, p.denominator) except NameError: pass # error will raise below if isinstance(p, (float, Float)): return Rational(*float(p).as_integer_ratio()) if not isinstance(p, SYMPY_INTS + (Rational,)): raise TypeError('invalid input: %s' % p) q = S.One else: p = Rational(p) q = Rational(q) if isinstance(q, Rational): p *= q.q q = q.p if isinstance(p, Rational): q *= p.q p = p.p # p and q are now integers if q == 0: if p == 0: if _errdict["divide"]: raise ValueError("Indeterminate 0/0") else: return S.NaN if p < 0: return S.NegativeInfinity return S.Infinity if q < 0: q = -q p = -p n = igcd(abs(p), q) if n > 1: p //= n q //= n if q == 1: return Integer(p) if p == 1 and q == 2: return S.Half obj = Expr.__new__(cls) obj.p = p obj.q = q return obj def limit_denominator(self, max_denominator=1000000): """Closest Rational to self with denominator at most max_denominator. >>> from sympy import Rational >>> Rational('3.141592653589793').limit_denominator(10) 22/7 >>> Rational('3.141592653589793').limit_denominator(100) 311/99 """ # Algorithm notes: For any real number x, define a *best upper # approximation* to x to be a rational number p/q such that: # # (1) p/q >= x, and # (2) if p/q > r/s >= x then s > q, for any rational r/s. # # Define *best lower approximation* similarly. Then it can be # proved that a rational number is a best upper or lower # approximation to x if, and only if, it is a convergent or # semiconvergent of the (unique shortest) continued fraction # associated to x. # # To find a best rational approximation with denominator <= M, # we find the best upper and lower approximations with # denominator <= M and take whichever of these is closer to x. # In the event of a tie, the bound with smaller denominator is # chosen. If both denominators are equal (which can happen # only when max_denominator == 1 and self is midway between # two integers) the lower bound---i.e., the floor of self, is # taken. if max_denominator < 1: raise ValueError("max_denominator should be at least 1") if self.q <= max_denominator: return self p0, q0, p1, q1 = 0, 1, 1, 0 n, d = self.p, self.q while True: a = n//d q2 = q0 + a*q1 if q2 > max_denominator: break p0, q0, p1, q1 = p1, q1, p0 + a*p1, q2 n, d = d, n - a*d k = (max_denominator - q0)//q1 bound1 = Rational(p0 + k*p1, q0 + k*q1) bound2 = Rational(p1, q1) if abs(bound2 - self) <= abs(bound1 - self): return bound2 else: return bound1 def __getnewargs__(self): return (self.p, self.q) def _hashable_content(self): return (self.p, self.q) def _eval_is_positive(self): return self.p > 0 def _eval_is_zero(self): return self.p == 0 def __neg__(self): return Rational(-self.p, self.q) @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Rational): return Rational(self.p*other.q + self.q*other.p, self.q*other.q) elif isinstance(other, Float): return other + self else: return Number.__add__(self, other) @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Rational): return Rational(self.p*other.q - self.q*other.p, self.q*other.q) elif isinstance(other, Float): return -other + self else: return Number.__sub__(self, other) @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Rational): return Rational(self.p*other.p, self.q*other.q) elif isinstance(other, Float): return other*self else: return Number.__mul__(self, other) @_sympifyit('other', NotImplemented) def __div__(self, other): if isinstance(other, Rational): if self.p and other.p == S.Zero: return S.ComplexInfinity else: return Rational(self.p*other.q, self.q*other.p) elif isinstance(other, Float): return self*(1/other) else: return Number.__div__(self, other) __truediv__ = __div__ @_sympifyit('other', NotImplemented) def __mod__(self, other): if isinstance(other, Rational): n = (self.p*other.q) // (other.p*self.q) return Rational(self.p*other.q - n*other.p*self.q, self.q*other.q) if isinstance(other, Float): # calculate mod with Rationals, *then* round the answer return Float(self.__mod__(Rational(other)), prec_to_dps(other._prec)) return Number.__mod__(self, other) @_sympifyit('other', NotImplemented) def __rmod__(self, other): if isinstance(other, Rational): return Rational.__mod__(other, self) return Number.__rmod__(self, other) def _eval_power(self, expt): if isinstance(expt, Number): if isinstance(expt, Float): return self._eval_evalf(expt._prec)**expt if expt.is_negative: # (3/4)**-2 -> (4/3)**2 ne = -expt if (ne is S.One): return Rational(self.q, self.p) if self.is_negative: if expt.q != 1: return -(S.NegativeOne)**((expt.p % expt.q) / S(expt.q))*Rational(self.q, -self.p)**ne else: return S.NegativeOne**ne*Rational(self.q, -self.p)**ne else: return Rational(self.q, self.p)**ne if expt is S.Infinity: # -oo already caught by test for negative if self.p > self.q: # (3/2)**oo -> oo return S.Infinity if self.p < -self.q: # (-3/2)**oo -> oo + I*oo return S.Infinity + S.Infinity*S.ImaginaryUnit return S.Zero if isinstance(expt, Integer): # (4/3)**2 -> 4**2 / 3**2 return Rational(self.p**expt.p, self.q**expt.p) if isinstance(expt, Rational): if self.p != 1: # (4/3)**(5/6) -> 4**(5/6)*3**(-5/6) return Integer(self.p)**expt*Integer(self.q)**(-expt) # as the above caught negative self.p, now self is positive return Integer(self.q)**Rational( expt.p*(expt.q - 1), expt.q) / \ Integer(self.q)**Integer(expt.p) if self.is_negative and expt.is_even: return (-self)**expt return def _as_mpf_val(self, prec): return mlib.from_rational(self.p, self.q, prec, rnd) def _mpmath_(self, prec, rnd): return mpmath.make_mpf(mlib.from_rational(self.p, self.q, prec, rnd)) def __abs__(self): return Rational(abs(self.p), self.q) def __int__(self): p, q = self.p, self.q if p < 0: return -(-p//q) return p//q __long__ = __int__ def __eq__(self, other): try: other = _sympify(other) except SympifyError: return False # sympy != other --> not == if isinstance(other, NumberSymbol): if other.is_irrational: return False return other.__eq__(self) if isinstance(other, Number): if isinstance(other, Rational): # a Rational is always in reduced form so will never be 2/4 # so we can just check equivalence of args return self.p == other.p and self.q == other.q if isinstance(other, Float): return mlib.mpf_eq(self._as_mpf_val(other._prec), other._mpf_) return False def __ne__(self, other): return not self.__eq__(other) def __gt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s > %s" % (self, other)) if isinstance(other, NumberSymbol): return other.__le__(self) expr = self if isinstance(other, Number): if isinstance(other, Rational): return _sympify(bool(self.p*other.q > self.q*other.p)) if isinstance(other, Float): return _sympify(bool(mlib.mpf_gt( self._as_mpf_val(other._prec), other._mpf_))) elif other.is_number and other.is_real: expr, other = Integer(self.p), self.q*other return Expr.__gt__(expr, other) def __ge__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s >= %s" % (self, other)) if isinstance(other, NumberSymbol): return other.__lt__(self) expr = self if isinstance(other, Number): if isinstance(other, Rational): return _sympify(bool(self.p*other.q >= self.q*other.p)) if isinstance(other, Float): return _sympify(bool(mlib.mpf_ge( self._as_mpf_val(other._prec), other._mpf_))) elif other.is_number and other.is_real: expr, other = Integer(self.p), self.q*other return Expr.__ge__(expr, other) def __lt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s < %s" % (self, other)) if isinstance(other, NumberSymbol): return other.__ge__(self) expr = self if isinstance(other, Number): if isinstance(other, Rational): return _sympify(bool(self.p*other.q < self.q*other.p)) if isinstance(other, Float): return _sympify(bool(mlib.mpf_lt( self._as_mpf_val(other._prec), other._mpf_))) elif other.is_number and other.is_real: expr, other = Integer(self.p), self.q*other return Expr.__lt__(expr, other) def __le__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s <= %s" % (self, other)) expr = self if isinstance(other, NumberSymbol): return other.__gt__(self) elif isinstance(other, Number): if isinstance(other, Rational): return _sympify(bool(self.p*other.q <= self.q*other.p)) if isinstance(other, Float): return _sympify(bool(mlib.mpf_le( self._as_mpf_val(other._prec), other._mpf_))) elif other.is_number and other.is_real: expr, other = Integer(self.p), self.q*other return Expr.__le__(expr, other) def __hash__(self): return super(Rational, self).__hash__() def factors(self, limit=None, use_trial=True, use_rho=False, use_pm1=False, verbose=False, visual=False): """A wrapper to factorint which return factors of self that are smaller than limit (or cheap to compute). Special methods of factoring are disabled by default so that only trial division is used. """ from sympy.ntheory import factorint f = factorint(self.p, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose).copy() f = defaultdict(int, f) for p, e in factorint(self.q, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose).items(): f[p] += -e if len(f) > 1 and 1 in f: del f[1] if not f: f = {1: 1} if not visual: return dict(f) else: if -1 in f: f.pop(-1) args = [S.NegativeOne] else: args = [] args.extend([Pow(*i, evaluate=False) for i in sorted(f.items())]) return Mul(*args, evaluate=False) @_sympifyit('other', NotImplemented) def gcd(self, other): if isinstance(other, Rational): if other is S.Zero: return other return Rational( Integer(igcd(self.p, other.p)), Integer(ilcm(self.q, other.q))) return Number.gcd(self, other) @_sympifyit('other', NotImplemented) def lcm(self, other): if isinstance(other, Rational): return Rational( self.p*other.p//igcd(self.p, other.p), igcd(self.q, other.q)) return Number.lcm(self, other) def as_numer_denom(self): return Integer(self.p), Integer(self.q) def _sage_(self): import sage.all as sage return sage.Integer(self.p)/sage.Integer(self.q) def as_content_primitive(self, radical=False): """Return the tuple (R, self/R) where R is the positive Rational extracted from self. Examples ======== >>> from sympy import S >>> (S(-3)/2).as_content_primitive() (3/2, -1) See docstring of Expr.as_content_primitive for more examples. """ if self: if self.is_positive: return self, S.One return -self, S.NegativeOne return S.One, self # int -> Integer _intcache = {} # TODO move this tracing facility to sympy/core/trace.py ? def _intcache_printinfo(): ints = sorted(_intcache.keys()) nhit = _intcache_hits nmiss = _intcache_misses if nhit == 0 and nmiss == 0: print() print('Integer cache statistic was not collected') return miss_ratio = float(nmiss) / (nhit + nmiss) print() print('Integer cache statistic') print('-----------------------') print() print('#items: %i' % len(ints)) print() print(' #hit #miss #total') print() print('%5i %5i (%7.5f %%) %5i' % ( nhit, nmiss, miss_ratio*100, nhit + nmiss) ) print() print(ints) _intcache_hits = 0 _intcache_misses = 0 def int_trace(f): import os if os.getenv('SYMPY_TRACE_INT', 'no').lower() != 'yes': return f def Integer_tracer(cls, i): global _intcache_hits, _intcache_misses try: _intcache_hits += 1 return _intcache[i] except KeyError: _intcache_hits -= 1 _intcache_misses += 1 return f(cls, i) # also we want to hook our _intcache_printinfo into sys.atexit import atexit atexit.register(_intcache_printinfo) return Integer_tracer class Integer(Rational): q = 1 is_integer = True is_number = True is_Integer = True __slots__ = ['p'] def _as_mpf_val(self, prec): return mlib.from_int(self.p, prec) def _mpmath_(self, prec, rnd): return mpmath.make_mpf(self._as_mpf_val(prec)) # TODO caching with decorator, but not to degrade performance @int_trace def __new__(cls, i): if isinstance(i, string_types): i = i.replace(' ', '') # whereas we cannot, in general, make a Rational from an # arbitrary expression, we can make an Integer unambiguously # (except when a non-integer expression happens to round to # an integer). So we proceed by taking int() of the input and # let the int routines determine whether the expression can # be made into an int or whether an error should be raised. try: ival = int(i) except TypeError: raise TypeError( 'Integer can only work with integer expressions.') try: return _intcache[ival] except KeyError: # We only work with well-behaved integer types. This converts, for # example, numpy.int32 instances. obj = Expr.__new__(cls) obj.p = ival _intcache[ival] = obj return obj def __getnewargs__(self): return (self.p,) # Arithmetic operations are here for efficiency def __int__(self): return self.p __long__ = __int__ def __neg__(self): return Integer(-self.p) def __abs__(self): if self.p >= 0: return self else: return Integer(-self.p) def __divmod__(self, other): from .containers import Tuple if isinstance(other, Integer): return Tuple(*(divmod(self.p, other.p))) else: return Number.__divmod__(self, other) def __rdivmod__(self, other): from .containers import Tuple if isinstance(other, integer_types): return Tuple(*(divmod(other, self.p))) else: try: other = Number(other) except TypeError: msg = "unsupported operand type(s) for divmod(): '%s' and '%s'" oname = type(other).__name__ sname = type(self).__name__ raise TypeError(msg % (oname, sname)) return Number.__divmod__(other, self) # TODO make it decorator + bytecodehacks? def __add__(self, other): if isinstance(other, integer_types): return Integer(self.p + other) elif isinstance(other, Integer): return Integer(self.p + other.p) return Rational.__add__(self, other) def __radd__(self, other): if isinstance(other, integer_types): return Integer(other + self.p) return Rational.__add__(self, other) def __sub__(self, other): if isinstance(other, integer_types): return Integer(self.p - other) elif isinstance(other, Integer): return Integer(self.p - other.p) return Rational.__sub__(self, other) def __rsub__(self, other): if isinstance(other, integer_types): return Integer(other - self.p) return Rational.__rsub__(self, other) def __mul__(self, other): if isinstance(other, integer_types): return Integer(self.p*other) elif isinstance(other, Integer): return Integer(self.p*other.p) return Rational.__mul__(self, other) def __rmul__(self, other): if isinstance(other, integer_types): return Integer(other*self.p) return Rational.__mul__(self, other) def __mod__(self, other): if isinstance(other, integer_types): return Integer(self.p % other) elif isinstance(other, Integer): return Integer(self.p % other.p) return Rational.__mod__(self, other) def __rmod__(self, other): if isinstance(other, integer_types): return Integer(other % self.p) elif isinstance(other, Integer): return Integer(other.p % self.p) return Rational.__rmod__(self, other) def __eq__(self, other): if isinstance(other, integer_types): return (self.p == other) elif isinstance(other, Integer): return (self.p == other.p) return Rational.__eq__(self, other) def __ne__(self, other): return not self.__eq__(other) def __gt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s > %s" % (self, other)) if isinstance(other, Integer): return _sympify(self.p > other.p) return Rational.__gt__(self, other) def __lt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s < %s" % (self, other)) if isinstance(other, Integer): return _sympify(self.p < other.p) return Rational.__lt__(self, other) def __ge__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s >= %s" % (self, other)) if isinstance(other, Integer): return _sympify(self.p >= other.p) return Rational.__ge__(self, other) def __le__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s <= %s" % (self, other)) if isinstance(other, Integer): return _sympify(self.p <= other.p) return Rational.__le__(self, other) def __hash__(self): return hash(self.p) def __index__(self): return self.p ######################################## def _eval_is_odd(self): return bool(self.p % 2) def _eval_power(self, expt): """ Tries to do some simplifications on self**expt Returns None if no further simplifications can be done When exponent is a fraction (so we have for example a square root), we try to find a simpler representation by factoring the argument up to factors of 2**15, e.g. - sqrt(4) becomes 2 - sqrt(-4) becomes 2*I - (2**(3+7)*3**(6+7))**Rational(1,7) becomes 6*18**(3/7) Further simplification would require a special call to factorint on the argument which is not done here for sake of speed. """ from sympy import perfect_power if expt is S.Infinity: if self.p > S.One: return S.Infinity # cases -1, 0, 1 are done in their respective classes return S.Infinity + S.ImaginaryUnit*S.Infinity if expt is S.NegativeInfinity: return Rational(1, self)**S.Infinity if not isinstance(expt, Number): # simplify when expt is even # (-2)**k --> 2**k if self.is_negative and expt.is_even: return (-self)**expt if not isinstance(expt, Rational): return if expt is S.Half and self.is_negative: # we extract I for this special case since everyone is doing so return S.ImaginaryUnit*Pow(-self, expt) if expt.is_negative: # invert base and change sign on exponent ne = -expt if self.is_negative: if expt.q != 1: return -(S.NegativeOne)**((expt.p % expt.q) / S(expt.q))*Rational(1, -self)**ne else: return (S.NegativeOne)**ne*Rational(1, -self)**ne else: return Rational(1, self.p)**ne # see if base is a perfect root, sqrt(4) --> 2 x, xexact = integer_nthroot(abs(self.p), expt.q) if xexact: # if it's a perfect root we've finished result = Integer(x**abs(expt.p)) if self.is_negative: result *= S.NegativeOne**expt return result # The following is an algorithm where we collect perfect roots # from the factors of base. # if it's not an nth root, it still might be a perfect power b_pos = int(abs(self.p)) p = perfect_power(b_pos) if p is not False: dict = {p[0]: p[1]} else: dict = Integer(self).factors(limit=2**15) # now process the dict of factors if self.is_negative: dict[-1] = 1 out_int = 1 # integer part out_rad = 1 # extracted radicals sqr_int = 1 sqr_gcd = 0 sqr_dict = {} for prime, exponent in dict.items(): exponent *= expt.p # remove multiples of expt.q: (2**12)**(1/10) -> 2*(2**2)**(1/10) div_e, div_m = divmod(exponent, expt.q) if div_e > 0: out_int *= prime**div_e if div_m > 0: # see if the reduced exponent shares a gcd with e.q # (2**2)**(1/10) -> 2**(1/5) g = igcd(div_m, expt.q) if g != 1: out_rad *= Pow(prime, Rational(div_m//g, expt.q//g)) else: sqr_dict[prime] = div_m # identify gcd of remaining powers for p, ex in sqr_dict.items(): if sqr_gcd == 0: sqr_gcd = ex else: sqr_gcd = igcd(sqr_gcd, ex) if sqr_gcd == 1: break for k, v in sqr_dict.items(): sqr_int *= k**(v//sqr_gcd) if sqr_int == self and out_int == 1 and out_rad == 1: result = None else: result = out_int*out_rad*Pow(sqr_int, Rational(sqr_gcd, expt.q)) return result def _eval_is_prime(self): from sympy.ntheory import isprime return isprime(self) def _eval_is_composite(self): if self > 1: return fuzzy_not(self.is_prime) else: return False def as_numer_denom(self): return self, S.One def __floordiv__(self, other): return Integer(self.p // Integer(other).p) def __rfloordiv__(self, other): return Integer(Integer(other).p // self.p) # Add sympify converters for i_type in integer_types: converter[i_type] = Integer class AlgebraicNumber(Expr): """Class for representing algebraic numbers in SymPy. """ __slots__ = ['rep', 'root', 'alias', 'minpoly'] is_AlgebraicNumber = True is_algebraic = True is_number = True def __new__(cls, expr, coeffs=None, alias=None, **args): """Construct a new algebraic number. """ from sympy import Poly from sympy.polys.polyclasses import ANP, DMP from sympy.polys.numberfields import minimal_polynomial from sympy.core.symbol import Symbol expr = sympify(expr) if isinstance(expr, (tuple, Tuple)): minpoly, root = expr if not minpoly.is_Poly: minpoly = Poly(minpoly) elif expr.is_AlgebraicNumber: minpoly, root = expr.minpoly, expr.root else: minpoly, root = minimal_polynomial( expr, args.get('gen'), polys=True), expr dom = minpoly.get_domain() if coeffs is not None: if not isinstance(coeffs, ANP): rep = DMP.from_sympy_list(sympify(coeffs), 0, dom) scoeffs = Tuple(*coeffs) else: rep = DMP.from_list(coeffs.to_list(), 0, dom) scoeffs = Tuple(*coeffs.to_list()) if rep.degree() >= minpoly.degree(): rep = rep.rem(minpoly.rep) else: rep = DMP.from_list([1, 0], 0, dom) scoeffs = Tuple(1, 0) if root.is_negative: rep = -rep scoeffs = Tuple(-1, 0) sargs = (root, scoeffs) if alias is not None: if not isinstance(alias, Symbol): alias = Symbol(alias) sargs = sargs + (alias,) obj = Expr.__new__(cls, *sargs) obj.rep = rep obj.root = root obj.alias = alias obj.minpoly = minpoly return obj def __hash__(self): return super(AlgebraicNumber, self).__hash__() def _eval_evalf(self, prec): return self.as_expr()._evalf(prec) @property def is_aliased(self): """Returns ``True`` if ``alias`` was set. """ return self.alias is not None def as_poly(self, x=None): """Create a Poly instance from ``self``. """ from sympy import Dummy, Poly, PurePoly if x is not None: return Poly.new(self.rep, x) else: if self.alias is not None: return Poly.new(self.rep, self.alias) else: return PurePoly.new(self.rep, Dummy('x')) def as_expr(self, x=None): """Create a Basic expression from ``self``. """ return self.as_poly(x or self.root).as_expr().expand() def coeffs(self): """Returns all SymPy coefficients of an algebraic number. """ return [ self.rep.dom.to_sympy(c) for c in self.rep.all_coeffs() ] def native_coeffs(self): """Returns all native coefficients of an algebraic number. """ return self.rep.all_coeffs() def to_algebraic_integer(self): """Convert ``self`` to an algebraic integer. """ from sympy import Poly f = self.minpoly if f.LC() == 1: return self coeff = f.LC()**(f.degree() - 1) poly = f.compose(Poly(f.gen/f.LC())) minpoly = poly*coeff root = f.LC()*self.root return AlgebraicNumber((minpoly, root), self.coeffs()) def _eval_simplify(self, ratio, measure): from sympy.polys import RootOf, minpoly for r in [r for r in self.minpoly.all_roots() if r.func != RootOf]: if minpoly(self.root - r).is_Symbol: # use the matching root if it's simpler if measure(r) < ratio*measure(self.root): return AlgebraicNumber(r) return self class RationalConstant(Rational): """ Abstract base class for rationals with specific behaviors Derived classes must define class attributes p and q and should probably all be singletons. """ __slots__ = [] def __new__(cls): return AtomicExpr.__new__(cls) class IntegerConstant(Integer): __slots__ = [] def __new__(cls): return AtomicExpr.__new__(cls) class Zero(with_metaclass(Singleton, IntegerConstant)): """The number zero. Zero is a singleton, and can be accessed by ``S.Zero`` Examples ======== >>> from sympy import S, Integer, zoo >>> Integer(0) is S.Zero True >>> 1/S.Zero zoo References ========== .. [1] http://en.wikipedia.org/wiki/Zero """ p = 0 q = 1 is_positive = False is_negative = False is_zero = True is_number = True __slots__ = [] @staticmethod def __abs__(): return S.Zero @staticmethod def __neg__(): return S.Zero def _eval_power(self, expt): if expt.is_positive: return self if expt.is_negative: return S.ComplexInfinity if expt.is_real is False: return S.NaN # infinities are already handled with pos and neg # tests above; now throw away leading numbers on Mul # exponent coeff, terms = expt.as_coeff_Mul() if coeff.is_negative: return S.ComplexInfinity**terms if coeff is not S.One: # there is a Number to discard return self**terms def _eval_order(self, *symbols): # Order(0,x) -> 0 return self def __nonzero__(self): return False __bool__ = __nonzero__ class One(with_metaclass(Singleton, IntegerConstant)): """The number one. One is a singleton, and can be accessed by ``S.One``. Examples ======== >>> from sympy import S, Integer >>> Integer(1) is S.One True References ========== .. [1] http://en.wikipedia.org/wiki/1_%28number%29 """ is_number = True p = 1 q = 1 __slots__ = [] @staticmethod def __abs__(): return S.One @staticmethod def __neg__(): return S.NegativeOne def _eval_power(self, expt): return self def _eval_order(self, *symbols): return @staticmethod def factors(limit=None, use_trial=True, use_rho=False, use_pm1=False, verbose=False, visual=False): if visual: return S.One return {1: 1} class NegativeOne(with_metaclass(Singleton, IntegerConstant)): """The number negative one. NegativeOne is a singleton, and can be accessed by ``S.NegativeOne``. Examples ======== >>> from sympy import S, Integer >>> Integer(-1) is S.NegativeOne True See Also ======== One References ========== .. [1] http://en.wikipedia.org/wiki/%E2%88%921_%28number%29 """ is_number = True p = -1 q = 1 __slots__ = [] @staticmethod def __abs__(): return S.One @staticmethod def __neg__(): return S.One def _eval_power(self, expt): if expt.is_odd: return S.NegativeOne if expt.is_even: return S.One if isinstance(expt, Number): if isinstance(expt, Float): return Float(-1.0)**expt if expt is S.NaN: return S.NaN if expt is S.Infinity or expt is S.NegativeInfinity: return S.NaN if expt is S.Half: return S.ImaginaryUnit if isinstance(expt, Rational): if expt.q == 2: return S.ImaginaryUnit**Integer(expt.p) i, r = divmod(expt.p, expt.q) if i: return self**i*self**Rational(r, expt.q) return class Half(with_metaclass(Singleton, RationalConstant)): """The rational number 1/2. Half is a singleton, and can be accessed by ``S.Half``. Examples ======== >>> from sympy import S, Rational >>> Rational(1, 2) is S.Half True References ========== .. [1] http://en.wikipedia.org/wiki/One_half """ is_number = True p = 1 q = 2 __slots__ = [] @staticmethod def __abs__(): return S.Half class Infinity(with_metaclass(Singleton, Number)): r"""Positive infinite quantity. In real analysis the symbol `\infty` denotes an unbounded limit: `x\to\infty` means that `x` grows without bound. Infinity is often used not only to define a limit but as a value in the affinely extended real number system. Points labeled `+\infty` and `-\infty` can be added to the topological space of the real numbers, producing the two-point compactification of the real numbers. Adding algebraic properties to this gives us the extended real numbers. Infinity is a singleton, and can be accessed by ``S.Infinity``, or can be imported as ``oo``. Examples ======== >>> from sympy import oo, exp, limit, Symbol >>> 1 + oo oo >>> 42/oo 0 >>> x = Symbol('x') >>> limit(exp(x), x, oo) oo See Also ======== NegativeInfinity, NaN References ========== .. [1] http://en.wikipedia.org/wiki/Infinity """ is_commutative = True is_positive = True is_infinite = True is_number = True is_prime = False __slots__ = [] def __new__(cls): return AtomicExpr.__new__(cls) def _latex(self, printer): return r"\infty" @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Number): if other is S.NegativeInfinity or other is S.NaN: return S.NaN elif other.is_Float: if other == Float('-inf'): return S.NaN else: return Float('inf') else: return S.Infinity return NotImplemented __radd__ = __add__ @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Number): if other is S.Infinity or other is S.NaN: return S.NaN elif other.is_Float: if other == Float('inf'): return S.NaN else: return Float('inf') else: return S.Infinity return NotImplemented @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Number): if other is S.Zero or other is S.NaN: return S.NaN elif other.is_Float: if other == 0: return S.NaN if other > 0: return Float('inf') else: return Float('-inf') else: if other > 0: return S.Infinity else: return S.NegativeInfinity return NotImplemented __rmul__ = __mul__ @_sympifyit('other', NotImplemented) def __div__(self, other): if isinstance(other, Number): if other is S.Infinity or \ other is S.NegativeInfinity or \ other is S.NaN: return S.NaN elif other.is_Float: if other == Float('-inf') or \ other == Float('inf'): return S.NaN elif other.is_nonnegative: return Float('inf') else: return Float('-inf') else: if other >= 0: return S.Infinity else: return S.NegativeInfinity return NotImplemented __truediv__ = __div__ def __abs__(self): return S.Infinity def __neg__(self): return S.NegativeInfinity def _eval_power(self, expt): """ ``expt`` is symbolic object but not equal to 0 or 1. ================ ======= ============================== Expression Result Notes ================ ======= ============================== ``oo ** nan`` ``nan`` ``oo ** -p`` ``0`` ``p`` is number, ``oo`` ================ ======= ============================== See Also ======== Pow NaN NegativeInfinity """ if expt.is_positive: return S.Infinity if expt.is_negative: return S.Zero if expt is S.NaN: return S.NaN if expt is S.ComplexInfinity: return S.NaN if expt.is_number: return self**expt.evalf() def _as_mpf_val(self, prec): return mlib.finf def _sage_(self): import sage.all as sage return sage.oo def __hash__(self): return super(Infinity, self).__hash__() def __eq__(self, other): return other is S.Infinity def __ne__(self, other): return other is not S.Infinity def __lt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s < %s" % (self, other)) if other.is_real: return S.false return Expr.__lt__(self, other) def __le__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s <= %s" % (self, other)) if other.is_real: if other.is_finite or other is S.NegativeInfinity: return S.false elif other.is_nonpositive: return S.false elif other.is_infinite and other.is_positive: return S.true return Expr.__le__(self, other) def __gt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s > %s" % (self, other)) if other.is_real: if other.is_finite or other is S.NegativeInfinity: return S.true elif other.is_nonpositive: return S.true elif other.is_infinite and other.is_positive: return S.false return Expr.__gt__(self, other) def __ge__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s >= %s" % (self, other)) if other.is_real: return S.true return Expr.__ge__(self, other) def __mod__(self, other): return S.NaN __rmod__ = __mod__ oo = S.Infinity class NegativeInfinity(with_metaclass(Singleton, Number)): """Negative infinite quantity. NegativeInfinity is a singleton, and can be accessed by ``S.NegativeInfinity``. See Also ======== Infinity """ is_commutative = True is_negative = True is_infinite = True is_number = True __slots__ = [] def __new__(cls): return AtomicExpr.__new__(cls) def _latex(self, printer): return r"-\infty" @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Number): if other is S.Infinity or other is S.NaN: return S.NaN elif other.is_Float: if other == Float('inf'): return Float('nan') else: return Float('-inf') else: return S.NegativeInfinity return NotImplemented __radd__ = __add__ @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Number): if other is S.NegativeInfinity or other is S.NaN: return S.NaN elif other.is_Float: if other == Float('-inf'): return Float('nan') else: return Float('-inf') else: return S.NegativeInfinity return NotImplemented @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Number): if other is S.Zero or other is S.NaN: return S.NaN elif other.is_Float: if other is S.NaN or other.is_zero: return S.NaN elif other.is_positive: return Float('-inf') else: return Float('inf') else: if other.is_positive: return S.NegativeInfinity else: return S.Infinity return NotImplemented __rmul__ = __mul__ @_sympifyit('other', NotImplemented) def __div__(self, other): if isinstance(other, Number): if other is S.Infinity or \ other is S.NegativeInfinity or \ other is S.NaN: return S.NaN elif other.is_Float: if other == Float('-inf') or \ other == Float('inf') or \ other is S.NaN: return S.NaN elif other.is_nonnegative: return Float('-inf') else: return Float('inf') else: if other >= 0: return S.NegativeInfinity else: return S.Infinity return NotImplemented __truediv__ = __div__ def __abs__(self): return S.Infinity def __neg__(self): return S.Infinity def _eval_power(self, expt): """ ``expt`` is symbolic object but not equal to 0 or 1. ================ ======= ============================== Expression Result Notes ================ ======= ============================== ``(-oo) ** nan`` ``nan`` ``(-oo) ** oo`` ``nan`` ``(-oo) ** -oo`` ``nan`` ``(-oo) ** e`` ``oo`` ``e`` is positive even integer ``(-oo) ** o`` ``-oo`` ``o`` is positive odd integer ================ ======= ============================== See Also ======== Infinity Pow NaN """ if isinstance(expt, Number): if expt is S.NaN or \ expt is S.Infinity or \ expt is S.NegativeInfinity: return S.NaN if isinstance(expt, Integer) and expt.is_positive: if expt.is_odd: return S.NegativeInfinity else: return S.Infinity return S.NegativeOne**expt*S.Infinity**expt def _as_mpf_val(self, prec): return mlib.fninf def _sage_(self): import sage.all as sage return -(sage.oo) def __hash__(self): return super(NegativeInfinity, self).__hash__() def __eq__(self, other): return other is S.NegativeInfinity def __ne__(self, other): return other is not S.NegativeInfinity def __lt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s < %s" % (self, other)) if other.is_real: if other.is_finite or other is S.Infinity: return S.true elif other.is_nonnegative: return S.true elif other.is_infinite and other.is_negative: return S.false return Expr.__lt__(self, other) def __le__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s <= %s" % (self, other)) if other.is_real: return S.true return Expr.__le__(self, other) def __gt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s > %s" % (self, other)) if other.is_real: return S.false return Expr.__gt__(self, other) def __ge__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s >= %s" % (self, other)) if other.is_real: if other.is_finite or other is S.Infinity: return S.false elif other.is_nonnegative: return S.false elif other.is_infinite and other.is_negative: return S.true return Expr.__ge__(self, other) def __mod__(self, other): return S.NaN __rmod__ = __mod__ class NaN(with_metaclass(Singleton, Number)): """ Not a Number. This serves as a place holder for numeric values that are indeterminate. Most operations on NaN, produce another NaN. Most indeterminate forms, such as ``0/0`` or ``oo - oo` produce NaN. Two exceptions are ``0**0`` and ``oo**0``, which all produce ``1`` (this is consistent with Python's float). NaN is loosely related to floating point nan, which is defined in the IEEE 754 floating point standard, and corresponds to the Python ``float('nan')``. Differences are noted below. NaN is mathematically not equal to anything else, even NaN itself. This explains the initially counter-intuitive results with ``Eq`` and ``==`` in the examples below. NaN is not comparable so inequalities raise a TypeError. This is in constrast with floating point nan where all inequalities are false. NaN is a singleton, and can be accessed by ``S.NaN``, or can be imported as ``nan``. Examples ======== >>> from sympy import nan, S, oo, Eq >>> nan is S.NaN True >>> oo - oo nan >>> nan + 1 nan >>> Eq(nan, nan) # mathematical equality False >>> nan == nan # structural equality True References ========== .. [1] http://en.wikipedia.org/wiki/NaN """ is_commutative = True is_real = None is_rational = None is_algebraic = None is_transcendental = None is_integer = None is_comparable = False is_finite = None is_zero = None is_prime = None is_positive = None is_negative = None is_number = True __slots__ = [] def __new__(cls): return AtomicExpr.__new__(cls) def _latex(self, printer): return r"\mathrm{NaN}" @_sympifyit('other', NotImplemented) def __add__(self, other): return self @_sympifyit('other', NotImplemented) def __sub__(self, other): return self @_sympifyit('other', NotImplemented) def __mul__(self, other): return self @_sympifyit('other', NotImplemented) def __div__(self, other): return self __truediv__ = __div__ def _as_mpf_val(self, prec): return _mpf_nan def _sage_(self): import sage.all as sage return sage.NaN def __hash__(self): return super(NaN, self).__hash__() def __eq__(self, other): # NaN is structurally equal to another NaN return other is S.NaN def __ne__(self, other): return other is not S.NaN def _eval_Eq(self, other): # NaN is not mathematically equal to anything, even NaN return S.false # Expr will _sympify and raise TypeError __gt__ = Expr.__gt__ __ge__ = Expr.__ge__ __lt__ = Expr.__lt__ __le__ = Expr.__le__ nan = S.NaN class ComplexInfinity(with_metaclass(Singleton, AtomicExpr)): r"""Complex infinity. In complex analysis the symbol `\tilde\infty`, called "complex infinity", represents a quantity with infinite magnitude, but undetermined complex phase. ComplexInfinity is a singleton, and can be accessed by ``S.ComplexInfinity``, or can be imported as ``zoo``. Examples ======== >>> from sympy import zoo, oo >>> zoo + 42 zoo >>> 42/zoo 0 >>> zoo + zoo nan >>> zoo*zoo zoo See Also ======== Infinity """ is_commutative = True is_infinite = True is_number = True is_prime = False __slots__ = [] def __new__(cls): return AtomicExpr.__new__(cls) def _latex(self, printer): return r"\tilde{\infty}" @staticmethod def __abs__(): return S.Infinity @staticmethod def __neg__(): return S.ComplexInfinity def _eval_power(self, expt): if expt is S.ComplexInfinity: return S.NaN if isinstance(expt, Number): if expt is S.Zero: return S.NaN else: if expt.is_positive: return S.ComplexInfinity else: return S.Zero def _sage_(self): import sage.all as sage return sage.UnsignedInfinityRing.gen() zoo = S.ComplexInfinity class NumberSymbol(AtomicExpr): is_commutative = True is_finite = True is_number = True __slots__ = [] is_NumberSymbol = True def __new__(cls): return AtomicExpr.__new__(cls) def approximation(self, number_cls): """ Return an interval with number_cls endpoints that contains the value of NumberSymbol. If not implemented, then return None. """ def _eval_evalf(self, prec): return Float._new(self._as_mpf_val(prec), prec) def __eq__(self, other): try: other = _sympify(other) except SympifyError: return False # sympy != other --> not == if self is other: return True if isinstance(other, Number) and self.is_irrational: return False return False # NumberSymbol != non-(Number|self) def __ne__(self, other): return not self.__eq__(other) def __lt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s < %s" % (self, other)) if self is other: return S.false if isinstance(other, Number): approx = self.approximation_interval(other.__class__) if approx is not None: l, u = approx if other < l: return S.false if other > u: return S.true return _sympify(self.evalf() < other) if other.is_real and other.is_number: other = other.evalf() return _sympify(self.evalf() < other) return Expr.__lt__(self, other) def __le__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s <= %s" % (self, other)) if self is other: return S.true if other.is_real and other.is_number: other = other.evalf() if isinstance(other, Number): return _sympify(self.evalf() <= other) return Expr.__le__(self, other) def __gt__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s > %s" % (self, other)) r = _sympify((-self) < (-other)) if r in (S.true, S.false): return r else: return Expr.__gt__(self, other) def __ge__(self, other): try: other = _sympify(other) except SympifyError: raise TypeError("Invalid comparison %s >= %s" % (self, other)) r = _sympify((-self) <= (-other)) if r in (S.true, S.false): return r else: return Expr.__ge__(self, other) def __int__(self): # subclass with appropriate return value raise NotImplementedError def __long__(self): return self.__int__() def __hash__(self): return super(NumberSymbol, self).__hash__() class Exp1(with_metaclass(Singleton, NumberSymbol)): r"""The `e` constant. The transcendental number `e = 2.718281828\dots` is the base of the natural logarithm and of the exponential function, `e = \exp(1)`. Sometimes called Euler's number or Napier's constant. Exp1 is a singleton, and can be accessed by ``S.Exp1``, or can be imported as ``E``. Examples ======== >>> from sympy import exp, log, E >>> E is exp(1) True >>> log(E) 1 References ========== .. [1] http://en.wikipedia.org/wiki/E_%28mathematical_constant%29 """ is_real = True is_positive = True is_negative = False # XXX Forces is_negative/is_nonnegative is_irrational = True is_number = True is_algebraic = False is_transcendental = True __slots__ = [] def _latex(self, printer): return r"e" @staticmethod def __abs__(): return S.Exp1 def __int__(self): return 2 def _as_mpf_val(self, prec): return mpf_e(prec) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (Integer(2), Integer(3)) elif issubclass(number_cls, Rational): pass def _eval_power(self, expt): from sympy import exp return exp(expt) def _eval_rewrite_as_sin(self): from sympy import sin I = S.ImaginaryUnit return sin(I + S.Pi/2) - I*sin(I) def _eval_rewrite_as_cos(self): from sympy import cos I = S.ImaginaryUnit return cos(I) + I*cos(I + S.Pi/2) def _sage_(self): import sage.all as sage return sage.e E = S.Exp1 class Pi(with_metaclass(Singleton, NumberSymbol)): r"""The `\pi` constant. The transcendental number `\pi = 3.141592654\dots` represents the ratio of a circle's circumference to its diameter, the area of the unit circle, the half-period of trigonometric functions, and many other things in mathematics. Pi is a singleton, and can be accessed by ``S.Pi``, or can be imported as ``pi``. Examples ======== >>> from sympy import S, pi, oo, sin, exp, integrate, Symbol >>> S.Pi pi >>> pi > 3 True >>> pi.is_irrational True >>> x = Symbol('x') >>> sin(x + 2*pi) sin(x) >>> integrate(exp(-x**2), (x, -oo, oo)) sqrt(pi) References ========== .. [1] http://en.wikipedia.org/wiki/Pi """ is_real = True is_positive = True is_negative = False is_irrational = True is_number = True is_algebraic = False is_transcendental = True __slots__ = [] def _latex(self, printer): return r"\pi" @staticmethod def __abs__(): return S.Pi def __int__(self): return 3 def _as_mpf_val(self, prec): return mpf_pi(prec) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (Integer(3), Integer(4)) elif issubclass(number_cls, Rational): return (Rational(223, 71), Rational(22, 7)) def _sage_(self): import sage.all as sage return sage.pi pi = S.Pi class GoldenRatio(with_metaclass(Singleton, NumberSymbol)): r"""The golden ratio, `\phi`. `\phi = \frac{1 + \sqrt{5}}{2}` is algebraic number. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities, i.e. their maximum. GoldenRatio is a singleton, and can be accessed by ``S.GoldenRatio``. Examples ======== >>> from sympy import S >>> S.GoldenRatio > 1 True >>> S.GoldenRatio.expand(func=True) 1/2 + sqrt(5)/2 >>> S.GoldenRatio.is_irrational True References ========== .. [1] http://en.wikipedia.org/wiki/Golden_ratio """ is_real = True is_positive = True is_negative = False is_irrational = True is_number = True is_algebraic = True is_transcendental = False __slots__ = [] def _latex(self, printer): return r"\phi" def __int__(self): return 1 def _as_mpf_val(self, prec): # XXX track down why this has to be increased rv = mlib.from_man_exp(phi_fixed(prec + 10), -prec - 10) return mpf_norm(rv, prec) def _eval_expand_func(self, **hints): from sympy import sqrt return S.Half + S.Half*sqrt(5) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (S.One, Rational(2)) elif issubclass(number_cls, Rational): pass def _sage_(self): import sage.all as sage return sage.golden_ratio class EulerGamma(with_metaclass(Singleton, NumberSymbol)): r"""The Euler-Mascheroni constant. `\gamma = 0.5772157\dots` (also called Euler's constant) is a mathematical constant recurring in analysis and number theory. It is defined as the limiting difference between the harmonic series and the natural logarithm: .. math:: \gamma = \lim\limits_{n\to\infty} \left(\sum\limits_{k=1}^n\frac{1}{k} - \ln n\right) EulerGamma is a singleton, and can be accessed by ``S.EulerGamma``. Examples ======== >>> from sympy import S >>> S.EulerGamma.is_irrational >>> S.EulerGamma > 0 True >>> S.EulerGamma > 1 False References ========== .. [1] http://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant """ is_real = True is_positive = True is_negative = False is_irrational = None is_number = True __slots__ = [] def _latex(self, printer): return r"\gamma" def __int__(self): return 0 def _as_mpf_val(self, prec): # XXX track down why this has to be increased v = mlib.libhyper.euler_fixed(prec + 10) rv = mlib.from_man_exp(v, -prec - 10) return mpf_norm(rv, prec) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (S.Zero, S.One) elif issubclass(number_cls, Rational): return (S.Half, Rational(3, 5)) def _sage_(self): import sage.all as sage return sage.euler_gamma class Catalan(with_metaclass(Singleton, NumberSymbol)): r"""Catalan's constant. `K = 0.91596559\dots` is given by the infinite series .. math:: K = \sum_{k=0}^{\infty} \frac{(-1)^k}{(2k+1)^2} Catalan is a singleton, and can be accessed by ``S.Catalan``. Examples ======== >>> from sympy import S >>> S.Catalan.is_irrational >>> S.Catalan > 0 True >>> S.Catalan > 1 False References ========== .. [1] http://en.wikipedia.org/wiki/Catalan%27s_constant """ is_real = True is_positive = True is_negative = False is_irrational = None is_number = True __slots__ = [] def __int__(self): return 0 def _as_mpf_val(self, prec): # XXX track down why this has to be increased v = mlib.catalan_fixed(prec + 10) rv = mlib.from_man_exp(v, -prec - 10) return mpf_norm(rv, prec) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (S.Zero, S.One) elif issubclass(number_cls, Rational): return (Rational(9, 10), S.One) def _sage_(self): import sage.all as sage return sage.catalan class ImaginaryUnit(with_metaclass(Singleton, AtomicExpr)): r"""The imaginary unit, `i = \sqrt{-1}`. I is a singleton, and can be accessed by ``S.I``, or can be imported as ``I``. Examples ======== >>> from sympy import I, sqrt >>> sqrt(-1) I >>> I*I -1 >>> 1/I -I References ========== .. [1] http://en.wikipedia.org/wiki/Imaginary_unit """ is_commutative = True is_imaginary = True is_finite = True is_number = True is_algebraic = True is_transcendental = False __slots__ = [] def _latex(self, printer): return r"i" @staticmethod def __abs__(): return S.One def _eval_evalf(self, prec): return self def _eval_conjugate(self): return -S.ImaginaryUnit def _eval_power(self, expt): """ b is I = sqrt(-1) e is symbolic object but not equal to 0, 1 I**r -> (-1)**(r/2) -> exp(r/2*Pi*I) -> sin(Pi*r/2) + cos(Pi*r/2)*I, r is decimal I**0 mod 4 -> 1 I**1 mod 4 -> I I**2 mod 4 -> -1 I**3 mod 4 -> -I """ if isinstance(expt, Number): if isinstance(expt, Integer): expt = expt.p % 4 if expt == 0: return S.One if expt == 1: return S.ImaginaryUnit if expt == 2: return -S.One return -S.ImaginaryUnit return (S.NegativeOne)**(expt*S.Half) return def as_base_exp(self): return S.NegativeOne, S.Half def _sage_(self): import sage.all as sage return sage.I I = S.ImaginaryUnit def sympify_fractions(f): return Rational(f.numerator, f.denominator) converter[fractions.Fraction] = sympify_fractions try: if HAS_GMPY == 2: import gmpy2 as gmpy elif HAS_GMPY == 1: import gmpy else: raise ImportError def sympify_mpz(x): return Integer(long(x)) def sympify_mpq(x): return Rational(long(x.numerator), long(x.denominator)) converter[type(gmpy.mpz(1))] = sympify_mpz converter[type(gmpy.mpq(1, 2))] = sympify_mpq except ImportError: pass def sympify_mpmath(x): return Expr._from_mpmath(x, x.context.prec) converter[mpnumeric] = sympify_mpmath def sympify_complex(a): real, imag = list(map(sympify, (a.real, a.imag))) return real + S.ImaginaryUnit*imag converter[complex] = sympify_complex _intcache[0] = S.Zero _intcache[1] = S.One _intcache[-1] = S.NegativeOne from .power import Pow, integer_nthroot from .mul import Mul Mul.identity = One() from .add import Add Add.identity = Zero()
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- import mock from mock import PropertyMock from mock import MagicMock from annotran import admin from annotran.admin import * from pyramid import httpexceptions as exc _SENTINEL = object() def _mock_request(feature=None, settings=None, params=None, authenticated_userid=_SENTINEL, route_url=None, **kwargs): """Return a mock Pyramid request object.""" params = params or {"foo": "bar"} if authenticated_userid is _SENTINEL: authenticated_userid = "acct:gam@annotran.com" return mock.Mock( feature=feature or (lambda feature: True), registry=mock.Mock(settings=settings or {}), params=params, POST=params, authenticated_userid=authenticated_userid, route_url=route_url or mock.Mock(return_value="test-read-url"), **kwargs) def test_reports_view(): """ This should return a context dictionary (of length 8) for the translation template. """ with mock.patch('annotran.languages.models.Language') as language: language.get_by_public_language_id = MagicMock(return_value=language) with mock.patch('h.groups.models.Group') as group: group.get_by_pubid = MagicMock(return_value=group) annotran.groups.views.read_group = MagicMock(return_value=group) request = _mock_request(authenticated_user=mock.Mock(username="test"), matchdict={'page': 'http://www.annotran_test.com/', 'language': '12345', 'group': '12345', 'user': 'acct:gam@127.0.0.1', 'report': 'report'}) result = reports_view(request) assert isinstance(result, dict) assert result.__len__() == 8 def test_reports_delete_block(): """ This should invoke admin.reports_delete(request, block=True) """ request = _mock_request(authenticated_user=mock.Mock()) admin.reports_delete = MagicMock(return_value=None) reports_delete_block(request) admin.reports_delete.assert_called_once() def test_reports_delete_report(): """ This should invoke deletion of a report only, and without blocking a user. After that it should redirect. """ with mock.patch('annotran.languages.models.Language') as language: language.get_by_public_language_id = MagicMock(return_value=language) with mock.patch('h.groups.models.Group') as group: group.get_by_pubid = MagicMock(return_value=group) with mock.patch('annotran.pages.models.Page') as page: page.get_by_uri = MagicMock(return_value=page) with mock.patch('annotran.translations.models.Translation') as translation: translation.get_translation = MagicMock(return_value=translation) with mock.patch('annotran.reports.models.Report') as report: report.get_by_id = MagicMock(return_value=report) with mock.patch('h.accounts.models.User') as user: user.query.filter = MagicMock(return_value=user) admin.delete_report = MagicMock(return_value=None) # this methos should be outside of admin.py (in reports/views)? request = _mock_request(authenticated_user=mock.Mock(username="test"), matchdict={'page': 'http://www.annotran_test.com/', 'language': '12345', 'report': '12345', 'group': '12345'}) result = reports_delete_report(request) admin.delete_report.assert_called_once() assert not request.db.flush.called assert isinstance(result, exc.HTTPRedirection) def test_reports_delete_report_with_blocking(): """ This should invoke deletion of a report only, and block a user by changing user's activation_id. After that it should redirect. """ with mock.patch('annotran.languages.models.Language') as language: language.get_by_public_language_id = MagicMock(return_value=language) with mock.patch('h.groups.models.Group') as group: group.get_by_pubid = MagicMock(return_value=group) with mock.patch('annotran.pages.models.Page') as page: page.get_by_uri = MagicMock(return_value=page) with mock.patch('annotran.translations.models.Translation') as translation: translation.get_translation = MagicMock(return_value=translation) with mock.patch('annotran.reports.models.Report') as report: report.get_by_id = MagicMock(return_value=report) with mock.patch('h.accounts.models.User') as user: propUser = PropertyMock(return_value=2897) type(user).activation_id = propUser user.get_by_username = MagicMock(return_value=user) user.query.filter = MagicMock(return_value=user) admin.delete_report = MagicMock(return_value=None) # this methos should be outside of admin.py (in reports/views)? request = _mock_request(authenticated_user=mock.Mock(username="test"), matchdict={'page': 'http://www.annotran_test.com/', 'language': '12345', 'report': '12345', 'group': '12345'}) result = reports_delete_report(request, True) admin.delete_report.assert_called_once() request.db.flush.assert_called_once() assert isinstance(result, exc.HTTPRedirection) def test_reports_delete_block_report(): """ This should invoke admin.reports_delete_report(request, block=True) """ request = _mock_request(authenticated_user=mock.Mock()) admin.reports_delete_report = MagicMock(return_value=None) reports_delete_block_report(request) admin.reports_delete_report.assert_called_once() def test_reports_index(): """ This should query all reports from a database and return a context dictionary (of length 1 - as there is only one report added) for it. """ reports = [] with mock.patch('annotran.languages.models.Language') as language: language.get_by_id = MagicMock(return_value=language) with mock.patch('h.groups.models.Group') as group: group.get_by_id = MagicMock(return_value=group) with mock.patch('annotran.pages.models.Page') as page: page.get_by_id = MagicMock(return_value=page) with mock.patch('annotran.translations.models.Translation') as translation: translation.get_by_composite_id = MagicMock(return_value=translation) with mock.patch('annotran.reports.models.Report') as report: propReport = PropertyMock(return_value=2897) type(report).id = propReport reports.append(report) report.get_all = MagicMock(return_value=reports) with mock.patch('h.accounts.models.User') as user: propUser = PropertyMock(return_value=2897) type(user).id = propUser user.get_by_username = MagicMock(return_value=user) user.query.filter = MagicMock(return_value=user) h.util.userid_from_username = MagicMock(return_value="12345") request = _mock_request(authenticated_user=mock.Mock()) result = reports_index(request) assert isinstance(result, dict) assert result.__len__() == 1
unknown
codeparrot/codeparrot-clean
"""SCons.Platform.win32 Platform-specific initialization for Win32 systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Platform/win32.py 4043 2009/02/23 09:06:45 scons" import os import os.path import string import sys import tempfile from SCons.Platform.posix import exitvalmap from SCons.Platform import TempFileMunge import SCons.Util try: import msvcrt import win32api import win32con msvcrt.get_osfhandle win32api.SetHandleInformation win32con.HANDLE_FLAG_INHERIT except ImportError: parallel_msg = \ "you do not seem to have the pywin32 extensions installed;\n" + \ "\tparallel (-j) builds may not work reliably with open Python files." except AttributeError: parallel_msg = \ "your pywin32 extensions do not support file handle operations;\n" + \ "\tparallel (-j) builds may not work reliably with open Python files." else: parallel_msg = None import __builtin__ _builtin_file = __builtin__.file _builtin_open = __builtin__.open def _scons_file(*args, **kw): fp = apply(_builtin_file, args, kw) win32api.SetHandleInformation(msvcrt.get_osfhandle(fp.fileno()), win32con.HANDLE_FLAG_INHERIT, 0) return fp def _scons_open(*args, **kw): fp = apply(_builtin_open, args, kw) win32api.SetHandleInformation(msvcrt.get_osfhandle(fp.fileno()), win32con.HANDLE_FLAG_INHERIT, 0) return fp __builtin__.file = _scons_file __builtin__.open = _scons_open # The upshot of all this is that, if you are using Python 1.5.2, # you had better have cmd or command.com in your PATH when you run # scons. def piped_spawn(sh, escape, cmd, args, env, stdout, stderr): # There is no direct way to do that in python. What we do # here should work for most cases: # In case stdout (stderr) is not redirected to a file, # we redirect it into a temporary file tmpFileStdout # (tmpFileStderr) and copy the contents of this file # to stdout (stderr) given in the argument if not sh: sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n") return 127 else: # one temporary file for stdout and stderr tmpFileStdout = os.path.normpath(tempfile.mktemp()) tmpFileStderr = os.path.normpath(tempfile.mktemp()) # check if output is redirected stdoutRedirected = 0 stderrRedirected = 0 for arg in args: # are there more possibilities to redirect stdout ? if (string.find( arg, ">", 0, 1 ) != -1 or string.find( arg, "1>", 0, 2 ) != -1): stdoutRedirected = 1 # are there more possibilities to redirect stderr ? if string.find( arg, "2>", 0, 2 ) != -1: stderrRedirected = 1 # redirect output of non-redirected streams to our tempfiles if stdoutRedirected == 0: args.append(">" + str(tmpFileStdout)) if stderrRedirected == 0: args.append("2>" + str(tmpFileStderr)) # actually do the spawn try: args = [sh, '/C', escape(string.join(args)) ] ret = os.spawnve(os.P_WAIT, sh, args, env) except OSError, e: # catch any error try: ret = exitvalmap[e[0]] except KeyError: sys.stderr.write("scons: unknown OSError exception code %d - %s: %s\n" % (e[0], cmd, e[1])) if stderr != None: stderr.write("scons: %s: %s\n" % (cmd, e[1])) # copy child output from tempfiles to our streams # and do clean up stuff if stdout != None and stdoutRedirected == 0: try: stdout.write(open( tmpFileStdout, "r" ).read()) os.remove( tmpFileStdout ) except (IOError, OSError): pass if stderr != None and stderrRedirected == 0: try: stderr.write(open( tmpFileStderr, "r" ).read()) os.remove( tmpFileStderr ) except (IOError, OSError): pass return ret def exec_spawn(l, env): try: result = os.spawnve(os.P_WAIT, l[0], l, env) except OSError, e: try: result = exitvalmap[e[0]] sys.stderr.write("scons: %s: %s\n" % (l[0], e[1])) except KeyError: result = 127 if len(l) > 2: if len(l[2]) < 1000: command = string.join(l[0:3]) else: command = l[0] else: command = l[0] sys.stderr.write("scons: unknown OSError exception code %d - '%s': %s\n" % (e[0], command, e[1])) return result def spawn(sh, escape, cmd, args, env): if not sh: sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n") return 127 return exec_spawn([sh, '/C', escape(string.join(args))], env) # Windows does not allow special characters in file names anyway, so no # need for a complex escape function, we will just quote the arg, except # that "cmd /c" requires that if an argument ends with a backslash it # needs to be escaped so as not to interfere with closing double quote # that we add. def escape(x): if x[-1] == '\\': x = x + '\\' return '"' + x + '"' # Get the windows system directory name _system_root = None def get_system_root(): global _system_root if _system_root is not None: return _system_root # A resonable default if we can't read the registry val = os.environ.get('SystemRoot', "C:/WINDOWS") if SCons.Util.can_read_reg: try: # Look for Windows NT system root k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows NT\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot') except SCons.Util.RegError: try: # Okay, try the Windows 9x system root k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot') except KeyboardInterrupt: raise except: pass _system_root = val return val # Get the location of the program files directory def get_program_files_dir(): # Now see if we can look in the registry... val = '' if SCons.Util.can_read_reg: try: # Look for Windows Program Files directory k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'ProgramFilesDir') except SCons.Util.RegError: val = '' pass if val == '': # A reasonable default if we can't read the registry # (Actually, it's pretty reasonable even if we can :-) val = os.path.join(os.path.dirname(get_system_root()),"Program Files") return val def generate(env): # Attempt to find cmd.exe (for WinNT/2k/XP) or # command.com for Win9x cmd_interp = '' # First see if we can look in the registry... if SCons.Util.can_read_reg: try: # Look for Windows NT system root k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows NT\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot') cmd_interp = os.path.join(val, 'System32\\cmd.exe') except SCons.Util.RegError: try: # Okay, try the Windows 9x system root k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot') cmd_interp = os.path.join(val, 'command.com') except KeyboardInterrupt: raise except: pass # For the special case of not having access to the registry, we # use a temporary path and pathext to attempt to find the command # interpreter. If we fail, we try to find the interpreter through # the env's PATH. The problem with that is that it might not # contain an ENV and a PATH. if not cmd_interp: systemroot = get_system_root() tmp_path = systemroot + os.pathsep + \ os.path.join(systemroot,'System32') tmp_pathext = '.com;.exe;.bat;.cmd' if os.environ.has_key('PATHEXT'): tmp_pathext = os.environ['PATHEXT'] cmd_interp = SCons.Util.WhereIs('cmd', tmp_path, tmp_pathext) if not cmd_interp: cmd_interp = SCons.Util.WhereIs('command', tmp_path, tmp_pathext) if not cmd_interp: cmd_interp = env.Detect('cmd') if not cmd_interp: cmd_interp = env.Detect('command') if not env.has_key('ENV'): env['ENV'] = {} # Import things from the external environment to the construction # environment's ENV. This is a potential slippery slope, because we # *don't* want to make builds dependent on the user's environment by # default. We're doing this for SystemRoot, though, because it's # needed for anything that uses sockets, and seldom changes, and # for SystemDrive because it's related. # # Weigh the impact carefully before adding other variables to this list. import_env = [ 'SystemDrive', 'SystemRoot', 'TEMP', 'TMP' ] for var in import_env: v = os.environ.get(var) if v: env['ENV'][var] = v if not env['ENV'].has_key('COMSPEC'): v = os.environ.get("COMSPEC") if v: env['ENV']['COMSPEC'] = v env.AppendENVPath('PATH', get_system_root() + '\System32') env['ENV']['PATHEXT'] = '.COM;.EXE;.BAT;.CMD' env['OBJPREFIX'] = '' env['OBJSUFFIX'] = '.obj' env['SHOBJPREFIX'] = '$OBJPREFIX' env['SHOBJSUFFIX'] = '$OBJSUFFIX' env['PROGPREFIX'] = '' env['PROGSUFFIX'] = '.exe' env['LIBPREFIX'] = '' env['LIBSUFFIX'] = '.lib' env['SHLIBPREFIX'] = '' env['SHLIBSUFFIX'] = '.dll' env['LIBPREFIXES'] = [ '$LIBPREFIX' ] env['LIBSUFFIXES'] = [ '$LIBSUFFIX' ] env['PSPAWN'] = piped_spawn env['SPAWN'] = spawn env['SHELL'] = cmd_interp env['TEMPFILE'] = TempFileMunge env['TEMPFILEPREFIX'] = '@' env['MAXLINELENGTH'] = 2048 env['ESCAPE'] = escape # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
unknown
codeparrot/codeparrot-clean
/* * Copyright (c) 2007 Mockito contributors * This program is made available under the terms of the MIT License. */ package org.mockito.exceptions.base; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.junit.Test; import org.mockitoutil.TestBase; public class MockitoExceptionTest extends TestBase { private void throwIt() { throw new MockitoException("boom"); } @Test public void shouldKeepUnfilteredStackTrace() { try { throwIt(); fail(); } catch (MockitoException e) { assertEquals("throwIt", e.getUnfilteredStackTrace()[0].getMethodName()); } } }
java
github
https://github.com/mockito/mockito
mockito-core/src/test/java/org/mockito/exceptions/base/MockitoExceptionTest.java
# This source file is part of the Swift.org open source project # # Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors # Licensed under Apache License v2.0 with Runtime Library Exception # # See http://swift.org/LICENSE.txt for license information # See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors # import json from .path import Path class Configuration: Debug = "debug" Release = "release" version = 1 command = None current = None project = None script_path = None build_script_path = None source_root = None target = None system_root = None toolchain = None linker = None build_directory = None intermediate_directory = None module_cache_directory = None install_directory = None prefix = None swift_install = None pkg_config = None requires_pkg_config = False clang = None clangxx = None swift = None swiftc = None ar = None swift_sdk = None bootstrap_directory = None verbose = False extra_c_flags = None extra_swift_flags = None extra_ld_flags = None build_mode = None config_path = None # dont save this; else it would be recursive variables = {} def __init__(self): pass def _encode_path(self, path): if path is not None: return path.absolute() else: return None def write(self, path): info = { 'version' : self.version, 'command' : self.command, 'project' : self.project, 'script_path' : self._encode_path(self.script_path), 'build_script_path' : self._encode_path(self.build_script_path), 'source_root' : self._encode_path(self.source_root), 'target' : self.target.triple, 'system_root' : self._encode_path(self.system_root), 'toolchain' : self._encode_path(self.toolchain), 'linker' : self.linker, 'build_directory' : self._encode_path(self.build_directory), 'intermediate_directory' : self._encode_path(self.intermediate_directory), 'module_cache_directory' : self._encode_path(self.module_cache_directory), 'install_directory' : self._encode_path(self.install_directory), 'prefix' : self.prefix, 'swift_install' : self.swift_install, 'pkg_config' : self.pkg_config, 'requires_pkg_config' : self.requires_pkg_config, 'clang' : self.clang, 'clangxx' : self.clangxx, 'swift' : self.swift, 'swiftc' : self.swiftc, 'ar' : self.ar, 'swift_sdk' : self.swift_sdk, 'bootstrap_directory' : self._encode_path(self.bootstrap_directory), 'verbose' : self.verbose, 'extra_c_flags' : self.extra_c_flags, 'extra_swift_flags' : self.extra_swift_flags, 'extra_ld_flags' : self.extra_ld_flags, 'build_mode' : self.build_mode, 'variables' : self.variables, } with open(path, 'w+') as outfile: json.dump(info, outfile)
unknown
codeparrot/codeparrot-clean
// RUN: mkdir -p %t.dir/clang-tidy/list-checks/ // RUN: echo '{Checks: "-*,google-*"}' > %t.dir/clang-tidy/.clang-tidy // RUN: cd %t.dir/clang-tidy/list-checks // RUN: clang-tidy -list-checks | grep "^ *google-"
cpp
github
https://github.com/llvm/llvm-project
clang-tools-extra/test/clang-tidy/infrastructure/list-checks.cpp
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, _ from odoo.exceptions import UserError class ReportStockRule(models.AbstractModel): _name = 'report.stock.report_stock_rule' _description = 'Stock rule report' @api.model def _get_report_values(self, docids, data=None): product = self.env['product.product'].browse(data['product_id']) warehouses = self.env['stock.warehouse'].browse(data['warehouse_ids']) routes = self._get_routes(data) # Some routes don't have a warehouse_id but contain rules of different warehouses, # we filter here the ones we want to display and build for each one a dict containing the rule, # their source and destination location. relevant_rules = routes.mapped('rule_ids').filtered(lambda r: not r.warehouse_id or r.warehouse_id in warehouses) rules_and_loc = [] for rule in relevant_rules: rules_and_loc.append(self._get_rule_loc(rule, product)) locations = self._sort_locations(rules_and_loc, warehouses) reordering_rules = self.env['stock.warehouse.orderpoint'].search([('product_id', '=', product.id)]) locations |= reordering_rules.mapped('location_id').filtered(lambda l: l not in locations) locations_names = locations.mapped('display_name') # Here we handle reordering rules and putaway strategies by creating the header_lines dict. This dict is indexed # by location_id and contains itself another dict with the relevant reordering rules and putaway strategies. header_lines = {} for location in locations: # TODO: group the RR by location_id to avoid a filtered at each loop rr = reordering_rules.filtered(lambda r: r.location_id.id == location.id) putaways = product.putaway_rule_ids.filtered(lambda p: p.location_in_id.id == location.id) if putaways or rr: header_lines[location.id] = {'putaway': [], 'orderpoint': []} for putaway in putaways: header_lines[location.id]['putaway'].append(putaway) for r in rr: header_lines[location.id]['orderpoint'].append(r) route_lines = [] colors = self._get_route_colors() for color_index, route in enumerate(routes): rules_to_display = route.rule_ids & relevant_rules if rules_to_display: route_color = colors[color_index % len(colors)] color_index = color_index + 1 for rule in rules_to_display: rule_loc = [r for r in rules_and_loc if r['rule'] == rule][0] res = [] for x in range(len(locations_names)): res.append([]) idx = locations_names.index(rule_loc['destination'].display_name) tpl = (rule, 'destination', route_color, ) res[idx] = tpl idx = locations_names.index(rule_loc['source'].display_name) tpl = (rule, 'origin', route_color, ) res[idx] = tpl route_lines.append(res) return { 'docs': product, 'locations': locations, 'header_lines': header_lines, 'route_lines': route_lines, } @api.model def _get_route_colors(self): return ['#FFA500', '#800080', '#228B22', '#008B8B', '#4682B4', '#FF0000', '#32CD32'] @api.model def _get_routes(self, data): """ Extract the routes to display from the wizard's content. """ product = self.env['product.product'].browse(data['product_id']) warehouse_ids = self.env['stock.warehouse'].browse(data['warehouse_ids']) return product.route_ids | product.categ_id.total_route_ids | warehouse_ids.mapped('route_ids') @api.model def _get_rule_loc(self, rule, product): rule.ensure_one() return {'rule': rule, 'source': rule.location_src_id, 'destination': rule.location_id} @api.model def _sort_locations(self, rules_and_loc, warehouses): """ We order the locations by setting first the locations of type supplier and manufacture, then we add the locations grouped by warehouse and we finish by the locations of type customer and the ones that were not added by the sort. """ all_src = self.env['stock.location'].concat(*([r['source'] for r in rules_and_loc])) all_dest = self.env['stock.location'].concat(*([r['destination'] for r in rules_and_loc])) all_locations = all_src | all_dest ordered_locations = self.env['stock.location'] locations = all_locations.filtered(lambda l: l.usage in ('supplier', 'production')) for warehouse_id in warehouses: all_warehouse_locations = all_locations.filtered(lambda l: l.get_warehouse() == warehouse_id) starting_rules = [d for d in rules_and_loc if d['source'] not in all_warehouse_locations] if starting_rules: start_locations = self.env['stock.location'].concat(*([r['destination'] for r in starting_rules])) else: starting_rules = [d for d in rules_and_loc if d['source'] not in all_dest] start_locations = self.env['stock.location'].concat(*([r['source'] for r in starting_rules])) used_rules = self.env['stock.rule'] locations |= self._sort_locations_by_warehouse(rules_and_loc, used_rules, start_locations, ordered_locations, warehouse_id) if any(location not in locations for location in all_warehouse_locations): remaining_locations = self.env['stock.location'].concat(*([r['source'] for r in rules_and_loc])).filtered(lambda l: l not in locations) locations |= self._sort_locations_by_warehouse(rules_and_loc, used_rules, remaining_locations, ordered_locations, warehouse_id) locations |= all_locations.filtered(lambda l: l.usage in ('customer')) locations |= all_locations.filtered(lambda l: l not in locations) return locations @api.model def _sort_locations_by_warehouse(self, rules_and_loc, used_rules, start_locations, ordered_locations, warehouse_id): """ We order locations by putting first the locations that are not the destination of others and do it recursively. """ start_locations = start_locations.filtered(lambda l: l.get_warehouse() == warehouse_id) ordered_locations |= start_locations rules_start = [] for rule in rules_and_loc: if rule['source'] in start_locations: rules_start.append(rule) used_rules |= rule['rule'] if rules_start: rules_start_dest_locations = self.env['stock.location'].concat(*([r['destination'] for r in rules_start])) remaining_rules = self.env['stock.rule'].concat(*([r['rule'] for r in rules_and_loc])) - used_rules remaining_rules_location = self.env['stock.location'] for r in rules_and_loc: if r['rule'] in remaining_rules: remaining_rules_location |= r['destination'] start_locations = rules_start_dest_locations - ordered_locations - remaining_rules_location ordered_locations = self._sort_locations_by_warehouse(rules_and_loc, used_rules, start_locations, ordered_locations, warehouse_id) return ordered_locations
unknown
codeparrot/codeparrot-clean
#!/usr/bin/python # encoding: utf-8 # filename: apresentacaoDeTrabalho.py # # scriptLattes V8 # Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr. # http://scriptlattes.sourceforge.net/ # # # Este programa é um software livre; você pode redistribui-lo e/ou # modifica-lo dentro dos termos da Licença Pública Geral GNU como # publicada pela Fundação do Software Livre (FSF); na versão 2 da # Licença, ou (na sua opinião) qualquer versão. # # Este programa é distribuído na esperança que possa ser util, # mas SEM NENHUMA GARANTIA; sem uma garantia implicita de ADEQUAÇÂO a qualquer # MERCADO ou APLICAÇÃO EM PARTICULAR. Veja a # Licença Pública Geral GNU para maiores detalhes. # # Você deve ter recebido uma cópia da Licença Pública Geral GNU # junto com este programa, se não, escreva para a Fundação do Software # Livre(FSF) Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # from scriptLattes import * from scriptLattes.geradorDePaginasWeb import * import re from scriptLattes.util import compararCadeias class ApresentacaoDeTrabalho: item = None # dado bruto idMembro = None relevante = None autores = None titulo = None ano = None natureza = None # tipo de apresentacao chave = None def __init__(self, idMembro, partesDoItem='', relevante=''): self.idMembro = set([]) self.idMembro.add(idMembro) if not partesDoItem=='': # partesDoItem[0]: Numero (NAO USADO) # partesDoItem[1]: Descricao do livro (DADO BRUTO) self.relevante = relevante self.item = partesDoItem[1] # Dividir o item na suas partes constituintes partes = self.item.partition(" . ") self.autores = partes[0].strip() partes = partes[2] aux = re.findall(u' \((.*?)\)', partes) if len(aux)>0: self.natureza = aux[-1] partes = partes.rpartition(" (") partes = partes[0] else: self.natureza = '' aux = re.findall(u'. ((?:19|20)\d\d)\\b', partes) if len(aux)>0: self.ano = aux[-1] #.strip().rstrip(".").rstrip(",") partes = partes.rpartition(". ") partes = partes[0] else: self.ano = '' self.titulo = partes.strip().rstrip(".") self.chave = self.autores # chave de comparação entre os objetos else: self.relevante = '' self.autores = '' self.titulo = '' self.ano = '' self.natureza = '' def compararCom(self, objeto): if self.idMembro.isdisjoint(objeto.idMembro) and compararCadeias(self.titulo, objeto.titulo): # Os IDs dos membros são agrupados. # Essa parte é importante para a criação do GRAFO de colaborações self.idMembro.update(objeto.idMembro) if len(self.autores)<len(objeto.autores): self.autores = objeto.autores if len(self.titulo)<len(objeto.titulo): self.titulo = objeto.titulo if len(self.natureza)<len(objeto.natureza): self.natureza = objeto.natureza return self else: # nao similares return None def html(self, listaDeMembros): s = self.autores + '. <b>' + self.titulo + '</b>. ' s+= str(self.ano) + '. ' if str(self.ano).isdigit() else '. ' s+= self.natureza if not self.natureza=='' else '' # s+= menuHTMLdeBuscaPB(self.titulo) return s # ------------------------------------------------------------------------ # def __str__(self): s = "\n[APRESENTACAO DE TRABALHO] \n" s += "+ID-MEMBRO : " + str(self.idMembro) + "\n" s += "+RELEVANTE : " + str(self.relevante) + "\n" s += "+AUTORES : " + self.autores.encode('utf8','replace') + "\n" s += "+TITULO : " + self.titulo.encode('utf8','replace') + "\n" s += "+ANO : " + str(self.ano) + "\n" s += "+NATUREZA : " + self.natureza.encode('utf8','replace') + "\n" s += "+item : " + self.item.encode('utf8','replace') + "\n" return s
unknown
codeparrot/codeparrot-clean
# -*- coding: utf-8 -*- """Tests for website.addons.box.utils.""" import mock from nose.tools import * # noqa (PEP8 asserts) from framework.auth import Auth from website.project.model import NodeLog from tests.factories import ProjectFactory from website.addons.box.tests.factories import BoxFileFactory from website.addons.box.tests.utils import BoxAddonTestCase from website.addons.box import utils from website.addons.box.views.config import serialize_folder from website.addons.box.model import BoxNodeSettings class TestNodeLogger(BoxAddonTestCase): def test_log_file_added(self): df = BoxFileFactory() logger = utils.BoxNodeLogger( node=self.project, auth=Auth(self.user), file_obj=df ) logger.log(NodeLog.FILE_ADDED, save=True) last_log = self.project.logs[-1] assert_equal(last_log.action, "box_{0}".format(NodeLog.FILE_ADDED)) # Regression test for https://github.com/CenterForOpenScience/osf.io/issues/1557 def test_log_deauthorized_when_node_settings_are_deleted(self): project = ProjectFactory() project.add_addon('box', auth=Auth(project.creator)) dbox_settings = project.get_addon('box') dbox_settings.delete(save=True) # sanity check assert_true(dbox_settings.deleted) logger = utils.BoxNodeLogger(node=project, auth=Auth(self.user)) logger.log(action='node_deauthorized', save=True) last_log = project.logs[-1] assert_equal(last_log.action, 'box_node_deauthorized') # FIXME(sloria): This test is incorrect. The mocking needs work. # class TestRenderFile(OsfTestCase): # @mock.patch('website.addons.box.client.BoxClient.get_file_and_metadata') # def test_render_box_file_when_file_has_taken_down_by_dmca(self, mock_get_file): # mock_resp = mock.Mock(spec=BoxResponse) # mock_resp.reason = 'This file is no longer available due to a takedown request under the Digital Millennium Copyright Act' # mock_resp.status = 461 # mock_client = mock.Mock(spec=BoxClient) # mock_client.get_file_and_metadata.side_effect = ErrorResponse(mock_resp, 'DMCA takedown') # with patch_client('website.addons.box.utils.get_node_addon_client', mock_client=mock_client): # f = BoxFileFactory() # result = utils.render_box_file(f, client=mock_client) # TODO(mfraezz): Add support for folder sharing urls # def test_get_share_folder_uri(): # expected = 'https://box.com/home/foo?shareoptions=1&share_subfolder=0&share=1' # assert_equal(utils.get_share_folder_uri('/foo/'), expected) # assert_equal(utils.get_share_folder_uri('foo'), expected) def test_serialize_folder(): metadata = { u'bytes': 0, u'icon': u'folder', u'is_dir': True, u'modified': u'Sat, 22 Mar 2014 05:40:29 +0000', u'path': u'/datasets/New Folder', u'rev': u'3fed51f002c12fc', u'revision': 67032351, u'root': u'box', u'size': u'0 bytes', u'thumb_exists': False } result = serialize_folder(metadata) assert_equal(result['path'], metadata['path']) assert_equal(result['name'], 'Box' + metadata['path']) class TestBoxAddonFolder(BoxAddonTestCase): @mock.patch.object(BoxNodeSettings, 'fetch_folder_name', lambda self: 'foo') def test_works(self): folder = utils.box_addon_folder( self.node_settings, Auth(self.user)) assert_true(isinstance(folder, list)) assert_true(isinstance(folder[0], dict)) def test_returns_none_unconfigured(self): self.node_settings.folder_id = None assert_is(utils.box_addon_folder( self.node_settings, Auth(self.user)), None)
unknown
codeparrot/codeparrot-clean
# frozen_string_literal: true class DrinkDesigner < ActiveRecord::Base has_one :chef, as: :employable accepts_nested_attributes_for :chef end class DrinkDesignerWithPolymorphicDependentNullifyChef < ActiveRecord::Base self.table_name = "drink_designers" has_one :chef, as: :employable, dependent: :nullify end class DrinkDesignerWithPolymorphicTouchChef < ActiveRecord::Base self.table_name = "drink_designers" has_one :chef, as: :employable, touch: true end class MocktailDesigner < DrinkDesigner end
ruby
github
https://github.com/rails/rails
activerecord/test/models/drink_designer.rb
# Copyright 2017 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import itertools from ..testproc.base import ( DROP_RESULT, DROP_OUTPUT, DROP_PASS_OUTPUT, DROP_PASS_STDOUT) from ..local import statusfile from ..testproc.result import Result OUTCOMES_PASS = [statusfile.PASS] OUTCOMES_FAIL = [statusfile.FAIL] OUTCOMES_PASS_OR_TIMEOUT = [statusfile.PASS, statusfile.TIMEOUT] OUTCOMES_FAIL_OR_TIMEOUT = [statusfile.FAIL, statusfile.TIMEOUT] class BaseOutProc(object): def process(self, output, reduction=None): has_unexpected_output = self.has_unexpected_output(output) return self._create_result(has_unexpected_output, output, reduction) def has_unexpected_output(self, output): return self.get_outcome(output) not in self.expected_outcomes def _create_result(self, has_unexpected_output, output, reduction): """Creates Result instance. When reduction is passed it tries to drop some parts of the result to save memory and time needed to send the result across process boundary. None disables reduction and full result is created. """ if reduction == DROP_RESULT: return None if reduction == DROP_OUTPUT: return Result(has_unexpected_output, None) if not has_unexpected_output: if reduction == DROP_PASS_OUTPUT: return Result(has_unexpected_output, None) if reduction == DROP_PASS_STDOUT: return Result(has_unexpected_output, output.without_text()) return Result(has_unexpected_output, output) def get_outcome(self, output): if output.HasCrashed(): return statusfile.CRASH elif output.HasTimedOut(): return statusfile.TIMEOUT elif self._has_failed(output): return statusfile.FAIL else: return statusfile.PASS def _has_failed(self, output): execution_failed = self._is_failure_output(output) if self.negative: return not execution_failed return execution_failed def _is_failure_output(self, output): return output.exit_code != 0 @property def negative(self): return False @property def expected_outcomes(self): raise NotImplementedError() class Negative(object): @property def negative(self): return True class PassOutProc(BaseOutProc): """Output processor optimized for positive tests expected to PASS.""" def has_unexpected_output(self, output): return self.get_outcome(output) != statusfile.PASS @property def expected_outcomes(self): return OUTCOMES_PASS class NegPassOutProc(Negative, PassOutProc): """Output processor optimized for negative tests expected to PASS""" pass class OutProc(BaseOutProc): """Output processor optimized for positive tests with expected outcomes different than a single PASS. """ def __init__(self, expected_outcomes): self._expected_outcomes = expected_outcomes @property def expected_outcomes(self): return self._expected_outcomes # TODO(majeski): Inherit from PassOutProc in case of OUTCOMES_PASS and remove # custom get/set state. def __getstate__(self): d = self.__dict__ if self._expected_outcomes is OUTCOMES_PASS: d = d.copy() del d['_expected_outcomes'] return d def __setstate__(self, d): if '_expected_outcomes' not in d: d['_expected_outcomes'] = OUTCOMES_PASS self.__dict__.update(d) # TODO(majeski): Override __reduce__ to make it deserialize as one instance. DEFAULT = PassOutProc() DEFAULT_NEGATIVE = NegPassOutProc() class ExpectedOutProc(OutProc): """Output processor that has is_failure_output depending on comparing the output with the expected output. """ def __init__(self, expected_outcomes, expected_filename): super(ExpectedOutProc, self).__init__(expected_outcomes) self._expected_filename = expected_filename def _is_failure_output(self, output): with open(self._expected_filename, 'r') as f: expected_lines = f.readlines() for act_iterator in self._act_block_iterator(output): for expected, actual in itertools.izip_longest( self._expected_iterator(expected_lines), act_iterator, fillvalue='' ): if expected != actual: return True return False def _act_block_iterator(self, output): """Iterates over blocks of actual output lines.""" lines = output.stdout.splitlines() start_index = 0 found_eqeq = False for index, line in enumerate(lines): # If a stress test separator is found: if line.startswith('=='): # Iterate over all lines before a separator except the first. if not found_eqeq: found_eqeq = True else: yield self._actual_iterator(lines[start_index:index]) # The next block of output lines starts after the separator. start_index = index + 1 # Iterate over complete output if no separator was found. if not found_eqeq: yield self._actual_iterator(lines) def _actual_iterator(self, lines): return self._iterator(lines, self._ignore_actual_line) def _expected_iterator(self, lines): return self._iterator(lines, self._ignore_expected_line) def _ignore_actual_line(self, line): """Ignore empty lines, valgrind output, Android output and trace incremental marking output. """ if not line: return True return (line.startswith('==') or line.startswith('**') or line.startswith('ANDROID') or line.startswith('###') or # FIXME(machenbach): The test driver shouldn't try to use slow # asserts if they weren't compiled. This fails in optdebug=2. line == 'Warning: unknown flag --enable-slow-asserts.' or line == 'Try --help for options') def _ignore_expected_line(self, line): return not line def _iterator(self, lines, ignore_predicate): for line in lines: line = line.strip() if not ignore_predicate(line): yield line
unknown
codeparrot/codeparrot-clean
from __future__ import division import random import tempfile from twisted.internet import defer, reactor from twisted.trial import unittest from twisted.web import client, resource, server from p2pool import data, node, work from p2pool.bitcoin import data as bitcoin_data, networks, worker_interface from p2pool.util import deferral, jsonrpc, math, variable class bitcoind(object): # can be used as p2p factory, p2p protocol, or rpc jsonrpc proxy def __init__(self): self.blocks = [0x000000000000016c169477c25421250ec5d32cf9c6d38538b5de970a2355fd89] self.headers = {0x16c169477c25421250ec5d32cf9c6d38538b5de970a2355fd89: { 'nonce': 1853158954, 'timestamp': 1351658517, 'merkle_root': 2282849479936278423916707524932131168473430114569971665822757638339486597658L, 'version': 1, 'previous_block': 1048610514577342396345362905164852351970507722694242579238530L, 'bits': bitcoin_data.FloatingInteger(bits=0x1a0513c5, target=0x513c50000000000000000000000000000000000000000000000L), }} self.conn = variable.Variable(self) self.new_headers = variable.Event() self.new_block = variable.Event() self.new_tx = variable.Event() # p2p factory def getProtocol(self): return self # p2p protocol def send_block(self, block): pass def send_tx(self, tx): pass def get_block_header(self, block_hash): return self.headers[block_hash] # rpc jsonrpc proxy def rpc_help(self): return '\ngetblock ' def rpc_getblock(self, block_hash_hex): block_hash = int(block_hash_hex, 16) return dict(height=self.blocks.index(block_hash)) def rpc_getmemorypool(self, result=None): if result is not None: block = bitcoin_data.block_type.unpack(result.decode('hex')) if sum(tx_out['value'] for tx_out in block['txs'][0]['tx_outs']) != sum(tx['tx_outs'][0]['value'] for tx in block['txs'][1:]) + 5000000000: print 'invalid fee' if block['header']['previous_block'] != self.blocks[-1]: return False if bitcoin_data.hash256(result.decode('hex')) > block['header']['bits'].target: return False header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(block['header'])) self.blocks.append(header_hash) self.headers[header_hash] = block['header'] reactor.callLater(0, self.new_block.happened) return True txs = [] for i in xrange(100): fee = i txs.append(dict( data=bitcoin_data.tx_type.pack(dict(version=1, tx_ins=[], tx_outs=[dict(value=fee*1000 + i, script='hello!'*100)], lock_time=0)).encode('hex'), fee=fee, )) return { "version" : 2, "previousblockhash" : '%064x' % (self.blocks[-1],), "transactions" : txs, "coinbaseaux" : { "flags" : "062f503253482f" }, "coinbasevalue" : 5000000000 + sum(tx['fee'] for tx in txs), "target" : "0000000000000513c50000000000000000000000000000000000000000000000", "mintime" : 1351655621, "mutable" : [ "time", "transactions", "prevblock" ], "noncerange" : "00000000ffffffff", "sigoplimit" : 20000, "sizelimit" : 1000000, "curtime" : 1351659940, "bits" : "21008000", "height" : len(self.blocks), } @apply class mm_provider(object): def __getattr__(self, name): print '>>>>>>>', name def rpc_getauxblock(self, request, result1=None, result2=None): if result1 is not None: print result1, result2 return True return { "target" : "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", # 2**256*2/3 "hash" : "2756ea0315d46dc3d8d974f34380873fc88863845ac01a658ef11bc3b368af52", "chainid" : 1 } mynet = math.Object( PARENT=networks.nets['litecoin_testnet'], SHARE_PERIOD=3, # seconds CHAIN_LENGTH=20*60//3, # shares REAL_CHAIN_LENGTH=20*60//3, # shares TARGET_LOOKBEHIND=200, # shares SPREAD=12, # blocks IDENTIFIER='cca5e24ec6408b1e'.decode('hex'), PREFIX='ad9614f6466a39cf'.decode('hex'), P2P_PORT=19338, MIN_TARGET=2**256 - 1, MAX_TARGET=2**256 - 1, PERSIST=False, WORKER_PORT=19327, BOOTSTRAP_ADDRS='72.14.191.28'.split(' '), ANNOUNCE_CHANNEL='#p2pool-alt', VERSION_CHECK=lambda v: True, ) class MiniNode(object): @classmethod @defer.inlineCallbacks def start(cls, net, factory, bitcoind, peer_ports, merged_urls): self = cls() self.n = node.Node(factory, bitcoind, [], [], net) yield self.n.start() self.n.p2p_node = node.P2PNode(self.n, port=0, max_incoming_conns=1000000, addr_store={}, connect_addrs=[('127.0.0.1', peer_port) for peer_port in peer_ports]) self.n.p2p_node.start() wb = work.WorkerBridge(node=self.n, my_pubkey_hash=random.randrange(2**160), donation_percentage=random.uniform(0, 10), merged_urls=merged_urls, worker_fee=3) self.wb = wb web_root = resource.Resource() worker_interface.WorkerInterface(wb).attach_to(web_root) self.web_port = reactor.listenTCP(0, server.Site(web_root)) defer.returnValue(self) @defer.inlineCallbacks def stop(self): yield self.web_port.stopListening() yield self.n.p2p_node.stop() yield self.n.stop() del self.web_port, self.n class Test(unittest.TestCase): @defer.inlineCallbacks def test_node(self): bitd = bitcoind() mm_root = resource.Resource() mm_root.putChild('', jsonrpc.HTTPServer(mm_provider)) mm_port = reactor.listenTCP(0, server.Site(mm_root)) n = node.Node(bitd, bitd, [], [], mynet) yield n.start() wb = work.WorkerBridge(node=n, my_pubkey_hash=42, donation_percentage=2, merged_urls=[('http://127.0.0.1:%i' % (mm_port.getHost().port,), '')], worker_fee=3) web_root = resource.Resource() worker_interface.WorkerInterface(wb).attach_to(web_root) port = reactor.listenTCP(0, server.Site(web_root)) proxy = jsonrpc.HTTPProxy('http://127.0.0.1:' + str(port.getHost().port)) yield deferral.sleep(3) for i in xrange(100): blah = yield proxy.rpc_getwork() yield proxy.rpc_getwork(blah['data']) yield deferral.sleep(3) assert len(n.tracker.items) == 100 assert n.tracker.verified.get_height(n.best_share_var.value) == 100 wb.stop() n.stop() yield port.stopListening() del n, wb, web_root, port, proxy import gc gc.collect() gc.collect() gc.collect() yield deferral.sleep(20) # waiting for work_poller to exit yield mm_port.stopListening() #test_node.timeout = 15 @defer.inlineCallbacks def test_nodes(self): N = 3 SHARES = 600 bitd = bitcoind() nodes = [] for i in xrange(N): nodes.append((yield MiniNode.start(mynet, bitd, bitd, [mn.n.p2p_node.serverfactory.listen_port.getHost().port for mn in nodes], []))) yield deferral.sleep(3) for i in xrange(SHARES): proxy = jsonrpc.HTTPProxy('http://127.0.0.1:' + str(random.choice(nodes).web_port.getHost().port)) blah = yield proxy.rpc_getwork() yield proxy.rpc_getwork(blah['data']) yield deferral.sleep(.05) print i print type(nodes[0].n.tracker.items[nodes[0].n.best_share_var.value]) # crawl web pages from p2pool import web stop_event = variable.Event() web2_root = web.get_web_root(nodes[0].wb, tempfile.mkdtemp(), variable.Variable(None), stop_event) web2_port = reactor.listenTCP(0, server.Site(web2_root)) for name in web2_root.listNames() + ['web/' + x for x in web2_root.getChildWithDefault('web', None).listNames()]: if name in ['web/graph_data', 'web/share', 'web/share_data']: continue print print name try: res = yield client.getPage('http://127.0.0.1:%i/%s' % (web2_port.getHost().port, name)) except: import traceback traceback.print_exc() else: print repr(res)[:100] print yield web2_port.stopListening() stop_event.happened() del web2_root yield deferral.sleep(3) for i, n in enumerate(nodes): assert len(n.n.tracker.items) == SHARES, (i, len(n.n.tracker.items)) assert n.n.tracker.verified.get_height(n.n.best_share_var.value) == SHARES, (i, n.n.tracker.verified.get_height(n.n.best_share_var.value)) assert type(n.n.tracker.items[nodes[0].n.best_share_var.value]) is data.Share assert type(n.n.tracker.items[n.n.tracker.get_nth_parent_hash(nodes[0].n.best_share_var.value, SHARES - 5)]) is data.Share for n in nodes: yield n.stop() del nodes, n import gc gc.collect() gc.collect() gc.collect() yield deferral.sleep(20) # waiting for work_poller to exit test_nodes.timeout = 300
unknown
codeparrot/codeparrot-clean
# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function import numpy as np from skbio.tree import DuplicateNodeError, MissingNodeError def _validate_counts_vector(counts, suppress_cast=False): """Validate and convert input to an acceptable counts vector type. Note: may not always return a copy of `counts`! """ counts = np.asarray(counts) if not suppress_cast: counts = counts.astype(int, casting='safe', copy=False) if counts.ndim != 1: raise ValueError("Only 1-D vectors are supported.") elif (counts < 0).any(): raise ValueError("Counts vector cannot contain negative values.") return counts def _validate_counts_vectors(*args, **kwargs): results = [] lens = [] # py2-compatible mechanism for specifying a keyword argument when also # passing *args derived from SO answer: # http://stackoverflow.com/a/15302038/3424666 suppress_cast = kwargs.pop('suppress_cast', False) for counts in args: results.append(_validate_counts_vector(counts, suppress_cast)) lens.append(len(counts)) if len(set(lens)) > 1: raise ValueError("Input vectors u_counts and v_counts must be of " "equal length.") return results def _validate_otu_ids_and_tree(counts, otu_ids, tree): # all otu_ids are unique # len(otu_ids) == len(counts) len_otu_ids = len(otu_ids) set_otu_ids = set(otu_ids) if len_otu_ids != len(set_otu_ids): raise ValueError("OTU IDs vector cannot contain duplicated ids.") if len(counts) != len_otu_ids: raise ValueError("OTU IDs vector must be the same length as counts " "vector(s).") # the tree is rooted if len(tree.root().children) > 2: # this is an imperfect check for whether the tree is rooted or not. # can this be improved? raise ValueError("Tree must be rooted.") # all nodes (except the root node) have corresponding branch lengths # all tip names in tree are unique # all otu_ids correspond to tip names in tree branch_lengths = [] tip_names = [] for e in tree.traverse(): if not e.is_root(): branch_lengths.append(e.length) if e.is_tip(): tip_names.append(e.name) set_tip_names = set(tip_names) if len(tip_names) != len(set_tip_names): raise DuplicateNodeError("All tip names must be unique.") if np.array([l is None for l in branch_lengths]).any(): raise ValueError("All non-root nodes in tree must have a branch " "length.") missing_tip_names = set_otu_ids - set_tip_names if missing_tip_names != set(): raise MissingNodeError("All otu_ids must be present as tip names in " "tree. Tree is missing tips with names: %s" % " ".join(missing_tip_names))
unknown
codeparrot/codeparrot-clean
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2006, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // // class RationalAttribute // //----------------------------------------------------------------------------- #include <ImfRationalAttribute.h> OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER using namespace OPENEXR_IMF_INTERNAL_NAMESPACE; template <> const char * RationalAttribute::staticTypeName () { return "rational"; } template <> void RationalAttribute::writeValueTo (OPENEXR_IMF_INTERNAL_NAMESPACE::OStream &os, int version) const { Xdr::write <StreamIO> (os, _value.n); Xdr::write <StreamIO> (os, _value.d); } template <> void RationalAttribute::readValueFrom (OPENEXR_IMF_INTERNAL_NAMESPACE::IStream &is, int size, int version) { Xdr::read <StreamIO> (is, _value.n); Xdr::read <StreamIO> (is, _value.d); } OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_EXIT
cpp
github
https://github.com/opencv/opencv
3rdparty/openexr/IlmImf/ImfRationalAttribute.cpp
# frozen_string_literal: true require "helper" class TestTagInclude < TagUnitTest context "include tag with parameters" do context "with symlink'd include" do should "not allow symlink includes" do FileUtils.mkdir_p("tmp") File.write("tmp/pages-test", "SYMLINK TEST") assert_raises IOError do content = <<~CONTENT --- title: Include symlink --- {% include tmp/pages-test %} CONTENT render_content(content, "safe" => true) end @result ||= "" refute_match(%r!SYMLINK TEST!, @result) end should "not expose the existence of symlinked files" do ex = assert_raises IOError do content = <<~CONTENT --- title: Include symlink --- {% include tmp/pages-test-does-not-exist %} CONTENT render_content(content, "safe" => true) end assert_match( "Could not locate the included file 'tmp/pages-test-does-not-exist' in any of " \ "[\"#{source_dir}/_includes\"]. Ensure it exists in one of those directories and is " \ "not a symlink as those are not allowed in safe mode.", ex.message ) end end context "with one parameter" do setup do content = <<~CONTENT --- title: Include tag parameters --- {% include sig.markdown myparam="test" %} {% include params.html param="value" %} CONTENT render_content(content) end should "correctly output include variable" do assert_match "<span id=\"include-param\">value</span>", @result.strip end should "ignore parameters if unused" do assert_match "<hr />\n<p>Tom Preston-Werner\ngithub.com/mojombo</p>\n", @result end end context "with simple syntax but multiline markup" do setup do content = <<~CONTENT --- title: Include tag parameters --- {% include sig.markdown myparam="test" %} {% include params.html param="value" %} CONTENT render_content(content) end should "correctly output include variable" do assert_match "<span id=\"include-param\">value</span>", @result.strip end should "ignore parameters if unused" do assert_match "<hr />\n<p>Tom Preston-Werner\ngithub.com/mojombo</p>\n", @result end end context "with variable syntax but multiline markup" do setup do content = <<~CONTENT --- title: Include tag parameters --- {% include sig.markdown myparam="test" %} {% assign path = "params" | append: ".html" %} {% include {{ path }} param="value" %} CONTENT render_content(content) end should "correctly output include variable" do assert_match "<span id=\"include-param\">value</span>", @result.strip end should "ignore parameters if unused" do assert_match "<hr />\n<p>Tom Preston-Werner\ngithub.com/mojombo</p>\n", @result end end context "with invalid parameter syntax" do should "throw a ArgumentError" do content = <<~CONTENT --- title: Invalid parameter syntax --- {% include params.html param s="value" %} CONTENT assert_raises ArgumentError, %(Did not raise exception on invalid "include" syntax) do render_content(content) end content = <<~CONTENT --- title: Invalid parameter syntax --- {% include params.html params="value %} CONTENT assert_raises ArgumentError, %(Did not raise exception on invalid "include" syntax) do render_content(content) end end end context "with several parameters" do setup do content = <<~CONTENT --- title: multiple include parameters --- {% include params.html param1="new_value" param2="another" %} CONTENT render_content(content) end should "list all parameters" do assert_match "<li>param1 = new_value</li>", @result assert_match "<li>param2 = another</li>", @result end should "not include previously used parameters" do assert_match "<span id=\"include-param\"></span>", @result end end context "without parameters" do setup do content = <<~CONTENT --- title: without parameters --- {% include params.html %} CONTENT render_content(content) end should "include file with empty parameters" do assert_match "<span id=\"include-param\"></span>", @result end end context "with include file with special characters without params" do setup do content = <<~CONTENT --- title: special characters --- {% include params@2.0.html %} CONTENT render_content(content) end should "include file with empty parameters" do assert_match "<span id=\"include-param\"></span>", @result end end context "with include file with special characters with params" do setup do content = <<~CONTENT --- title: special characters --- {% include params@2.0.html param1="foobar" param2="bazbar" %} CONTENT render_content(content) end should "include file with empty parameters" do assert_match "<li>param1 = foobar</li>", @result assert_match "<li>param2 = bazbar</li>", @result end end context "with custom includes directory" do setup do content = <<~CONTENT --- title: custom includes directory --- {% include custom.html %} CONTENT render_content(content, "includes_dir" => "_includes_custom") end should "include file from custom directory" do assert_match "custom_included", @result end end context "without parameters within if statement" do setup do content = <<~CONTENT --- title: without parameters within if statement --- {% if true %}{% include params.html %}{% endif %} CONTENT render_content(content) end should "include file with empty parameters within if statement" do assert_match "<span id=\"include-param\"></span>", @result end end context "include missing file" do setup do @content = <<~CONTENT --- title: missing file --- {% include missing.html %} CONTENT end should "raise error relative to source directory" do exception = assert_raises IOError do render_content(@content) end assert_match( "Could not locate the included file 'missing.html' in any of " \ "[\"#{source_dir}/_includes\"].", exception.message ) end end context "include tag with variable and liquid filters" do setup do site = fixture_site.tap do |s| s.read s.render end post = site.posts.docs.find do |p| p.basename.eql? "2013-12-17-include-variable-filters.markdown" end @content = post.output end should "include file as variable with liquid filters" do assert_match(%r!1 included!, @content) assert_match(%r!2 included!, @content) assert_match(%r!3 included!, @content) end should "include file as variable and liquid filters with arbitrary whitespace" do assert_match(%r!4 included!, @content) assert_match(%r!5 included!, @content) assert_match(%r!6 included!, @content) end should "include file as variable and filters with additional parameters" do assert_match("<li>var1 = foo</li>", @content) assert_match("<li>var2 = bar</li>", @content) end should "include file as partial variable" do assert_match(%r!8 included!, @content) end end end end
ruby
github
https://github.com/jekyll/jekyll
test/test_tag_include.rb
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for distributions KL mechanism.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.distributions.python.ops import kullback_leibler from tensorflow.contrib.distributions.python.ops import normal from tensorflow.python.ops import array_ops from tensorflow.python.platform import test # pylint: disable=protected-access _DIVERGENCES = kullback_leibler._DIVERGENCES _registered_kl = kullback_leibler._registered_kl # pylint: enable=protected-access class KLTest(test.TestCase): def testRegistration(self): class MyDist(normal.Normal): pass # Register KL to a lambda that spits out the name parameter @kullback_leibler.RegisterKL(MyDist, MyDist) def _kl(a, b, name=None): # pylint: disable=unused-argument,unused-variable return name a = MyDist(loc=0.0, scale=1.0) self.assertEqual("OK", kullback_leibler.kl(a, a, name="OK")) def testDomainErrorExceptions(self): class MyDistException(normal.Normal): pass # Register KL to a lambda that spits out the name parameter @kullback_leibler.RegisterKL(MyDistException, MyDistException) # pylint: disable=unused-argument,unused-variable def _kl(a, b, name=None): return array_ops.identity([float("nan")]) # pylint: disable=unused-argument,unused-variable with self.test_session(): a = MyDistException(loc=0.0, scale=1.0) kl = kullback_leibler.kl(a, a, allow_nan_stats=False) with self.assertRaisesOpError( "KL calculation between .* and .* returned NaN values"): kl.eval() kl_ok = kullback_leibler.kl(a, a) self.assertAllEqual([float("nan")], kl_ok.eval()) def testRegistrationFailures(self): class MyDist(normal.Normal): pass with self.assertRaisesRegexp(TypeError, "must be callable"): kullback_leibler.RegisterKL(MyDist, MyDist)("blah") # First registration is OK kullback_leibler.RegisterKL(MyDist, MyDist)(lambda a, b: None) # Second registration fails with self.assertRaisesRegexp(ValueError, "has already been registered"): kullback_leibler.RegisterKL(MyDist, MyDist)(lambda a, b: None) def testExactRegistrationsAllMatch(self): for (k, v) in _DIVERGENCES.items(): self.assertEqual(v, _registered_kl(*k)) def testIndirectRegistration(self): class Sub1(normal.Normal): pass class Sub2(normal.Normal): pass class Sub11(Sub1): pass # pylint: disable=unused-argument,unused-variable @kullback_leibler.RegisterKL(Sub1, Sub1) def _kl11(a, b, name=None): return "sub1-1" @kullback_leibler.RegisterKL(Sub1, Sub2) def _kl12(a, b, name=None): return "sub1-2" @kullback_leibler.RegisterKL(Sub2, Sub1) def _kl21(a, b, name=None): return "sub2-1" # pylint: enable=unused-argument,unused_variable sub1 = Sub1(loc=0.0, scale=1.0) sub2 = Sub2(loc=0.0, scale=1.0) sub11 = Sub11(loc=0.0, scale=1.0) self.assertEqual("sub1-1", kullback_leibler.kl(sub1, sub1)) self.assertEqual("sub1-2", kullback_leibler.kl(sub1, sub2)) self.assertEqual("sub2-1", kullback_leibler.kl(sub2, sub1)) self.assertEqual("sub1-1", kullback_leibler.kl(sub11, sub11)) self.assertEqual("sub1-1", kullback_leibler.kl(sub11, sub1)) self.assertEqual("sub1-2", kullback_leibler.kl(sub11, sub2)) self.assertEqual("sub1-1", kullback_leibler.kl(sub11, sub1)) self.assertEqual("sub1-2", kullback_leibler.kl(sub11, sub2)) self.assertEqual("sub2-1", kullback_leibler.kl(sub2, sub11)) self.assertEqual("sub1-1", kullback_leibler.kl(sub1, sub11)) if __name__ == "__main__": test.main()
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env python3 # Copyright (c) 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import re import fnmatch import sys import subprocess import datetime import os ################################################################################ # file filtering ################################################################################ EXCLUDE = [ # libsecp256k1: 'src/secp256k1/include/secp256k1.h', 'src/secp256k1/include/secp256k1_ecdh.h', 'src/secp256k1/include/secp256k1_recovery.h', 'src/secp256k1/include/secp256k1_schnorr.h', 'src/secp256k1/src/java/org_bitcoin_NativeSecp256k1.c', 'src/secp256k1/src/java/org_bitcoin_NativeSecp256k1.h', 'src/secp256k1/src/java/org_bitcoin_Secp256k1Context.c', 'src/secp256k1/src/java/org_bitcoin_Secp256k1Context.h', # univalue: 'src/univalue/test/object.cpp', 'src/univalue/lib/univalue_escapes.h', # auto generated: 'src/qt/bitcoinstrings.cpp', 'src/chainparamsseeds.h', # other external copyrights: 'src/tinyformat.h', 'src/leveldb/util/env_win.cc', 'src/crypto/ctaes/bench.c', 'test/functional/test_framework/bignum.py', # python init: '*__init__.py', ] EXCLUDE_COMPILED = re.compile('|'.join([fnmatch.translate(m) for m in EXCLUDE])) INCLUDE = ['*.h', '*.cpp', '*.cc', '*.c', '*.py'] INCLUDE_COMPILED = re.compile('|'.join([fnmatch.translate(m) for m in INCLUDE])) def applies_to_file(filename): return ((EXCLUDE_COMPILED.match(filename) is None) and (INCLUDE_COMPILED.match(filename) is not None)) ################################################################################ # obtain list of files in repo according to INCLUDE and EXCLUDE ################################################################################ GIT_LS_CMD = 'git ls-files' def call_git_ls(): out = subprocess.check_output(GIT_LS_CMD.split(' ')) return [f for f in out.decode("utf-8").split('\n') if f != ''] def get_filenames_to_examine(): filenames = call_git_ls() return sorted([filename for filename in filenames if applies_to_file(filename)]) ################################################################################ # define and compile regexes for the patterns we are looking for ################################################################################ COPYRIGHT_WITH_C = 'Copyright \(c\)' COPYRIGHT_WITHOUT_C = 'Copyright' ANY_COPYRIGHT_STYLE = '(%s|%s)' % (COPYRIGHT_WITH_C, COPYRIGHT_WITHOUT_C) YEAR = "20[0-9][0-9]" YEAR_RANGE = '(%s)(-%s)?' % (YEAR, YEAR) YEAR_LIST = '(%s)(, %s)+' % (YEAR, YEAR) ANY_YEAR_STYLE = '(%s|%s)' % (YEAR_RANGE, YEAR_LIST) ANY_COPYRIGHT_STYLE_OR_YEAR_STYLE = ("%s %s" % (ANY_COPYRIGHT_STYLE, ANY_YEAR_STYLE)) ANY_COPYRIGHT_COMPILED = re.compile(ANY_COPYRIGHT_STYLE_OR_YEAR_STYLE) def compile_copyright_regex(copyright_style, year_style, name): return re.compile('%s %s %s' % (copyright_style, year_style, name)) EXPECTED_HOLDER_NAMES = [ "Satoshi Nakamoto\n", "The Bitcoin Core developers\n", "The Bitcoin Core developers \n", "Bitcoin Core Developers\n", "the Bitcoin Core developers\n", "The Bitcoin developers\n", "The LevelDB Authors\. All rights reserved\.\n", "BitPay Inc\.\n", "BitPay, Inc\.\n", "University of Illinois at Urbana-Champaign\.\n", "MarcoFalke\n", "Pieter Wuille\n", "Pieter Wuille +\*\n", "Pieter Wuille, Gregory Maxwell +\*\n", "Pieter Wuille, Andrew Poelstra +\*\n", "Andrew Poelstra +\*\n", "Wladimir J. van der Laan\n", "Jeff Garzik\n", "Diederik Huys, Pieter Wuille +\*\n", "Thomas Daede, Cory Fields +\*\n", "Jan-Klaas Kollhof\n", "Sam Rushing\n", "ArtForz -- public domain half-a-node\n", ] DOMINANT_STYLE_COMPILED = {} YEAR_LIST_STYLE_COMPILED = {} WITHOUT_C_STYLE_COMPILED = {} for holder_name in EXPECTED_HOLDER_NAMES: DOMINANT_STYLE_COMPILED[holder_name] = ( compile_copyright_regex(COPYRIGHT_WITH_C, YEAR_RANGE, holder_name)) YEAR_LIST_STYLE_COMPILED[holder_name] = ( compile_copyright_regex(COPYRIGHT_WITH_C, YEAR_LIST, holder_name)) WITHOUT_C_STYLE_COMPILED[holder_name] = ( compile_copyright_regex(COPYRIGHT_WITHOUT_C, ANY_YEAR_STYLE, holder_name)) ################################################################################ # search file contents for copyright message of particular category ################################################################################ def get_count_of_copyrights_of_any_style_any_holder(contents): return len(ANY_COPYRIGHT_COMPILED.findall(contents)) def file_has_dominant_style_copyright_for_holder(contents, holder_name): match = DOMINANT_STYLE_COMPILED[holder_name].search(contents) return match is not None def file_has_year_list_style_copyright_for_holder(contents, holder_name): match = YEAR_LIST_STYLE_COMPILED[holder_name].search(contents) return match is not None def file_has_without_c_style_copyright_for_holder(contents, holder_name): match = WITHOUT_C_STYLE_COMPILED[holder_name].search(contents) return match is not None ################################################################################ # get file info ################################################################################ def read_file(filename): return open(os.path.abspath(filename), 'r').read() def gather_file_info(filename): info = {} info['filename'] = filename c = read_file(filename) info['contents'] = c info['all_copyrights'] = get_count_of_copyrights_of_any_style_any_holder(c) info['classified_copyrights'] = 0 info['dominant_style'] = {} info['year_list_style'] = {} info['without_c_style'] = {} for holder_name in EXPECTED_HOLDER_NAMES: has_dominant_style = ( file_has_dominant_style_copyright_for_holder(c, holder_name)) has_year_list_style = ( file_has_year_list_style_copyright_for_holder(c, holder_name)) has_without_c_style = ( file_has_without_c_style_copyright_for_holder(c, holder_name)) info['dominant_style'][holder_name] = has_dominant_style info['year_list_style'][holder_name] = has_year_list_style info['without_c_style'][holder_name] = has_without_c_style if has_dominant_style or has_year_list_style or has_without_c_style: info['classified_copyrights'] = info['classified_copyrights'] + 1 return info ################################################################################ # report execution ################################################################################ SEPARATOR = '-'.join(['' for _ in range(80)]) def print_filenames(filenames, verbose): if not verbose: return for filename in filenames: print("\t%s" % filename) def print_report(file_infos, verbose): print(SEPARATOR) examined = [i['filename'] for i in file_infos] print("%d files examined according to INCLUDE and EXCLUDE fnmatch rules" % len(examined)) print_filenames(examined, verbose) print(SEPARATOR) print('') zero_copyrights = [i['filename'] for i in file_infos if i['all_copyrights'] == 0] print("%4d with zero copyrights" % len(zero_copyrights)) print_filenames(zero_copyrights, verbose) one_copyright = [i['filename'] for i in file_infos if i['all_copyrights'] == 1] print("%4d with one copyright" % len(one_copyright)) print_filenames(one_copyright, verbose) two_copyrights = [i['filename'] for i in file_infos if i['all_copyrights'] == 2] print("%4d with two copyrights" % len(two_copyrights)) print_filenames(two_copyrights, verbose) three_copyrights = [i['filename'] for i in file_infos if i['all_copyrights'] == 3] print("%4d with three copyrights" % len(three_copyrights)) print_filenames(three_copyrights, verbose) four_or_more_copyrights = [i['filename'] for i in file_infos if i['all_copyrights'] >= 4] print("%4d with four or more copyrights" % len(four_or_more_copyrights)) print_filenames(four_or_more_copyrights, verbose) print('') print(SEPARATOR) print('Copyrights with dominant style:\ne.g. "Copyright (c)" and ' '"<year>" or "<startYear>-<endYear>":\n') for holder_name in EXPECTED_HOLDER_NAMES: dominant_style = [i['filename'] for i in file_infos if i['dominant_style'][holder_name]] if len(dominant_style) > 0: print("%4d with '%s'" % (len(dominant_style), holder_name.replace('\n', '\\n'))) print_filenames(dominant_style, verbose) print('') print(SEPARATOR) print('Copyrights with year list style:\ne.g. "Copyright (c)" and ' '"<year1>, <year2>, ...":\n') for holder_name in EXPECTED_HOLDER_NAMES: year_list_style = [i['filename'] for i in file_infos if i['year_list_style'][holder_name]] if len(year_list_style) > 0: print("%4d with '%s'" % (len(year_list_style), holder_name.replace('\n', '\\n'))) print_filenames(year_list_style, verbose) print('') print(SEPARATOR) print('Copyrights with no "(c)" style:\ne.g. "Copyright" and "<year>" or ' '"<startYear>-<endYear>":\n') for holder_name in EXPECTED_HOLDER_NAMES: without_c_style = [i['filename'] for i in file_infos if i['without_c_style'][holder_name]] if len(without_c_style) > 0: print("%4d with '%s'" % (len(without_c_style), holder_name.replace('\n', '\\n'))) print_filenames(without_c_style, verbose) print('') print(SEPARATOR) unclassified_copyrights = [i['filename'] for i in file_infos if i['classified_copyrights'] < i['all_copyrights']] print("%d with unexpected copyright holder names" % len(unclassified_copyrights)) print_filenames(unclassified_copyrights, verbose) print(SEPARATOR) def exec_report(base_directory, verbose): original_cwd = os.getcwd() os.chdir(base_directory) filenames = get_filenames_to_examine() file_infos = [gather_file_info(f) for f in filenames] print_report(file_infos, verbose) os.chdir(original_cwd) ################################################################################ # report cmd ################################################################################ REPORT_USAGE = """ Produces a report of all copyright header notices found inside the source files of a repository. Usage: $ ./copyright_header.py report <base_directory> [verbose] Arguments: <base_directory> - The base directory of a bitcoin source code repository. [verbose] - Includes a list of every file of each subcategory in the report. """ def report_cmd(argv): if len(argv) == 2: sys.exit(REPORT_USAGE) base_directory = argv[2] if not os.path.exists(base_directory): sys.exit("*** bad <base_directory>: %s" % base_directory) if len(argv) == 3: verbose = False elif argv[3] == 'verbose': verbose = True else: sys.exit("*** unknown argument: %s" % argv[2]) exec_report(base_directory, verbose) ################################################################################ # query git for year of last change ################################################################################ GIT_LOG_CMD = "git log --pretty=format:%%ai %s" def call_git_log(filename): out = subprocess.check_output((GIT_LOG_CMD % filename).split(' ')) return out.decode("utf-8").split('\n') def get_git_change_years(filename): git_log_lines = call_git_log(filename) if len(git_log_lines) == 0: return [datetime.date.today().year] # timestamp is in ISO 8601 format. e.g. "2016-09-05 14:25:32 -0600" return [line.split(' ')[0].split('-')[0] for line in git_log_lines] def get_most_recent_git_change_year(filename): return max(get_git_change_years(filename)) ################################################################################ # read and write to file ################################################################################ def read_file_lines(filename): f = open(os.path.abspath(filename), 'r') file_lines = f.readlines() f.close() return file_lines def write_file_lines(filename, file_lines): f = open(os.path.abspath(filename), 'w') f.write(''.join(file_lines)) f.close() ################################################################################ # update header years execution ################################################################################ COPYRIGHT = 'Copyright \(c\)' YEAR = "20[0-9][0-9]" YEAR_RANGE = '(%s)(-%s)?' % (YEAR, YEAR) HOLDER = 'The Bitcoin Core developers' UPDATEABLE_LINE_COMPILED = re.compile(' '.join([COPYRIGHT, YEAR_RANGE, HOLDER])) def get_updatable_copyright_line(file_lines): index = 0 for line in file_lines: if UPDATEABLE_LINE_COMPILED.search(line) is not None: return index, line index = index + 1 return None, None def parse_year_range(year_range): year_split = year_range.split('-') start_year = year_split[0] if len(year_split) == 1: return start_year, start_year return start_year, year_split[1] def year_range_to_str(start_year, end_year): if start_year == end_year: return start_year return "%s-%s" % (start_year, end_year) def create_updated_copyright_line(line, last_git_change_year): copyright_splitter = 'Copyright (c) ' copyright_split = line.split(copyright_splitter) # Preserve characters on line that are ahead of the start of the copyright # notice - they are part of the comment block and vary from file-to-file. before_copyright = copyright_split[0] after_copyright = copyright_split[1] space_split = after_copyright.split(' ') year_range = space_split[0] start_year, end_year = parse_year_range(year_range) if end_year == last_git_change_year: return line return (before_copyright + copyright_splitter + year_range_to_str(start_year, last_git_change_year) + ' ' + ' '.join(space_split[1:])) def update_updatable_copyright(filename): file_lines = read_file_lines(filename) index, line = get_updatable_copyright_line(file_lines) if not line: print_file_action_message(filename, "No updatable copyright.") return last_git_change_year = get_most_recent_git_change_year(filename) new_line = create_updated_copyright_line(line, last_git_change_year) if line == new_line: print_file_action_message(filename, "Copyright up-to-date.") return file_lines[index] = new_line write_file_lines(filename, file_lines) print_file_action_message(filename, "Copyright updated! -> %s" % last_git_change_year) def exec_update_header_year(base_directory): original_cwd = os.getcwd() os.chdir(base_directory) for filename in get_filenames_to_examine(): update_updatable_copyright(filename) os.chdir(original_cwd) ################################################################################ # update cmd ################################################################################ UPDATE_USAGE = """ Updates all the copyright headers of "The Bitcoin Core developers" which were changed in a year more recent than is listed. For example: // Copyright (c) <firstYear>-<lastYear> The Bitcoin Core developers will be updated to: // Copyright (c) <firstYear>-<lastModifiedYear> The Bitcoin Core developers where <lastModifiedYear> is obtained from the 'git log' history. This subcommand also handles copyright headers that have only a single year. In those cases: // Copyright (c) <year> The Bitcoin Core developers will be updated to: // Copyright (c) <year>-<lastModifiedYear> The Bitcoin Core developers where the update is appropriate. Usage: $ ./copyright_header.py update <base_directory> Arguments: <base_directory> - The base directory of a bitcoin source code repository. """ def print_file_action_message(filename, action): print("%-52s %s" % (filename, action)) def update_cmd(argv): if len(argv) != 3: sys.exit(UPDATE_USAGE) base_directory = argv[2] if not os.path.exists(base_directory): sys.exit("*** bad base_directory: %s" % base_directory) exec_update_header_year(base_directory) ################################################################################ # inserted copyright header format ################################################################################ def get_header_lines(header, start_year, end_year): lines = header.split('\n')[1:-1] lines[0] = lines[0] % year_range_to_str(start_year, end_year) return [line + '\n' for line in lines] CPP_HEADER = ''' // Copyright (c) %s The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' def get_cpp_header_lines_to_insert(start_year, end_year): return reversed(get_header_lines(CPP_HEADER, start_year, end_year)) PYTHON_HEADER = ''' # Copyright (c) %s The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' def get_python_header_lines_to_insert(start_year, end_year): return reversed(get_header_lines(PYTHON_HEADER, start_year, end_year)) ################################################################################ # query git for year of last change ################################################################################ def get_git_change_year_range(filename): years = get_git_change_years(filename) return min(years), max(years) ################################################################################ # check for existing core copyright ################################################################################ def file_already_has_core_copyright(file_lines): index, _ = get_updatable_copyright_line(file_lines) return index != None ################################################################################ # insert header execution ################################################################################ def file_has_hashbang(file_lines): if len(file_lines) < 1: return False if len(file_lines[0]) <= 2: return False return file_lines[0][:2] == '#!' def insert_python_header(filename, file_lines, start_year, end_year): if file_has_hashbang(file_lines): insert_idx = 1 else: insert_idx = 0 header_lines = get_python_header_lines_to_insert(start_year, end_year) for line in header_lines: file_lines.insert(insert_idx, line) write_file_lines(filename, file_lines) def insert_cpp_header(filename, file_lines, start_year, end_year): header_lines = get_cpp_header_lines_to_insert(start_year, end_year) for line in header_lines: file_lines.insert(0, line) write_file_lines(filename, file_lines) def exec_insert_header(filename, style): file_lines = read_file_lines(filename) if file_already_has_core_copyright(file_lines): sys.exit('*** %s already has a copyright by The Bitcoin Core developers' % (filename)) start_year, end_year = get_git_change_year_range(filename) if style == 'python': insert_python_header(filename, file_lines, start_year, end_year) else: insert_cpp_header(filename, file_lines, start_year, end_year) ################################################################################ # insert cmd ################################################################################ INSERT_USAGE = """ Inserts a copyright header for "The Bitcoin Core developers" at the top of the file in either Python or C++ style as determined by the file extension. If the file is a Python file and it has a '#!' starting the first line, the header is inserted in the line below it. The copyright dates will be set to be: "<year_introduced>-<current_year>" where <year_introduced> is according to the 'git log' history. If <year_introduced> is equal to <current_year>, the date will be set to be: "<current_year>" If the file already has a copyright for "The Bitcoin Core developers", the script will exit. Usage: $ ./copyright_header.py insert <file> Arguments: <file> - A source file in the bitcoin repository. """ def insert_cmd(argv): if len(argv) != 3: sys.exit(INSERT_USAGE) filename = argv[2] if not os.path.isfile(filename): sys.exit("*** bad filename: %s" % filename) _, extension = os.path.splitext(filename) if extension not in ['.h', '.cpp', '.cc', '.c', '.py']: sys.exit("*** cannot insert for file extension %s" % extension) if extension == '.py': style = 'python' else: style = 'cpp' exec_insert_header(filename, style) ################################################################################ # UI ################################################################################ USAGE = """ copyright_header.py - utilities for managing copyright headers of 'The Bitcoin Core developers' in repository source files. Usage: $ ./copyright_header <subcommand> Subcommands: report update insert To see subcommand usage, run them without arguments. """ SUBCOMMANDS = ['report', 'update', 'insert'] if __name__ == "__main__": if len(sys.argv) == 1: sys.exit(USAGE) subcommand = sys.argv[1] if subcommand not in SUBCOMMANDS: sys.exit(USAGE) if subcommand == 'report': report_cmd(sys.argv) elif subcommand == 'update': update_cmd(sys.argv) elif subcommand == 'insert': insert_cmd(sys.argv)
unknown
codeparrot/codeparrot-clean
package kotlinx.coroutines import kotlinx.coroutines.testing.* import org.junit.* class AwaitJvmTest : TestBase() { @Test public fun testSecondLeak() = runTest { // This test is to make sure that handlers installed on the second deferred do not leak val d1 = CompletableDeferred<Int>() val d2 = CompletableDeferred<Int>() d1.completeExceptionally(TestException()) // first is crashed val iterations = 3_000_000 * stressTestMultiplier for (iter in 1..iterations) { try { awaitAll(d1, d2) expectUnreached() } catch (e: TestException) { expect(iter) } } finish(iterations + 1) } }
kotlin
github
https://github.com/Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/jvm/test/AwaitJvmTest.kt
# SPDX-License-Identifier: GPL-2.0 %YAML 1.2 --- $id: http://devicetree.org/schemas/display/allwinner,sun8i-a83t-de2-mixer.yaml# $schema: http://devicetree.org/meta-schemas/core.yaml# title: Allwinner Display Engine 2.0 Mixer maintainers: - Chen-Yu Tsai <wens@csie.org> - Maxime Ripard <mripard@kernel.org> properties: compatible: enum: - allwinner,sun8i-a83t-de2-mixer-0 - allwinner,sun8i-a83t-de2-mixer-1 - allwinner,sun8i-h3-de2-mixer-0 - allwinner,sun8i-r40-de2-mixer-0 - allwinner,sun8i-r40-de2-mixer-1 - allwinner,sun8i-v3s-de2-mixer - allwinner,sun20i-d1-de2-mixer-0 - allwinner,sun20i-d1-de2-mixer-1 - allwinner,sun50i-a64-de2-mixer-0 - allwinner,sun50i-a64-de2-mixer-1 - allwinner,sun50i-h6-de3-mixer-0 - allwinner,sun50i-h616-de33-mixer-0 reg: true reg-names: true clocks: items: - description: The mixer interface clock - description: The mixer module clock clock-names: items: - const: bus - const: mod iommus: maxItems: 1 resets: maxItems: 1 ports: $ref: /schemas/graph.yaml#/properties/ports properties: port@0: $ref: /schemas/graph.yaml#/properties/port description: | Input endpoints of the controller. port@1: $ref: /schemas/graph.yaml#/properties/port description: | Output endpoints of the controller. required: - port@1 allOf: - if: properties: compatible: contains: enum: - allwinner,sun50i-h616-de33-mixer-0 then: properties: reg: description: | Registers for controlling individual layers of the display engine (layers), global control (top), and display blending control (display). Names are from Allwinner BSP kernel. maxItems: 3 reg-names: items: - const: layers - const: top - const: display required: - reg-names else: properties: reg: maxItems: 1 required: - compatible - reg - clocks - clock-names - resets - ports additionalProperties: false examples: - | #include <dt-bindings/clock/sun8i-de2.h> #include <dt-bindings/reset/sun8i-de2.h> mixer0: mixer@1100000 { compatible = "allwinner,sun8i-a83t-de2-mixer-0"; reg = <0x01100000 0x100000>; clocks = <&display_clocks CLK_BUS_MIXER0>, <&display_clocks CLK_MIXER0>; clock-names = "bus", "mod"; resets = <&display_clocks RST_MIXER0>; ports { #address-cells = <1>; #size-cells = <0>; mixer0_out: port@1 { #address-cells = <1>; #size-cells = <0>; reg = <1>; mixer0_out_tcon0: endpoint@0 { reg = <0>; remote-endpoint = <&tcon0_in_mixer0>; }; mixer0_out_tcon1: endpoint@1 { reg = <1>; remote-endpoint = <&tcon1_in_mixer0>; }; }; }; }; ...
unknown
github
https://github.com/torvalds/linux
Documentation/devicetree/bindings/display/allwinner,sun8i-a83t-de2-mixer.yaml
import urllib2, urllib, sys, os, re, random, copy, time import htmlcleaner from BeautifulSoup import BeautifulSoup, Tag, NavigableString import xbmc,xbmcplugin,xbmcgui,xbmcaddon from t0mm0.common.net import Net from t0mm0.common.addon import Addon from scrapers import CommonScraper net = Net() class AllucServiceSracper(CommonScraper): def __init__(self, settingsid, DB=None, REG=None): if DB: self.DB=DB if REG: self.REG=REG self.addon_id = 'script.module.donnie' self.service='alluc' self.name = 'alluc.to' self.referrer = 'http://www.alluc.to' self.base_url = 'http://www.alluc.to' self.raiseError = False self.ajax_url = self.base_url + '/membersonly/components/com_iceplayer/video.phpAjaxResp.php' self.user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3' self.provides = [] self._streams = [] self._episodes = [] self.args = None self.cookie = None self.AZ = ['%23', 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y', 'Z'] self.settingsid = settingsid self._loadsettings() self.settings_addon = self.addon def _getShowsByCHR(self, character, pDialog, percent, silent): self.log("getting shows by %s", character) url = self.base_url + '/tv-shows.html?mode=showall&letter=%s' % character if character == '%23' : character = '1' self.log("Scrapping: %s", url) if not silent: pDialog.update(percent, url, '') pagedata = self.getURL(url, append_base_url=False) if pagedata=='': return False soup = BeautifulSoup(pagedata) shows = soup.findAll("li", {"class": "linklist2"}) for show in shows: try: a = show.find('a') href = a['href'] name = a['title'] name = str(name[6:len(name)-7]) year = re.search('\((.+?)\)$', name).group(1) name=self.cleanName(name) if not silent: pDialog.update(percent, url, name) self.addShowToDB(name, href, character, year) except Exception, e: self.log("********Donnie Error: %s, %s" % (self.service, e)) self.DB.commit() return True def _getRecentShows(self, silent): self.log("Getting recent shows for: %s", self.service) url = self.base_url + '/tv-shows.html' self.log("Scrapping: %s", url) if not silent: pDialog = xbmcgui.DialogProgress() pDialog.create('Caching recent shows from ' + self.service) pDialog.update(0, url, '') pagedata = self.getURL(url, append_base_url=False) if pagedata=='': return False soup = BeautifulSoup(pagedata) shows = soup.findAll("li", {"class": "linklist2"}) for show in shows: try: percent = int((100 * shows.index(show))/len(shows)) a = show.find('a') href = a['href'] name = a['title'] name = str(name[6:len(name)-7]) year = re.search('\((.+?)\)$', name).group(1) name=self.cleanName(name) character = self.getInitialChr(name) if not silent: pDialog.update(percent, url, name) self.addShowToDB(name, href, character, year) except Exception, e: self.log("********Donnie Error: %s, %s" % (self.service, e)) self.update_cache_status("tvshows") self.DB.commit() return True def _getNewEpisodes(self, silent=False): self.log("Getting new episodes for %s", self.service) episodes = [] return episodes def _getEpisodes(self, showid, show, url, pDialog, percent, silent, createFiles=True): self.log("Getting episodes for %s", show) pagedata = self.getURL('/'+url, append_base_url=True) if pagedata=='': return False soup = BeautifulSoup(pagedata) links = soup.findAll("a", {"class": "linklist2"}) parser = re.compile('season-(.+?)/episode-(.+?)/') for a in links: try: href = a['href'] temp = parser.search(href) if temp: season = temp.group(1) episode = temp.group(2) name = "Episode %s" % episode if not silent: pDialog.update(percent, show, name) self.addEpisodeToDB(showid, show, name, season, episode, href, createFiles=createFiles) except Exception, e: self.log("********Donnie Error: %s, %s" % (self.service, e)) self.DB.commit() return True def _getMoviesByCHR(self, character, pDialog, percent, silent): url = self.base_url + '/movies.html?mode=showall&letter=%s' % character if character == '%23' : character = '1' if not silent: pDialog.update(percent, url, '') pagedata = self.getURL(url, append_base_url=False) if pagedata=='': return False soup = BeautifulSoup(pagedata) movies = soup.findAll("li", {"class": "linklist2"}) for movie in movies: try: a = movie.find('a') href = a['href'] name = a['title'] name = str(name[6:len(name)-7]) year = re.search('\((.+?)\)$', name).group(1) name=self.cleanName(name) if not silent: pDialog.update(percent, url, name) self.addMovieToDB(name, href, self.service + '://' + href, character, year) except Exception, e: self.log("********Donnie Error: %s, %s" % (self.service, e)) self.DB.commit() return True def _getRecentMovies(self, silent, DB=None): url = self.base_url + '/movies.html' if not silent: pDialog = xbmcgui.DialogProgress() pDialog.create('Caching recent movies from ' + self.service) pDialog.update(0, url, '') pagedata = self.getURL(url, append_base_url=False) if pagedata=='': return False soup = BeautifulSoup(pagedata) movies = soup.findAll("li", {"class": "linklist2"}) for movie in movies: try: percent = int((100 * movies.index(movie))/len(movies)) href = a['href'] name = a['title'] name = str(name[6:len(name)-7]) year = re.search('\((.+?)\)$', name).group(1) name=self.cleanName(name) character = self.getInitialChr(name) if not silent: pDialog.update(percent, url, self.cleanName(name)) self.addMovieToDB(name, href, imdb, character, year) except Exception, e: self.log("********Donnie Error: %s, %s" % (self.service, e)) self.update_cache_status("movies") self.DB.commit() return True def _getStreams(self, episodeid=None, movieid=None, directurl=None): streams = [] if directurl: self.getProviders() url = directurl else: url = self.getServices(episodeid=episodeid, movieid=movieid) if not url: return if self.ENABLE_MIRROR_CACHING: if url: self.log(url) cache_url = url else: return streams cached = self.checkStreamCache(cache_url) if len(cached) > 0: self.log("Loading streams from cache") for temp in cached: self.getStreamByPriority(temp[0], temp[1]) return cached self.log("Locating streams for provided by service: %s", self.service) pagedata = self.getURL('/'+url, append_base_url=True) if pagedata=='': return soup = BeautifulSoup(pagedata) hosters = soup.findAll('div', {'class':'grouphosterlabel'}) for hoster in hosters: label = hoster.string provider = self.whichHost(label) if provider: div = hoster.parent.parent hosts = div.findAll('a', {'class':'openlink'}) for host in hosts: raw_url = host['href'] if re.match("^tv-shows|movies", raw_url): self.getStreamByPriority('Alluc - ' + provider, self.service + '://' + raw_url) if self.ENABLE_MIRROR_CACHING: self.cacheStreamLink(cache_url, 'Alluc - ' + provider, self.service + '://' + raw_url) self.DB.commit() def whichHost(self, host): table = { 'Movreel' : 'movreel.com', 'Divxstage' : 'divxstage.eu', 'Videoweed' : 'videoweed.es', 'Filenuke' : 'filenuke.com', 'Sharesix' : 'sharesix.com', '180upload' : '180upload.com', 'Novamov' : 'novamov.com', 'Nowvideo' : 'nowvideo.com', 'Moveshare' : 'moveshare.net', 'Shockshare' : 'shockshare.com', 'Putlocker' : 'putlocker.com', } try: test = re.search("^(.+?) \(\d{1,2}\)", host).group(1) host_url = table[test] return host_url except: return None def _resolveStream(self, stream): import urlresolver, httplib2 uri = stream.replace(self.service + '://', '') resolved_url = '' raw_url = self.base_url + '/' + uri h = httplib2.Http() h.follow_redirects = True (response, body) = h.request(raw_url) try: resolved_url = urlresolver.HostedMediaFile(url=response['content-location']).resolve() except: self.log('Unable to resolve using urlresolver') resolved_url = self.resolveLink(response['content-location']) if not resolved_url: print "Unable to resolve url, sorry!" return resolved_url def _resolveIMDB(self, uri): from donnie.imdb import IMDB Imdb = IMDB() imdb = '' row = self.DB.query("SELECT movie, year FROM rw_movies WHERE url=?", [uri]) movie = row[0] year = row[1] if re.search('\(\\d{4}\)$', movie): movie = movie[0:len(movie)-6] data = Imdb.resolveIMDB(movie, year) if len(data['Search']) > 1: results = [] options = [] dialog = xbmcgui.Dialog() for result in data['Search']: results.append(result['Title']) options.append(result['imdbID']) result_select = dialog.select('Multiple results returned from IMDB:', results) if result_select < 0: return False imdb = options[result_select] else : imdb = data['search'][0]['imdbID'] return self.padIMDB(imdb) def getStreamByPriority(self, link, stream): self.log(link) host = re.search('- (.+?)$', link).group(1) SQL = "INSERT INTO rw_stream_list(stream, url, priority, machineid) " \ "SELECT ?, ?, priority, ? " \ "FROM rw_providers " \ "WHERE mirror=? and provider=?" self.DB.execute(SQL, [link, stream, self.REG.getSetting('machine-id'), host, self.service])
unknown
codeparrot/codeparrot-clean
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.fs.tosfs.object.exceptions; import org.apache.hadoop.util.StringUtils; import java.io.IOException; public class ChecksumMismatchException extends IOException { public ChecksumMismatchException(String message) { super(message); } public ChecksumMismatchException(byte[] expected, byte[] actual) { this(String.format("Expected checksum is %s while actual checksum is %s", StringUtils.byteToHexString(expected), StringUtils.byteToHexString(actual))); } }
java
github
https://github.com/apache/hadoop
hadoop-cloud-storage-project/hadoop-tos/src/main/java/org/apache/hadoop/fs/tosfs/object/exceptions/ChecksumMismatchException.java
"""A CallTip window class for Tkinter/IDLE. After ToolTip.py, which uses ideas gleaned from PySol Used by the CallTips IDLE extension. """ from tkinter import Toplevel, Label, LEFT, SOLID, TclError HIDE_VIRTUAL_EVENT_NAME = "<<calltipwindow-hide>>" HIDE_SEQUENCES = ("<Key-Escape>", "<FocusOut>") CHECKHIDE_VIRTUAL_EVENT_NAME = "<<calltipwindow-checkhide>>" CHECKHIDE_SEQUENCES = ("<KeyRelease>", "<ButtonRelease>") CHECKHIDE_TIME = 100 # miliseconds MARK_RIGHT = "calltipwindowregion_right" class CallTip: def __init__(self, widget): self.widget = widget self.tipwindow = self.label = None self.parenline = self.parencol = None self.lastline = None self.hideid = self.checkhideid = None self.checkhide_after_id = None def position_window(self): """Check if needs to reposition the window, and if so - do it.""" curline = int(self.widget.index("insert").split('.')[0]) if curline == self.lastline: return self.lastline = curline self.widget.see("insert") if curline == self.parenline: box = self.widget.bbox("%d.%d" % (self.parenline, self.parencol)) else: box = self.widget.bbox("%d.0" % curline) if not box: box = list(self.widget.bbox("insert")) # align to left of window box[0] = 0 box[2] = 0 x = box[0] + self.widget.winfo_rootx() + 2 y = box[1] + box[3] + self.widget.winfo_rooty() self.tipwindow.wm_geometry("+%d+%d" % (x, y)) def showtip(self, text, parenleft, parenright): """Show the calltip, bind events which will close it and reposition it. """ # Only called in CallTips, where lines are truncated self.text = text if self.tipwindow or not self.text: return self.widget.mark_set(MARK_RIGHT, parenright) self.parenline, self.parencol = map( int, self.widget.index(parenleft).split(".")) self.tipwindow = tw = Toplevel(self.widget) self.position_window() # remove border on calltip window tw.wm_overrideredirect(1) try: # This command is only needed and available on Tk >= 8.4.0 for OSX # Without it, call tips intrude on the typing process by grabbing # the focus. tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "noActivates") except TclError: pass self.label = Label(tw, text=self.text, justify=LEFT, background="#ffffe0", relief=SOLID, borderwidth=1, font = self.widget['font']) self.label.pack() self.checkhideid = self.widget.bind(CHECKHIDE_VIRTUAL_EVENT_NAME, self.checkhide_event) for seq in CHECKHIDE_SEQUENCES: self.widget.event_add(CHECKHIDE_VIRTUAL_EVENT_NAME, seq) self.widget.after(CHECKHIDE_TIME, self.checkhide_event) self.hideid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event) for seq in HIDE_SEQUENCES: self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq) def checkhide_event(self, event=None): if not self.tipwindow: # If the event was triggered by the same event that unbinded # this function, the function will be called nevertheless, # so do nothing in this case. return curline, curcol = map(int, self.widget.index("insert").split('.')) if curline < self.parenline or \ (curline == self.parenline and curcol <= self.parencol) or \ self.widget.compare("insert", ">", MARK_RIGHT): self.hidetip() else: self.position_window() if self.checkhide_after_id is not None: self.widget.after_cancel(self.checkhide_after_id) self.checkhide_after_id = \ self.widget.after(CHECKHIDE_TIME, self.checkhide_event) def hide_event(self, event): if not self.tipwindow: # See the explanation in checkhide_event. return self.hidetip() def hidetip(self): if not self.tipwindow: return for seq in CHECKHIDE_SEQUENCES: self.widget.event_delete(CHECKHIDE_VIRTUAL_EVENT_NAME, seq) self.widget.unbind(CHECKHIDE_VIRTUAL_EVENT_NAME, self.checkhideid) self.checkhideid = None for seq in HIDE_SEQUENCES: self.widget.event_delete(HIDE_VIRTUAL_EVENT_NAME, seq) self.widget.unbind(HIDE_VIRTUAL_EVENT_NAME, self.hideid) self.hideid = None self.label.destroy() self.label = None self.tipwindow.destroy() self.tipwindow = None self.widget.mark_unset(MARK_RIGHT) self.parenline = self.parencol = self.lastline = None def is_active(self): return bool(self.tipwindow) def _calltip_window(parent): # htest # import re from tkinter import Tk, Text, LEFT, BOTH root = Tk() root.title("Test calltips") width, height, x, y = list(map(int, re.split('[x+]', parent.geometry()))) root.geometry("+%d+%d"%(x, y + 150)) class MyEditWin: # conceptually an editor_window def __init__(self): text = self.text = Text(root) text.pack(side=LEFT, fill=BOTH, expand=1) text.insert("insert", "string.split") root.update() self.calltip = CallTip(text) text.event_add("<<calltip-show>>", "(") text.event_add("<<calltip-hide>>", ")") text.bind("<<calltip-show>>", self.calltip_show) text.bind("<<calltip-hide>>", self.calltip_hide) text.focus_set() root.mainloop() def calltip_show(self, event): self.calltip.showtip("Hello world", "insert", "end") def calltip_hide(self, event): self.calltip.hidetip() MyEditWin() if __name__=='__main__': from idlelib.idle_test.htest import run run(_calltip_window)
unknown
codeparrot/codeparrot-clean
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_PLATFORM_TYPES_H_ #define TENSORFLOW_CORE_PLATFORM_TYPES_H_ #include <cstdint> #include <string> #include "absl/base/macros.h" #include "xla/tsl/platform/types.h" #include "tensorflow/core/platform/bfloat16.h" #include "tensorflow/core/platform/platform.h" #include "tensorflow/core/platform/tstring.h" #include "tsl/platform/bfloat16.h" #include "tsl/platform/tstring.h" namespace tensorflow { // Alias tensorflow::string to std::string. using string ABSL_DEPRECATE_AND_INLINE() = std::string; using tsl::uint2; using tsl::uint4; using uint8 ABSL_DEPRECATE_AND_INLINE() = uint8_t; using uint16 ABSL_DEPRECATE_AND_INLINE() = uint16_t; using uint32 ABSL_DEPRECATE_AND_INLINE() = uint32_t; using uint64 ABSL_DEPRECATE_AND_INLINE() = uint64_t; using tsl::int2; using tsl::int4; using int8 ABSL_DEPRECATE_AND_INLINE() = int8_t; using int16 ABSL_DEPRECATE_AND_INLINE() = int16_t; using int32 ABSL_DEPRECATE_AND_INLINE() = int32_t; using int64 ABSL_DEPRECATE_AND_INLINE() = int64_t; using tsl::float4_e2m1fn; using tsl::float8_e4m3b11fnuz; using tsl::float8_e4m3fn; using tsl::float8_e4m3fnuz; using tsl::float8_e5m2; using tsl::float8_e5m2fnuz; using tsl::kint16max; using tsl::kint16min; using tsl::kint32max; using tsl::kint32min; using tsl::kint64max; using tsl::kint64min; using tsl::kint8max; using tsl::kint8min; using tsl::kuint16max; using tsl::kuint32max; using tsl::kuint64max; using tsl::kuint8max; // A typedef for a uint64 used as a short fingerprint. using tsl::bfloat16; using tsl::Fprint; using tsl::tstring; // NOLINT: suppress 'using decl 'tstring' is unused' } // namespace tensorflow #endif // TENSORFLOW_CORE_PLATFORM_TYPES_H_
c
github
https://github.com/tensorflow/tensorflow
tensorflow/core/platform/types.h
import time from mitmproxy import exceptions BLOCKSIZE = 1024 # It's not clear what the upper limit for time.sleep is. It's lower than the # maximum int or float. 1 year should do. FOREVER = 60 * 60 * 24 * 365 def send_chunk(fp, val, blocksize, start, end): """ (start, end): Inclusive lower bound, exclusive upper bound. """ for i in range(start, end, blocksize): fp.write( val[i:min(i + blocksize, end)] ) return end - start def write_values(fp, vals, actions, sofar=0, blocksize=BLOCKSIZE): """ vals: A list of values, which may be strings or Value objects. actions: A list of (offset, action, arg) tuples. Action may be "inject", "pause" or "disconnect". Both vals and actions are in reverse order, with the first items last. Return True if connection should disconnect. """ sofar = 0 try: while vals: v = vals.pop() offset = 0 while actions and actions[-1][0] < (sofar + len(v)): a = actions.pop() offset += send_chunk( fp, v, blocksize, offset, a[0] - sofar - offset ) if a[1] == "pause": time.sleep( FOREVER if a[2] == "f" else a[2] ) elif a[1] == "disconnect": return True elif a[1] == "inject": send_chunk(fp, a[2], blocksize, 0, len(a[2])) send_chunk(fp, v, blocksize, offset, len(v)) sofar += len(v) # Remainders while actions: a = actions.pop() if a[1] == "pause": time.sleep( FOREVER if a[2] == "f" else a[2] ) elif a[1] == "disconnect": return True elif a[1] == "inject": send_chunk(fp, a[2], blocksize, 0, len(a[2])) except exceptions.TcpDisconnect: # pragma: no cover return True
unknown
codeparrot/codeparrot-clean
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os from tempfile import mkdtemp from shutil import rmtree import numpy as np import nibabel as nb from nipype.testing import (assert_equal, assert_not_equal, assert_raises, skipif) import nipype.interfaces.fsl.utils as fsl from nipype.interfaces.fsl import no_fsl, Info from .test_maths import (set_output_type, create_files_in_directory, clean_directory) @skipif(no_fsl) def test_fslroi(): filelist, outdir, cwd, _ = create_files_in_directory() roi = fsl.ExtractROI() # make sure command gets called yield assert_equal, roi.cmd, 'fslroi' # test raising error with mandatory args absent yield assert_raises, ValueError, roi.run # .inputs based parameters setting roi.inputs.in_file = filelist[0] roi.inputs.roi_file = 'foo_roi.nii' roi.inputs.t_min = 10 roi.inputs.t_size = 20 yield assert_equal, roi.cmdline, 'fslroi %s foo_roi.nii 10 20' % filelist[0] # .run based parameter setting roi2 = fsl.ExtractROI(in_file=filelist[0], roi_file='foo2_roi.nii', t_min=20, t_size=40, x_min=3, x_size=30, y_min=40, y_size=10, z_min=5, z_size=20) yield assert_equal, roi2.cmdline, \ 'fslroi %s foo2_roi.nii 3 30 40 10 5 20 20 40' % filelist[0] clean_directory(outdir, cwd) # test arguments for opt_map # Fslroi class doesn't have a filled opt_map{} @skipif(no_fsl) def test_fslmerge(): filelist, outdir, cwd, _ = create_files_in_directory() merger = fsl.Merge() # make sure command gets called yield assert_equal, merger.cmd, 'fslmerge' # test raising error with mandatory args absent yield assert_raises, ValueError, merger.run # .inputs based parameters setting merger.inputs.in_files = filelist merger.inputs.merged_file = 'foo_merged.nii' merger.inputs.dimension = 't' merger.inputs.output_type = 'NIFTI' yield assert_equal, merger.cmdline, 'fslmerge -t foo_merged.nii %s' % ' '.join(filelist) # verify that providing a tr value updates the dimension to tr merger.inputs.tr = 2.25 yield assert_equal, merger.cmdline, 'fslmerge -tr foo_merged.nii %s %.2f' % (' '.join(filelist), 2.25) # .run based parameter setting merger2 = fsl.Merge(in_files=filelist, merged_file='foo_merged.nii', dimension='t', output_type='NIFTI', tr=2.25) yield assert_equal, merger2.cmdline, \ 'fslmerge -tr foo_merged.nii %s %.2f' % (' '.join(filelist), 2.25) clean_directory(outdir, cwd) # test arguments for opt_map # Fslmerge class doesn't have a filled opt_map{} # test fslmath @skipif(no_fsl) def test_fslmaths(): filelist, outdir, cwd, _ = create_files_in_directory() math = fsl.ImageMaths() # make sure command gets called yield assert_equal, math.cmd, 'fslmaths' # test raising error with mandatory args absent yield assert_raises, ValueError, math.run # .inputs based parameters setting math.inputs.in_file = filelist[0] math.inputs.op_string = '-add 2.5 -mul input_volume2' math.inputs.out_file = 'foo_math.nii' yield assert_equal, math.cmdline, \ 'fslmaths %s -add 2.5 -mul input_volume2 foo_math.nii' % filelist[0] # .run based parameter setting math2 = fsl.ImageMaths(in_file=filelist[0], op_string='-add 2.5', out_file='foo2_math.nii') yield assert_equal, math2.cmdline, 'fslmaths %s -add 2.5 foo2_math.nii' % filelist[0] # test arguments for opt_map # Fslmath class doesn't have opt_map{} clean_directory(outdir, cwd) # test overlay @skipif(no_fsl) def test_overlay(): filelist, outdir, cwd, _ = create_files_in_directory() overlay = fsl.Overlay() # make sure command gets called yield assert_equal, overlay.cmd, 'overlay' # test raising error with mandatory args absent yield assert_raises, ValueError, overlay.run # .inputs based parameters setting overlay.inputs.stat_image = filelist[0] overlay.inputs.stat_thresh = (2.5, 10) overlay.inputs.background_image = filelist[1] overlay.inputs.auto_thresh_bg = True overlay.inputs.show_negative_stats = True overlay.inputs.out_file = 'foo_overlay.nii' yield assert_equal, overlay.cmdline, \ 'overlay 1 0 %s -a %s 2.50 10.00 %s -2.50 -10.00 foo_overlay.nii' % ( filelist[1], filelist[0], filelist[0]) # .run based parameter setting overlay2 = fsl.Overlay(stat_image=filelist[0], stat_thresh=(2.5, 10), background_image=filelist[1], auto_thresh_bg=True, out_file='foo2_overlay.nii') yield assert_equal, overlay2.cmdline, 'overlay 1 0 %s -a %s 2.50 10.00 foo2_overlay.nii' % ( filelist[1], filelist[0]) clean_directory(outdir, cwd) # test slicer @skipif(no_fsl) def test_slicer(): filelist, outdir, cwd, _ = create_files_in_directory() slicer = fsl.Slicer() # make sure command gets called yield assert_equal, slicer.cmd, 'slicer' # test raising error with mandatory args absent yield assert_raises, ValueError, slicer.run # .inputs based parameters setting slicer.inputs.in_file = filelist[0] slicer.inputs.image_edges = filelist[1] slicer.inputs.intensity_range = (10., 20.) slicer.inputs.all_axial = True slicer.inputs.image_width = 750 slicer.inputs.out_file = 'foo_bar.png' yield assert_equal, slicer.cmdline, \ 'slicer %s %s -L -i 10.000 20.000 -A 750 foo_bar.png' % ( filelist[0], filelist[1]) # .run based parameter setting slicer2 = fsl.Slicer( in_file=filelist[0], middle_slices=True, label_slices=False, out_file='foo_bar2.png') yield assert_equal, slicer2.cmdline, 'slicer %s -a foo_bar2.png' % (filelist[0]) clean_directory(outdir, cwd) def create_parfiles(): np.savetxt('a.par', np.random.rand(6, 3)) np.savetxt('b.par', np.random.rand(6, 3)) return ['a.par', 'b.par'] # test fsl_tsplot @skipif(no_fsl) def test_plottimeseries(): filelist, outdir, cwd, _ = create_files_in_directory() parfiles = create_parfiles() plotter = fsl.PlotTimeSeries() # make sure command gets called yield assert_equal, plotter.cmd, 'fsl_tsplot' # test raising error with mandatory args absent yield assert_raises, ValueError, plotter.run # .inputs based parameters setting plotter.inputs.in_file = parfiles[0] plotter.inputs.labels = ['x', 'y', 'z'] plotter.inputs.y_range = (0, 1) plotter.inputs.title = 'test plot' plotter.inputs.out_file = 'foo.png' yield assert_equal, plotter.cmdline, \ ('fsl_tsplot -i %s -a x,y,z -o foo.png -t \'test plot\' -u 1 --ymin=0 --ymax=1' % parfiles[0]) # .run based parameter setting plotter2 = fsl.PlotTimeSeries( in_file=parfiles, title='test2 plot', plot_range=(2, 5), out_file='bar.png') yield assert_equal, plotter2.cmdline, \ 'fsl_tsplot -i %s,%s -o bar.png --start=2 --finish=5 -t \'test2 plot\' -u 1' % tuple( parfiles) clean_directory(outdir, cwd) @skipif(no_fsl) def test_plotmotionparams(): filelist, outdir, cwd, _ = create_files_in_directory() parfiles = create_parfiles() plotter = fsl.PlotMotionParams() # make sure command gets called yield assert_equal, plotter.cmd, 'fsl_tsplot' # test raising error with mandatory args absent yield assert_raises, ValueError, plotter.run # .inputs based parameters setting plotter.inputs.in_file = parfiles[0] plotter.inputs.in_source = 'fsl' plotter.inputs.plot_type = 'rotations' plotter.inputs.out_file = 'foo.png' yield assert_equal, plotter.cmdline, \ ('fsl_tsplot -i %s -o foo.png -t \'MCFLIRT estimated rotations (radians)\' ' '--start=1 --finish=3 -a x,y,z' % parfiles[0]) # .run based parameter setting plotter2 = fsl.PlotMotionParams( in_file=parfiles[1], in_source='spm', plot_type='translations', out_file='bar.png') yield assert_equal, plotter2.cmdline, \ ('fsl_tsplot -i %s -o bar.png -t \'Realign estimated translations (mm)\' ' '--start=1 --finish=3 -a x,y,z' % parfiles[1]) clean_directory(outdir, cwd) @skipif(no_fsl) def test_convertxfm(): filelist, outdir, cwd, _ = create_files_in_directory() cvt = fsl.ConvertXFM() # make sure command gets called yield assert_equal, cvt.cmd, "convert_xfm" # test raising error with mandatory args absent yield assert_raises, ValueError, cvt.run # .inputs based parameters setting cvt.inputs.in_file = filelist[0] cvt.inputs.invert_xfm = True cvt.inputs.out_file = "foo.mat" yield assert_equal, cvt.cmdline, 'convert_xfm -omat foo.mat -inverse %s' % filelist[0] # constructor based parameter setting cvt2 = fsl.ConvertXFM( in_file=filelist[0], in_file2=filelist[1], concat_xfm=True, out_file="bar.mat") yield assert_equal, cvt2.cmdline, \ "convert_xfm -omat bar.mat -concat %s %s" % (filelist[1], filelist[0]) clean_directory(outdir, cwd) @skipif(no_fsl) def test_swapdims(fsl_output_type=None): prev_type = set_output_type(fsl_output_type) files, testdir, origdir, out_ext = create_files_in_directory() swap = fsl.SwapDimensions() # Test the underlying command yield assert_equal, swap.cmd, "fslswapdim" # Test mandatory args args = [dict(in_file=files[0]), dict(new_dims=("x", "y", "z"))] for arg in args: wontrun = fsl.SwapDimensions(**arg) yield assert_raises, ValueError, wontrun.run # Now test a basic command line swap.inputs.in_file = files[0] swap.inputs.new_dims = ("x", "y", "z") yield assert_equal, swap.cmdline, "fslswapdim a.nii x y z %s" % os.path.realpath(os.path.join(testdir, "a_newdims%s" % out_ext)) # Test that we can set an output name swap.inputs.out_file = "b.nii" yield assert_equal, swap.cmdline, "fslswapdim a.nii x y z b.nii" # Clean up clean_directory(testdir, origdir) set_output_type(prev_type)
unknown
codeparrot/codeparrot-clean
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. # This test may make an actual HTTP request. __author__ = 'j.s@google.com (Jeff Scudder)' import unittest import atom.http_core import atom.auth import atom.client import atom.mock_http_core class AtomPubClientEchoTest(unittest.TestCase): def test_simple_request_with_no_client_defaults(self): client = atom.client.AtomPubClient(atom.mock_http_core.EchoHttpClient()) self.assert_(client.host is None) self.assert_(client.auth_token is None) # Make several equivalent requests. responses = [client.request('GET', 'http://example.org/'), client.request(http_request=atom.http_core.HttpRequest( uri=atom.http_core.Uri('http', 'example.org', path='/'), method='GET')), client.request('GET', http_request=atom.http_core.HttpRequest( uri=atom.http_core.Uri('http', 'example.org', path='/')))] for response in responses: self.assert_(response.getheader('Echo-Host') == 'example.org:None') self.assert_(response.getheader('Echo-Uri') == '/') self.assert_(response.getheader('Echo-Scheme') == 'http') self.assert_(response.getheader('Echo-Method') == 'GET') self.assert_(response.getheader('User-Agent').startswith('gdata-py/')) def test_auth_request_with_no_client_defaults(self): client = atom.client.AtomPubClient(atom.mock_http_core.EchoHttpClient()) token = atom.auth.BasicAuth('Jeff', '123') response = client.request('POST', 'https://example.net:8080/', auth_token=token) self.assert_(response.getheader('Echo-Host') == 'example.net:8080') self.assert_(response.getheader('Echo-Uri') == '/') self.assert_(response.getheader('Echo-Scheme') == 'https') self.assert_(response.getheader('Authorization') == 'Basic SmVmZjoxMjM=') self.assert_(response.getheader('Echo-Method') == 'POST') def test_request_with_client_defaults(self): client = atom.client.AtomPubClient(atom.mock_http_core.EchoHttpClient(), 'example.com', atom.auth.BasicAuth('Jeff', '123')) self.assert_(client.host == 'example.com') self.assert_(client.auth_token is not None) self.assert_(client.auth_token.basic_cookie == 'SmVmZjoxMjM=') response = client.request('GET', 'http://example.org/') self.assert_(response.getheader('Echo-Host') == 'example.org:None') self.assert_(response.getheader('Echo-Uri') == '/') self.assert_(response.getheader('Echo-Scheme') == 'http') self.assert_(response.getheader('Echo-Method') == 'GET') self.assert_(response.getheader('Authorization') == 'Basic SmVmZjoxMjM=') response = client.request('GET', '/') self.assert_(response.getheader('Echo-Host') == 'example.com:None') self.assert_(response.getheader('Echo-Uri') == '/') self.assert_(response.getheader('Echo-Scheme') == 'http') self.assert_(response.getheader('Authorization') == 'Basic SmVmZjoxMjM=') response = client.request('GET', '/', http_request=atom.http_core.HttpRequest( uri=atom.http_core.Uri(port=99))) self.assert_(response.getheader('Echo-Host') == 'example.com:99') self.assert_(response.getheader('Echo-Uri') == '/') def test_get(self): client = atom.client.AtomPubClient(atom.mock_http_core.EchoHttpClient()) response = client.get('http://example.com/simple') self.assert_(response.getheader('Echo-Host') == 'example.com:None') self.assert_(response.getheader('Echo-Uri') == '/simple') self.assert_(response.getheader('Echo-Method') == 'GET') response = client.Get(uri='http://example.com/simple2') self.assert_(response.getheader('Echo-Uri') == '/simple2') self.assert_(response.getheader('Echo-Method') == 'GET') def test_modify_request_using_args(self): client = atom.client.AtomPubClient(atom.mock_http_core.EchoHttpClient()) class RequestModifier(object): def modify_request(self, http_request): http_request.headers['Special'] = 'Set' response = client.get('http://example.com/modified', extra=RequestModifier()) self.assert_(response.getheader('Echo-Host') == 'example.com:None') self.assert_(response.getheader('Echo-Uri') == '/modified') self.assert_(response.getheader('Echo-Method') == 'GET') self.assert_(response.getheader('Special') == 'Set') def test_post(self): client = atom.client.AtomPubClient(atom.mock_http_core.EchoHttpClient()) class TestData(object): def modify_request(self, http_request): http_request.add_body_part('test body', 'text/testdata') response = client.Post(uri='http://example.com/', data=TestData()) self.assert_(response.getheader('Echo-Host') == 'example.com:None') self.assert_(response.getheader('Echo-Uri') == '/') self.assert_(response.getheader('Echo-Method') == 'POST') self.assert_(response.getheader('Content-Length') == str(len('test body'))) self.assert_(response.getheader('Content-Type') == 'text/testdata') self.assert_(response.read(2) == 'te') self.assert_(response.read() == 'st body') response = client.post(data=TestData(), uri='http://example.com/') self.assert_(response.read() == 'test body') self.assert_(response.getheader('Content-Type') == 'text/testdata') # Don't pass in a body, but use an extra kwarg to add the body to the # http_request. response = client.post(x=TestData(), uri='http://example.com/') self.assert_(response.read() == 'test body') def test_put(self): body_text = '<put>test</put>' client = atom.client.AtomPubClient(atom.mock_http_core.EchoHttpClient()) class TestData(object): def modify_request(self, http_request): http_request.add_body_part(body_text, 'application/xml') response = client.put('http://example.org', TestData()) self.assert_(response.getheader('Echo-Host') == 'example.org:None') self.assert_(response.getheader('Echo-Uri') == '/') self.assert_(response.getheader('Echo-Method') == 'PUT') self.assert_(response.getheader('Content-Length') == str(len(body_text))) self.assert_(response.getheader('Content-Type') == 'application/xml') response = client.put(uri='http://example.org', data=TestData()) self.assert_(response.getheader('Content-Length') == str(len(body_text))) self.assert_(response.getheader('Content-Type') == 'application/xml') def test_delete(self): client = atom.client.AtomPubClient(atom.mock_http_core.EchoHttpClient(), source='my new app') response = client.Delete('http://example.com/simple') self.assertEqual(response.getheader('Echo-Host'), 'example.com:None') self.assertEqual(response.getheader('Echo-Uri'), '/simple') self.assertEqual(response.getheader('Echo-Method'), 'DELETE') response = client.delete(uri='http://example.com/d') self.assertEqual(response.getheader('Echo-Uri'), '/d') self.assertEqual(response.getheader('Echo-Method'), 'DELETE') self.assert_( response.getheader('User-Agent').startswith('my new app gdata-py/')) def suite(): return unittest.TestSuite((unittest.makeSuite(AtomPubClientEchoTest, 'test'), )) if __name__ == '__main__': unittest.main()
unknown
codeparrot/codeparrot-clean
export const x00 = "x00"; export const x01 = "x01"; export const x02 = "x02"; export const x03 = "x03"; export const x04 = "x04"; export const x05 = "x05"; export const x06 = "x06"; export const x07 = "x07"; export const x08 = "x08"; export const x09 = "x09"; export const x10 = "x10"; export const x11 = "x11"; export const x12 = "x12"; export const x13 = "x13"; export const x14 = "x14"; export const x15 = "x15"; export const x16 = "x16"; export const x17 = "x17"; export const x18 = "x18"; export const x19 = "x19"; export const x20 = "x20"; export const x21 = "x21"; export const x22 = "x22"; export const x23 = "x23"; export const x24 = "x24"; export const x25 = "x25"; export const x26 = "x26"; export const x27 = "x27"; export const x28 = "x28"; export const x29 = "x29"; export const x30 = "x30"; export const x31 = "x31"; export const x32 = "x32"; export const x33 = "x33"; export const x34 = "x34"; export const x35 = "x35"; export const x36 = "x36"; export const x37 = "x37"; export const x38 = "x38"; export const x39 = "x39"; export const x40 = "x40"; export const x41 = "x41"; export const x42 = "x42"; export const x43 = "x43"; export const x44 = "x44"; export const x45 = "x45"; export const x46 = "x46"; export const x47 = "x47"; export const x48 = "x48"; export const x49 = "x49"; export const y00 = "y00"; export const y01 = "y01"; export const y02 = "y02"; export const y03 = "y03"; export const y04 = "y04"; export const y05 = "y05"; export const y06 = "y06"; export const y07 = "y07"; export const y08 = "y08"; export const y09 = "y09"; export const y10 = "y10"; export const y11 = "y11"; export const y12 = "y12"; export const y13 = "y13"; export const y14 = "y14"; export const y15 = "y15"; export const y16 = "y16"; export const y17 = "y17"; export const y18 = "y18"; export const y19 = "y19"; export const y20 = "y20"; export const y21 = "y21"; export const y22 = "y22"; export const y23 = "y23"; export const y24 = "y24"; export const y25 = "y25"; export const y26 = "y26"; export const y27 = "y27"; export const y28 = "y28"; export const y29 = "y29"; export const y30 = "y30"; export const y31 = "y31"; export const y32 = "y32"; export const y33 = "y33"; export const y34 = "y34"; export const y35 = "y35"; export const y36 = "y36"; export const y37 = "y37"; export const y38 = "y38"; export const y39 = "y39"; export const y40 = "y40"; export const y41 = "y41"; export const y42 = "y42"; export const y43 = "y43"; export const y44 = "y44"; export const y45 = "y45"; export const y46 = "y46"; export const y47 = "y47"; export const y48 = "y48"; export const y49 = "y49";
javascript
github
https://github.com/webpack/webpack
test/cases/optimize/many-exports-100/module.js
# Run tests for functions in Python/fileutils.c. import os import os.path import unittest from test.support import import_helper # Skip this test if the _testcapi module isn't available. _testcapi = import_helper.import_module('_testinternalcapi') class PathTests(unittest.TestCase): def test_capi_normalize_path(self): if os.name == 'nt': raise unittest.SkipTest('Windows has its own helper for this') else: from test.test_posixpath import PosixPathTest as posixdata tests = posixdata.NORMPATH_CASES for filename, expected in tests: if not os.path.isabs(filename): continue with self.subTest(filename): result = _testcapi.normalize_path(filename) self.assertEqual(result, expected, msg=f'input: {filename!r} expected output: {expected!r}') if __name__ == "__main__": unittest.main()
python
github
https://github.com/python/cpython
Lib/test/test_fileutils.py
# This file is part of Buildbot. Buildbot is free software: you can # redistribute it and/or modify it under the terms of the GNU General Public # License as published by the Free Software Foundation, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # Copyright Buildbot Team Members from __future__ import absolute_import from __future__ import print_function from twisted.internet import defer from buildbot.mq import base from buildbot.test.util import validation from buildbot.util import service from buildbot.util import tuplematch class FakeMQConnector(service.AsyncMultiService, base.MQBase): # a fake connector that doesn't actually bridge messages from production to # consumption, and thus doesn't do any topic handling or persistence # note that this *does* verify all messages sent and received, unless this # is set to false: verifyMessages = True def __init__(self, testcase): service.AsyncMultiService.__init__(self) self.testcase = testcase self.setup_called = False self.productions = [] self.qrefs = [] def setup(self): self.setup_called = True return defer.succeed(None) def produce(self, routingKey, data): self.testcase.assertIsInstance(routingKey, tuple) # XXX this is incompatible with the new scheme of sending multiple messages, # since the message type is no longer encoded by the first element of the # routing key # if self.verifyMessages: # validation.verifyMessage(self.testcase, routingKey, data) if any(not isinstance(k, str) for k in routingKey): raise AssertionError("%s is not all str" % (routingKey,)) self.productions.append((routingKey, data)) # note - no consumers are called: IT'S A FAKE def callConsumer(self, routingKey, msg): if self.verifyMessages: validation.verifyMessage(self.testcase, routingKey, msg) matched = False for q in self.qrefs: if tuplematch.matchTuple(routingKey, q.filter): matched = True q.callback(routingKey, msg) if not matched: raise AssertionError("no consumer found") def startConsuming(self, callback, filter, persistent_name=None): if any(not isinstance(k, str) and k is not None for k in filter): raise AssertionError("%s is not a filter" % (filter,)) qref = FakeQueueRef() qref.qrefs = self.qrefs qref.callback = callback qref.filter = filter qref.persistent_name = persistent_name self.qrefs.append(qref) return defer.succeed(qref) def clearProductions(self): "Clear out the cached productions" self.productions = [] def assertProductions(self, exp, orderMatters=True): """Assert that the given messages have been produced, then flush the list of produced messages. If C{orderMatters} is false, then the messages are sorted first; use this in cases where the messages must all be produced, but the order is not specified. """ if orderMatters: self.testcase.assertEqual(self.productions, exp) else: self.testcase.assertEqual(sorted(self.productions), sorted(exp)) self.productions = [] class FakeQueueRef(object): def stopConsuming(self): if self in self.qrefs: self.qrefs.remove(self)
unknown
codeparrot/codeparrot-clean
{ "compilerOptions": { "target": "es5", "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": false, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, "isolatedModules": true, "jsx": "react-jsx", "incremental": true }, "include": [ "next-env.d.ts", "remark-html.d.ts", "**/*.ts", "**/*.tsx", "tailwind.config.js", "postcss.config.js" ], "exclude": ["node_modules"] }
json
github
https://github.com/vercel/next.js
examples/blog-with-comment/tsconfig.json
# Copyright 2017 The UAI-SDK Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== def add_uai_args(parser): uai = parser.add_argument_group('uai-args', 'the UAI related args') ''' Default work dir. The working dir for the traing job, it will contains: /data/data --data_dir /data/output --output_dir Note: DO NOT CHANGE THIS VALUE UCloud Train Job Executor Will Set it Automatically ''' uai.add_argument('--work_dir', type=str, default="/data", help='Default work path') ''' Default data path used in Training, all data will be downloaded into this path Please use data in this path as input for Training Note: DO NOT CHANGE THIS VALUE UCloud Train Job Executor Will Set it Automatically ''' uai.add_argument("--data_dir", type=str, default="/data/data", help="Default data path") ''' Default output path used in Training, files in this path will be uploaded to UFile after training finished. You can also assume your checkpoint files inside output_path (If you provided in the UCloud console), files will also be downloaded into this path befor Training start Note: DO NOT CHANGE THIS VALUE UCloud Train Job Executor Will Set it Automatically ''' uai.add_argument("--output_dir", type=str, default="/data/output", help="Default output path") ''' Default tensorboard output path used in Training, iles in this path will be uploaded to UFile after training finished. This dir is same as output_dir Note: DO NOT CHANGE THIS VALUE UCloud Train Job Executor Will Set it Automatically ''' uai.add_argument("--log_dir", type=str, default="/data/output", help="Default log path") ''' Define num_gpus for training Note: DO NOT CHANGE THIS VALUE UCloud Train Job Executor Will Set it Automatically ''' uai.add_argument("--num_gpus", type=int, help="Num of avaliable gpus")
unknown
codeparrot/codeparrot-clean
""" Settings that modify processing of user text input """ from askbot.conf.settings_wrapper import settings from askbot.conf.super_groups import DATA_AND_FORMATTING from askbot.deps.livesettings import ConfigurationGroup from askbot.deps.livesettings import BooleanValue, StringValue, LongStringValue from askbot import const from django.utils.translation import ugettext_lazy as _ import re MARKUP = ConfigurationGroup( 'MARKUP', _('Markup in posts'), super_group = DATA_AND_FORMATTING ) def regex_settings_validation(*args): """ Validate the regular expressions """ try: new_value = args[1] regex_list = new_value.split('\n') for i in range(0, len(regex_list)): re.compile(regex_list[i].strip()) return args[1] except Exception: # The regex is invalid, so we overwrite it with empty string return "" # removed as it's better to disable underscores by default # to fix issues in urls with the undrescores # #settings.register( # BooleanValue( # MARKUP, # 'MARKUP_CODE_FRIENDLY', # description = _('Enable code-friendly Markdown'), # help_text = _( # 'If checked, underscore characters will not ' # 'trigger italic or bold formatting - ' # 'bold and italic text can still be marked up ' # 'with asterisks. Note that "MathJax support" ' # 'implicitly turns this feature on, because ' # 'underscores are heavily used in LaTeX input.' # ), # default = False # ) #) settings.register( BooleanValue( MARKUP, 'ENABLE_MATHJAX', description=_('Mathjax support (rendering of LaTeX)'), help_text=_( 'If you enable this feature, ' '<a href="%(url)s">mathjax</a> must be ' 'installed on your server in its own directory.' ) % { 'url': const.DEPENDENCY_URLS['mathjax'], }, default = False ) ) settings.register( StringValue( MARKUP, 'MATHJAX_BASE_URL', description=_('Base url of MathJax deployment'), help_text=_( 'Note - <strong>MathJax is not included with ' 'askbot</strong> - you should deploy it yourself, ' 'preferably at a separate domain and enter url ' 'pointing to the "mathjax" directory ' '(for example: http://mysite.com/mathjax)' ), default = '' ) ) settings.register( BooleanValue( MARKUP, 'ENABLE_AUTO_LINKING', description=_('Enable autolinking with specific patterns'), help_text=_( 'If you enable this feature, ' 'the application will be able to ' 'detect patterns and auto link to URLs' ), default = False ) ) settings.register( LongStringValue( MARKUP, 'AUTO_LINK_PATTERNS', description=_('Regexes to detect the link patterns'), help_text=_( 'Enter valid regular expressions for the patters,' ' one per line.' ' For example to' ' detect a bug pattern like #bug123,' ' use the following regex: #bug(\d+). The numbers' ' captured by the pattern in the parentheses will' ' be transferred to the link url template.' ' Please look up more information about regular' ' expressions elsewhere.' ), update_callback=regex_settings_validation, default = '' ) ) settings.register( LongStringValue( MARKUP, 'AUTO_LINK_URLS', description=_('URLs for autolinking'), help_text=_( 'Here, please enter url templates for the patterns' ' entered in the previous setting, also one entry per line.' ' <strong>Make sure that number of lines in this setting' ' and the previous one are the same</strong>' ' For example template' ' https://bugzilla.redhat.com/show_bug.cgi?id=\\1' ' together with the pattern shown above' ' and the entry in the post #123' ' will produce link to the bug 123 in the redhat bug tracker.' ), default = '' ) )
unknown
codeparrot/codeparrot-clean
"Test statusbar, coverage 100%." from idlelib import statusbar import unittest from test.support import requires from tkinter import Tk class Test(unittest.TestCase): @classmethod def setUpClass(cls): requires('gui') cls.root = Tk() cls.root.withdraw() @classmethod def tearDownClass(cls): cls.root.update_idletasks() cls.root.destroy() del cls.root def test_init(self): bar = statusbar.MultiStatusBar(self.root) self.assertEqual(bar.labels, {}) def test_set_label(self): bar = statusbar.MultiStatusBar(self.root) bar.set_label('left', text='sometext', width=10) self.assertIn('left', bar.labels) left = bar.labels['left'] self.assertEqual(left['text'], 'sometext') self.assertEqual(left['width'], 10) bar.set_label('left', text='revised text') self.assertEqual(left['text'], 'revised text') bar.set_label('right', text='correct text') self.assertEqual(bar.labels['right']['text'], 'correct text') if __name__ == '__main__': unittest.main(verbosity=2)
python
github
https://github.com/python/cpython
Lib/idlelib/idle_test/test_statusbar.py
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file import os,sys from waflib.TaskGen import feature,after_method from waflib import Utils,Task,Logs,Options testlock=Utils.threading.Lock() @feature('test') @after_method('apply_link') def make_test(self): if getattr(self,'link_task',None): self.create_task('utest',self.link_task.outputs) class utest(Task.Task): color='PINK' after=['vnum','inst'] vars=[] def runnable_status(self): if getattr(Options.options,'no_tests',False): return Task.SKIP_ME ret=super(utest,self).runnable_status() if ret==Task.SKIP_ME: if getattr(Options.options,'all_tests',False): return Task.RUN_ME return ret def run(self): filename=self.inputs[0].abspath() self.ut_exec=getattr(self.generator,'ut_exec',[filename]) if getattr(self.generator,'ut_fun',None): self.generator.ut_fun(self) try: fu=getattr(self.generator.bld,'all_test_paths') except AttributeError: fu=os.environ.copy() lst=[] for g in self.generator.bld.groups: for tg in g: if getattr(tg,'link_task',None): s=tg.link_task.outputs[0].parent.abspath() if s not in lst: lst.append(s) def add_path(dct,path,var): dct[var]=os.pathsep.join(Utils.to_list(path)+[os.environ.get(var,'')]) if Utils.is_win32: add_path(fu,lst,'PATH') elif Utils.unversioned_sys_platform()=='darwin': add_path(fu,lst,'DYLD_LIBRARY_PATH') add_path(fu,lst,'LD_LIBRARY_PATH') else: add_path(fu,lst,'LD_LIBRARY_PATH') self.generator.bld.all_test_paths=fu cwd=getattr(self.generator,'ut_cwd','')or self.inputs[0].parent.abspath() testcmd=getattr(Options.options,'testcmd',False) if testcmd: self.ut_exec=(testcmd%self.ut_exec[0]).split(' ') proc=Utils.subprocess.Popen(self.ut_exec,cwd=cwd,env=fu,stderr=Utils.subprocess.PIPE,stdout=Utils.subprocess.PIPE) (stdout,stderr)=proc.communicate() tup=(filename,proc.returncode,stdout,stderr) self.generator.utest_result=tup testlock.acquire() try: bld=self.generator.bld Logs.debug("ut: %r",tup) try: bld.utest_results.append(tup) except AttributeError: bld.utest_results=[tup] finally: testlock.release() def summary(bld): lst=getattr(bld,'utest_results',[]) if lst: Logs.pprint('CYAN','execution summary') total=len(lst) tfail=len([x for x in lst if x[1]]) Logs.pprint('CYAN',' tests that pass %d/%d'%(total-tfail,total)) for(f,code,out,err)in lst: if not code: Logs.pprint('CYAN',' %s'%f) Logs.pprint('CYAN',' tests that fail %d/%d'%(tfail,total)) for(f,code,out,err)in lst: if code: Logs.pprint('CYAN',' %s'%f) def set_exit_code(bld): lst=getattr(bld,'utest_results',[]) for(f,code,out,err)in lst: if code: msg=[] if out: msg.append('stdout:%s%s'%(os.linesep,out.decode('utf-8'))) if err: msg.append('stderr:%s%s'%(os.linesep,err.decode('utf-8'))) bld.fatal(os.linesep.join(msg)) def options(opt): opt.add_option('--notests',action='store_true',default=False,help='Exec no unit tests',dest='no_tests') opt.add_option('--alltests',action='store_true',default=False,help='Exec all unit tests',dest='all_tests') opt.add_option('--testcmd',action='store',default=False,help='Run the unit tests using the test-cmd string'' example "--test-cmd="valgrind --error-exitcode=1'' %s" to run under valgrind',dest='testcmd')
unknown
codeparrot/codeparrot-clean
#!/usr/bin/python # # @author: Gaurav Rastogi (grastogi@avinetworks.com) # Eric Anderson (eanderson@avinetworks.com) # module_check: supported # Avi Version: 17.1.1 # # Copyright: (c) 2017 Gaurav Rastogi, <grastogi@avinetworks.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: avi_cloud author: Gaurav Rastogi (grastogi@avinetworks.com) short_description: Module for setup of Cloud Avi RESTful Object description: - This module is used to configure Cloud object - more examples at U(https://github.com/avinetworks/devops) requirements: [ avisdk ] version_added: "2.4" options: state: description: - The state that should be applied on the entity. default: present choices: ["absent", "present"] avi_api_update_method: description: - Default method for object update is HTTP PUT. - Setting to patch will override that behavior to use HTTP PATCH. version_added: "2.5" default: put choices: ["put", "patch"] avi_api_patch_op: description: - Patch operation to use when using avi_api_update_method as patch. version_added: "2.5" choices: ["add", "replace", "delete"] apic_configuration: description: - Apicconfiguration settings for cloud. apic_mode: description: - Boolean flag to set apic_mode. - Default value when not specified in API or module is interpreted by Avi Controller as False. aws_configuration: description: - Awsconfiguration settings for cloud. azure_configuration: description: - Field introduced in 17.2.1. version_added: "2.5" cloudstack_configuration: description: - Cloudstackconfiguration settings for cloud. custom_tags: description: - Custom tags for all avi created resources in the cloud infrastructure. - Field introduced in 17.1.5. version_added: "2.5" dhcp_enabled: description: - Select the ip address management scheme. - Default value when not specified in API or module is interpreted by Avi Controller as False. dns_provider_ref: description: - Dns profile for the cloud. - It is a reference to an object of type ipamdnsproviderprofile. docker_configuration: description: - Dockerconfiguration settings for cloud. east_west_dns_provider_ref: description: - Dns profile for east-west services. - It is a reference to an object of type ipamdnsproviderprofile. east_west_ipam_provider_ref: description: - Ipam profile for east-west services. - Warning - please use virtual subnets in this ipam profile that do not conflict with the underlay networks or any overlay networks in the cluster. - For example in aws and gcp, 169.254.0.0/16 is used for storing instance metadata. - Hence, it should not be used in this profile. - It is a reference to an object of type ipamdnsproviderprofile. enable_vip_static_routes: description: - Use static routes for vip side network resolution during virtualservice placement. - Default value when not specified in API or module is interpreted by Avi Controller as False. ipam_provider_ref: description: - Ipam profile for the cloud. - It is a reference to an object of type ipamdnsproviderprofile. license_tier: description: - Specifies the default license tier which would be used by new se groups. - This field by default inherits the value from system configuration. - Enum options - ENTERPRISE_16, ENTERPRISE_18. - Field introduced in 17.2.5. version_added: "2.5" license_type: description: - If no license type is specified then default license enforcement for the cloud type is chosen. - The default mappings are container cloud is max ses, openstack and vmware is cores and linux it is sockets. - Enum options - LIC_BACKEND_SERVERS, LIC_SOCKETS, LIC_CORES, LIC_HOSTS, LIC_SE_BANDWIDTH. linuxserver_configuration: description: - Linuxserverconfiguration settings for cloud. mesos_configuration: description: - Mesosconfiguration settings for cloud. mtu: description: - Mtu setting for the cloud. - Default value when not specified in API or module is interpreted by Avi Controller as 1500. - Units(BYTES). name: description: - Name of the object. required: true nsx_configuration: description: - Configuration parameters for nsx manager. - Field introduced in 17.1.1. obj_name_prefix: description: - Default prefix for all automatically created objects in this cloud. - This prefix can be overridden by the se-group template. openstack_configuration: description: - Openstackconfiguration settings for cloud. oshiftk8s_configuration: description: - Oshiftk8sconfiguration settings for cloud. prefer_static_routes: description: - Prefer static routes over interface routes during virtualservice placement. - Default value when not specified in API or module is interpreted by Avi Controller as False. proxy_configuration: description: - Proxyconfiguration settings for cloud. rancher_configuration: description: - Rancherconfiguration settings for cloud. state_based_dns_registration: description: - Dns records for vips are added/deleted based on the operational state of the vips. - Field introduced in 17.1.12. - Default value when not specified in API or module is interpreted by Avi Controller as True. version_added: "2.5" tenant_ref: description: - It is a reference to an object of type tenant. url: description: - Avi controller URL of the object. uuid: description: - Unique object identifier of the object. vca_configuration: description: - Vcloudairconfiguration settings for cloud. vcenter_configuration: description: - Vcenterconfiguration settings for cloud. vtype: description: - Cloud type. - Enum options - CLOUD_NONE, CLOUD_VCENTER, CLOUD_OPENSTACK, CLOUD_AWS, CLOUD_VCA, CLOUD_APIC, CLOUD_MESOS, CLOUD_LINUXSERVER, CLOUD_DOCKER_UCP, - CLOUD_RANCHER, CLOUD_OSHIFT_K8S, CLOUD_AZURE. - Default value when not specified in API or module is interpreted by Avi Controller as CLOUD_NONE. required: true extends_documentation_fragment: - avi ''' EXAMPLES = """ - name: Create a VMWare cloud with write access mode avi_cloud: username: '{{ username }}' controller: '{{ controller }}' password: '{{ password }}' apic_mode: false dhcp_enabled: true enable_vip_static_routes: false license_type: LIC_CORES mtu: 1500 name: VCenter Cloud prefer_static_routes: false tenant_ref: admin vcenter_configuration: datacenter_ref: /api/vimgrdcruntime/datacenter-2-10.10.20.100 management_network: /api/vimgrnwruntime/dvportgroup-103-10.10.20.100 password: password privilege: WRITE_ACCESS username: user vcenter_url: 10.10.20.100 vtype: CLOUD_VCENTER """ RETURN = ''' obj: description: Cloud (api/cloud) object returned: success, changed type: dict ''' from ansible.module_utils.basic import AnsibleModule try: from ansible.module_utils.network.avi.avi import ( avi_common_argument_spec, HAS_AVI, avi_ansible_api) except ImportError: HAS_AVI = False def main(): argument_specs = dict( state=dict(default='present', choices=['absent', 'present']), avi_api_update_method=dict(default='put', choices=['put', 'patch']), avi_api_patch_op=dict(choices=['add', 'replace', 'delete']), apic_configuration=dict(type='dict',), apic_mode=dict(type='bool',), aws_configuration=dict(type='dict',), azure_configuration=dict(type='dict',), cloudstack_configuration=dict(type='dict',), custom_tags=dict(type='list',), dhcp_enabled=dict(type='bool',), dns_provider_ref=dict(type='str',), docker_configuration=dict(type='dict',), east_west_dns_provider_ref=dict(type='str',), east_west_ipam_provider_ref=dict(type='str',), enable_vip_static_routes=dict(type='bool',), ipam_provider_ref=dict(type='str',), license_tier=dict(type='str',), license_type=dict(type='str',), linuxserver_configuration=dict(type='dict',), mesos_configuration=dict(type='dict',), mtu=dict(type='int',), name=dict(type='str', required=True), nsx_configuration=dict(type='dict',), obj_name_prefix=dict(type='str',), openstack_configuration=dict(type='dict',), oshiftk8s_configuration=dict(type='dict',), prefer_static_routes=dict(type='bool',), proxy_configuration=dict(type='dict',), rancher_configuration=dict(type='dict',), state_based_dns_registration=dict(type='bool',), tenant_ref=dict(type='str',), url=dict(type='str',), uuid=dict(type='str',), vca_configuration=dict(type='dict',), vcenter_configuration=dict(type='dict',), vtype=dict(type='str', required=True), ) argument_specs.update(avi_common_argument_spec()) module = AnsibleModule( argument_spec=argument_specs, supports_check_mode=True) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk>=17.1) is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) return avi_ansible_api(module, 'cloud', set([])) if __name__ == '__main__': main()
unknown
codeparrot/codeparrot-clean
"Test pyshell, coverage 12%." # Plus coverage of test_warning. Was 20% with test_openshell. from idlelib import pyshell import unittest from test.support import requires from tkinter import Tk class FunctionTest(unittest.TestCase): # Test stand-alone module level non-gui functions. def test_restart_line_wide(self): eq = self.assertEqual for file, mul, extra in (('', 22, ''), ('finame', 21, '=')): width = 60 bar = mul * '=' with self.subTest(file=file, bar=bar): file = file or 'Shell' line = pyshell.restart_line(width, file) eq(len(line), width) eq(line, f"{bar+extra} RESTART: {file} {bar}") def test_restart_line_narrow(self): expect, taglen = "= RESTART: Shell", 16 for width in (taglen-1, taglen, taglen+1): with self.subTest(width=width): self.assertEqual(pyshell.restart_line(width, ''), expect) self.assertEqual(pyshell.restart_line(taglen+2, ''), expect+' =') class PyShellFileListTest(unittest.TestCase): @classmethod def setUpClass(cls): requires('gui') cls.root = Tk() cls.root.withdraw() @classmethod def tearDownClass(cls): #cls.root.update_idletasks() ## for id in cls.root.tk.call('after', 'info'): ## cls.root.after_cancel(id) # Need for EditorWindow. cls.root.destroy() del cls.root def test_init(self): psfl = pyshell.PyShellFileList(self.root) self.assertEqual(psfl.EditorWindow, pyshell.PyShellEditorWindow) self.assertIsNone(psfl.pyshell) # The following sometimes causes 'invalid command name "109734456recolorize"'. # Uncommenting after_cancel above prevents this, but results in # TclError: bad window path name ".!listedtoplevel.!frame.text" # which is normally prevented by after_cancel. ## def test_openshell(self): ## pyshell.use_subprocess = False ## ps = pyshell.PyShellFileList(self.root).open_shell() ## self.assertIsInstance(ps, pyshell.PyShell) if __name__ == '__main__': unittest.main(verbosity=2)
unknown
codeparrot/codeparrot-clean
import os import shutil import sys from django.core.exceptions import ImproperlyConfigured from django.db.backends.base.creation import BaseDatabaseCreation from django.utils.six.moves import input class DatabaseCreation(BaseDatabaseCreation): def _get_test_db_name(self): test_database_name = self.connection.settings_dict['TEST']['NAME'] if test_database_name and test_database_name != ':memory:': if 'mode=memory' in test_database_name: raise ImproperlyConfigured( "Using `mode=memory` parameter in the database name is not allowed, " "use `:memory:` instead." ) return test_database_name if self.connection.features.can_share_in_memory_db: return 'file:memorydb_%s?mode=memory&cache=shared' % self.connection.alias return ':memory:' def _create_test_db(self, verbosity, autoclobber, keepdb=False): test_database_name = self._get_test_db_name() if keepdb: return test_database_name if not self.connection.is_in_memory_db(test_database_name): # Erase the old test database if verbosity >= 1: print("Destroying old test database for alias %s..." % ( self._get_database_display_str(verbosity, test_database_name), )) if os.access(test_database_name, os.F_OK): if not autoclobber: confirm = input( "Type 'yes' if you would like to try deleting the test " "database '%s', or 'no' to cancel: " % test_database_name ) if autoclobber or confirm == 'yes': try: os.remove(test_database_name) except Exception as e: sys.stderr.write("Got an error deleting the old test database: %s\n" % e) sys.exit(2) else: print("Tests cancelled.") sys.exit(1) return test_database_name def get_test_db_clone_settings(self, number): orig_settings_dict = self.connection.settings_dict source_database_name = orig_settings_dict['NAME'] if self.connection.is_in_memory_db(source_database_name): return orig_settings_dict else: new_settings_dict = orig_settings_dict.copy() root, ext = os.path.splitext(orig_settings_dict['NAME']) new_settings_dict['NAME'] = '{}_{}.{}'.format(root, number, ext) return new_settings_dict def _clone_test_db(self, number, verbosity, keepdb=False): source_database_name = self.connection.settings_dict['NAME'] target_database_name = self.get_test_db_clone_settings(number)['NAME'] # Forking automatically makes a copy of an in-memory database. if not self.connection.is_in_memory_db(source_database_name): # Erase the old test database if os.access(target_database_name, os.F_OK): if keepdb: return if verbosity >= 1: print("Destroying old test database for alias %s..." % ( self._get_database_display_str(verbosity, target_database_name), )) try: os.remove(target_database_name) except Exception as e: sys.stderr.write("Got an error deleting the old test database: %s\n" % e) sys.exit(2) try: shutil.copy(source_database_name, target_database_name) except Exception as e: sys.stderr.write("Got an error cloning the test database: %s\n" % e) sys.exit(2) def _destroy_test_db(self, test_database_name, verbosity): if test_database_name and not self.connection.is_in_memory_db(test_database_name): # Remove the SQLite database file os.remove(test_database_name) def test_db_signature(self): """ Returns a tuple that uniquely identifies a test database. This takes into account the special cases of ":memory:" and "" for SQLite since the databases will be distinct despite having the same TEST NAME. See http://www.sqlite.org/inmemorydb.html """ test_database_name = self._get_test_db_name() sig = [self.connection.settings_dict['NAME']] if self.connection.is_in_memory_db(test_database_name): sig.append(self.connection.alias) return tuple(sig)
unknown
codeparrot/codeparrot-clean
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( determine_ext, parse_duration, unified_strdate, ) class HuffPostIE(InfoExtractor): IE_DESC = 'Huffington Post' _VALID_URL = r'''(?x) https?://(embed\.)?live\.huffingtonpost\.com/ (?: r/segment/[^/]+/| HPLEmbedPlayer/\?segmentId= ) (?P<id>[0-9a-f]+)''' _TEST = { 'url': 'http://live.huffingtonpost.com/r/segment/legalese-it/52dd3e4b02a7602131000677', 'md5': '55f5e8981c1c80a64706a44b74833de8', 'info_dict': { 'id': '52dd3e4b02a7602131000677', 'ext': 'mp4', 'title': 'Legalese It! with @MikeSacksHP', 'description': 'This week on Legalese It, Mike talks to David Bosco about his new book on the ICC, "Rough Justice," he also discusses the Virginia AG\'s historic stance on gay marriage, the execution of Edgar Tamayo, the ICC\'s delay of Kenya\'s President and more. ', 'duration': 1549, 'upload_date': '20140124', }, 'params': { # m3u8 download 'skip_download': True, }, 'expected_warnings': ['HTTP Error 404: Not Found'], } def _real_extract(self, url): video_id = self._match_id(url) api_url = 'http://embed.live.huffingtonpost.com/api/segments/%s.json' % video_id data = self._download_json(api_url, video_id)['data'] video_title = data['title'] duration = parse_duration(data.get('running_time')) upload_date = unified_strdate( data.get('schedule', {}).get('starts_at') or data.get('segment_start_date_time')) description = data.get('description') thumbnails = [] for url in filter(None, data['images'].values()): m = re.match('.*-([0-9]+x[0-9]+)\.', url) if not m: continue thumbnails.append({ 'url': url, 'resolution': m.group(1), }) formats = [] sources = data.get('sources', {}) live_sources = list(sources.get('live', {}).items()) + list(sources.get('live_again', {}).items()) for key, url in live_sources: ext = determine_ext(url) if ext == 'm3u8': formats.extend(self._extract_m3u8_formats( url, video_id, ext='mp4', m3u8_id='hls', fatal=False)) elif ext == 'f4m': formats.extend(self._extract_f4m_formats( url + '?hdcore=2.9.5', video_id, f4m_id='hds', fatal=False)) else: formats.append({ 'format': key, 'format_id': key.replace('/', '.'), 'ext': 'mp4', 'url': url, 'vcodec': 'none' if key.startswith('audio/') else None, }) if not formats and data.get('fivemin_id'): return self.url_result('5min:%s' % data['fivemin_id']) self._sort_formats(formats) return { 'id': video_id, 'title': video_title, 'description': description, 'formats': formats, 'duration': duration, 'upload_date': upload_date, 'thumbnails': thumbnails, }
unknown
codeparrot/codeparrot-clean
from django.db import models # Create your models here. class Transaction(models.Model): # Transaction id sent by merchant. transaction_id = models.CharField(max_length=100) # Payment gateway type used in transaction payment_gateway_type = models.CharField(max_length=20, null=True, blank=True) # Map to PG_TYPE # Map to addedon transaction_date_time = models.DateTimeField(null=True, blank=True) # mode (credit card/ CD - Cheque / Net Banking) mode = models.CharField(max_length=10, null=True, blank=True) status = models.CharField(max_length=15, null=True, blank=True) amount = models.DecimalField(max_digits=19, decimal_places=6) # Unique id from PayU.in mihpayid = models.CharField(max_length=100, null=True, blank=True) bankcode = models.CharField(max_length=10, null=True, blank=True) # Reference number for the payment gateway (received in PG_TYPE) bank_ref_num = models.CharField(max_length=100, null=True, blank=True) discount = models.DecimalField(max_digits=19, decimal_places=6, default=0) additional_charges = models.DecimalField(max_digits=19, decimal_places=6, default=0) # Charged by Payu # Status of transaction in PayU system # Map to unmappedstatus(initiated/ in progress /dropped / bounced / captured / auth/ failed / usercancelled/ pending) txn_status_on_payu = models.CharField(max_length=20, null=True, blank=True) hash_status = models.CharField(max_length=100, null=True, blank=True) class Meta: app_label = 'payu' class CancelRefundCaptureRequests(models.Model): transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE) # PayU Request ID for a request in a Transaction. request_id = models.CharField(max_length=100) # Cancel or Refund or Capture Request request_type = models.CharField(max_length=20) # Status of webservice call status = models.CharField(max_length=15) message = models.CharField(max_length=100) # PayU ID mihpayid = models.CharField(max_length=100) # Bank Reference Number bank_ref_num = models.CharField(max_length=100, null=True, blank=True) amount = models.DecimalField(max_digits=19, decimal_places=6, default=0) error_code = models.CharField(max_length=10) class Meta: app_label = 'payu'
unknown
codeparrot/codeparrot-clean
/* * Copyright 2010-2025 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.api.renderer.types.renderers import org.jetbrains.kotlin.analysis.api.KaExperimentalApi import org.jetbrains.kotlin.analysis.api.KaSession import org.jetbrains.kotlin.analysis.api.KaSpi import org.jetbrains.kotlin.analysis.api.renderer.types.KaTypeRenderer import org.jetbrains.kotlin.analysis.api.types.KaTypeParameterType import org.jetbrains.kotlin.analysis.utils.printer.PrettyPrinter @KaSpi @KaExperimentalApi public interface KaTypeParameterTypeRenderer { public fun renderType( analysisSession: KaSession, type: KaTypeParameterType, typeRenderer: KaTypeRenderer, printer: PrettyPrinter, ) @KaExperimentalApi public object AS_SOURCE : KaTypeParameterTypeRenderer { override fun renderType( analysisSession: KaSession, type: KaTypeParameterType, typeRenderer: KaTypeRenderer, printer: PrettyPrinter, ) { printer { " ".separated( { typeRenderer.annotationsRenderer.renderAnnotations(analysisSession, type, printer) }, { typeRenderer.typeNameRenderer.renderName(analysisSession, type.name, type, typeRenderer, printer) with(analysisSession) { if (type.isMarkedNullable) { printer.append('?') } } } ) } } } }
kotlin
github
https://github.com/JetBrains/kotlin
analysis/analysis-api/src/org/jetbrains/kotlin/analysis/api/renderer/types/renderers/KaTypeParameterTypeRenderer.kt
# -*- coding: utf-8 -*- # #################################################################### # Copyright (C) 2005-2013 by the FIFE team # http://www.fifengine.net # This file is part of FIFE. # # FIFE is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # #################################################################### """ Pychan extension widgets. Extension widgets are partly experimental, partly rarely used widgets which are added here. They are by default not included in the widgets registry and thus cannot be loaded from XML files. Use L{pychan.widgets.registerWidget} to enable that. Not the same care to keep the API stable will be taken for them and before and if they are added (or replace) the standard widgets they will have to be reviewed in detail. """
unknown
codeparrot/codeparrot-clean
#!/bin/sh # # Copyright (c) 2013 Ramkumar Ramachandra # test_description='git rebase --autostash tests' GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main export GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME . ./test-lib.sh test_expect_success setup ' echo hello-world >file0 && git add . && test_tick && git commit -m "initial commit" && git checkout -b feature-branch && echo another-hello >file1 && echo goodbye >file2 && git add . && test_tick && git commit -m "second commit" && echo final-goodbye >file3 && git add . && test_tick && git commit -m "third commit" && git checkout -b unrelated-onto-branch main && echo unrelated >file4 && git add . && test_tick && git commit -m "unrelated commit" && git checkout -b related-onto-branch main && echo conflicting-change >file2 && git add . && test_tick && git commit -m "related commit" && remove_progress_re="$(printf "s/.*\\r//")" ' create_expected_success_apply () { cat >expected <<-EOF $(grep "^Created autostash: [0-9a-f][0-9a-f]*\$" actual) First, rewinding head to replay your work on top of it... Applying: second commit Applying: third commit Applied autostash. EOF } create_expected_success_merge () { q_to_cr >expected <<-EOF $(grep "^Created autostash: [0-9a-f][0-9a-f]*\$" actual) Applied autostash. Successfully rebased and updated refs/heads/rebased-feature-branch. EOF } create_expected_failure_apply () { cat >expected <<-EOF $(grep "^Created autostash: [0-9a-f][0-9a-f]*\$" actual) First, rewinding head to replay your work on top of it... Applying: second commit Applying: third commit Applying autostash resulted in conflicts. Your changes are safe in the stash. You can run "git stash pop" or "git stash drop" at any time. EOF } create_expected_failure_merge () { cat >expected <<-EOF $(grep "^Created autostash: [0-9a-f][0-9a-f]*\$" actual) Applying autostash resulted in conflicts. Your changes are safe in the stash. You can run "git stash pop" or "git stash drop" at any time. Successfully rebased and updated refs/heads/rebased-feature-branch. EOF } testrebase () { type=$1 dotest=$2 test_expect_success "rebase$type: restore autostash when pre-rebase hook fails" ' git checkout -f feature-branch && test_hook pre-rebase <<-\EOF && exit 1 EOF echo changed >file0 && test_must_fail git rebase $type --autostash -f HEAD^ && test_must_fail git rebase --quit 2>err && test_grep "no rebase in progress" err && echo changed >expect && test_cmp expect file0 ' test_expect_success "rebase$type: restore autostash when checkout onto fails" ' git checkout -f --detach feature-branch && echo uncommitted-content >file0 && echo untracked >file4 && test_when_finished "rm file4" && test_must_fail git rebase $type --autostash \ unrelated-onto-branch && test_must_fail git rebase --quit 2>err && test_grep "no rebase in progress" err && echo uncommitted-content >expect && test_cmp expect file0 ' test_expect_success "rebase$type: restore autostash when branch checkout fails" ' git checkout -f unrelated-onto-branch^ && echo uncommitted-content >file0 && echo untracked >file4 && test_when_finished "rm file4" && test_must_fail git rebase $type --autostash HEAD \ unrelated-onto-branch && test_must_fail git rebase --quit 2>err && test_grep "no rebase in progress" err && echo uncommitted-content >expect && test_cmp expect file0 ' test_expect_success "rebase$type: dirty worktree, --no-autostash" ' test_config rebase.autostash true && git reset --hard && git checkout -b rebased-feature-branch feature-branch && test_when_finished git branch -D rebased-feature-branch && test_when_finished git checkout feature-branch && echo dirty >>file3 && test_must_fail git rebase$type --no-autostash unrelated-onto-branch ' test_expect_success "rebase$type: dirty worktree, non-conflicting rebase" ' test_config rebase.autostash true && git reset --hard && git checkout -b rebased-feature-branch feature-branch && echo dirty >>file3 && git rebase$type unrelated-onto-branch >actual 2>&1 && grep unrelated file4 && grep dirty file3 && git checkout feature-branch ' test_expect_success "rebase$type --autostash: check output" ' test_when_finished git branch -D rebased-feature-branch && suffix=${type#\ --} && suffix=${suffix:-apply} && if test ${suffix} = "interactive"; then suffix=merge fi && create_expected_success_$suffix && sed "$remove_progress_re" <actual >actual2 && test_cmp expected actual2 ' test_expect_success "rebase$type: dirty index, non-conflicting rebase" ' test_config rebase.autostash true && git reset --hard && git checkout -b rebased-feature-branch feature-branch && test_when_finished git branch -D rebased-feature-branch && echo dirty >>file3 && git add file3 && git rebase$type unrelated-onto-branch && grep unrelated file4 && grep dirty file3 && git checkout feature-branch ' test_expect_success "rebase$type: conflicting rebase" ' test_config rebase.autostash true && git reset --hard && git checkout -b rebased-feature-branch feature-branch && test_when_finished git branch -D rebased-feature-branch && echo dirty >>file3 && test_must_fail git rebase$type related-onto-branch && test_path_is_file $dotest/autostash && test_path_is_missing file3 && rm -rf $dotest && git reset --hard && git checkout feature-branch ' test_expect_success "rebase$type: --continue" ' test_config rebase.autostash true && git reset --hard && git checkout -b rebased-feature-branch feature-branch && test_when_finished git branch -D rebased-feature-branch && echo dirty >>file3 && test_must_fail git rebase$type related-onto-branch && test_path_is_file $dotest/autostash && test_path_is_missing file3 && echo "conflicting-plus-goodbye" >file2 && git add file2 && git rebase --continue && test_path_is_missing $dotest/autostash && grep dirty file3 && git checkout feature-branch ' test_expect_success "rebase$type: --skip" ' test_config rebase.autostash true && git reset --hard && git checkout -b rebased-feature-branch feature-branch && test_when_finished git branch -D rebased-feature-branch && echo dirty >>file3 && test_must_fail git rebase$type related-onto-branch && test_path_is_file $dotest/autostash && test_path_is_missing file3 && git rebase --skip && test_path_is_missing $dotest/autostash && grep dirty file3 && git checkout feature-branch ' test_expect_success "rebase$type: --abort" ' test_config rebase.autostash true && git reset --hard && git checkout -b rebased-feature-branch feature-branch && test_when_finished git branch -D rebased-feature-branch && echo dirty >>file3 && test_must_fail git rebase$type related-onto-branch && test_path_is_file $dotest/autostash && test_path_is_missing file3 && git rebase --abort && test_path_is_missing $dotest/autostash && grep dirty file3 && git checkout feature-branch ' test_expect_success "rebase$type: --quit" ' test_config rebase.autostash true && git reset --hard && git checkout -b rebased-feature-branch feature-branch && test_when_finished git branch -D rebased-feature-branch && echo dirty >>file3 && git diff >expect && test_must_fail git rebase$type related-onto-branch && test_path_is_file $dotest/autostash && test_path_is_missing file3 && git rebase --quit && test_when_finished git stash drop && test_path_is_missing $dotest/autostash && ! grep dirty file3 && git stash show -p >actual && test_cmp expect actual && git reset --hard && git checkout feature-branch ' test_expect_success "rebase$type: non-conflicting rebase, conflicting stash" ' test_config rebase.autostash true && git reset --hard && git checkout -b rebased-feature-branch feature-branch && echo dirty >file4 && git add file4 && git rebase$type unrelated-onto-branch >actual 2>&1 && test_path_is_missing $dotest && git reset --hard && grep unrelated file4 && ! grep dirty file4 && git checkout feature-branch && git stash pop && grep dirty file4 ' test_expect_success "rebase$type: check output with conflicting stash" ' test_when_finished git branch -D rebased-feature-branch && suffix=${type#\ --} && suffix=${suffix:-apply} && if test ${suffix} = "interactive"; then suffix=merge fi && create_expected_failure_$suffix && sed "$remove_progress_re" <actual >actual2 && test_cmp expected actual2 ' } test_expect_success "rebase: fast-forward rebase" ' test_config rebase.autostash true && git reset --hard && git checkout -b behind-feature-branch feature-branch~1 && test_when_finished git branch -D behind-feature-branch && echo dirty >>file1 && git rebase feature-branch && grep dirty file1 && git checkout feature-branch ' test_expect_success "rebase: noop rebase" ' test_config rebase.autostash true && git reset --hard && git checkout -b same-feature-branch feature-branch && test_when_finished git branch -D same-feature-branch && echo dirty >>file1 && git rebase feature-branch && grep dirty file1 && git checkout feature-branch ' testrebase " --apply" .git/rebase-apply testrebase " --merge" .git/rebase-merge testrebase " --interactive" .git/rebase-merge test_expect_success 'abort rebase -i with --autostash' ' test_when_finished "git reset --hard" && echo uncommitted-content >file0 && ( write_script abort-editor.sh <<-\EOF && echo >"$1" EOF test_set_editor "$(pwd)/abort-editor.sh" && test_must_fail git rebase -i --autostash HEAD^ && rm -f abort-editor.sh ) && echo uncommitted-content >expected && test_cmp expected file0 ' test_expect_success 'restore autostash on editor failure' ' test_when_finished "git reset --hard" && echo uncommitted-content >file0 && ( test_set_editor "false" && test_must_fail git rebase -i --autostash HEAD^ ) && echo uncommitted-content >expected && test_cmp expected file0 ' test_expect_success 'autostash is saved on editor failure with conflict' ' test_when_finished "git reset --hard" && echo uncommitted-content >file0 && ( write_script abort-editor.sh <<-\EOF && echo conflicting-content >file0 exit 1 EOF test_set_editor "$(pwd)/abort-editor.sh" && test_must_fail git rebase -i --autostash HEAD^ && rm -f abort-editor.sh ) && echo conflicting-content >expected && test_cmp expected file0 && git checkout file0 && git stash pop && echo uncommitted-content >expected && test_cmp expected file0 ' test_expect_success 'autostash with dirty submodules' ' test_when_finished "git reset --hard && git checkout main" && git checkout -b with-submodule && git -c protocol.file.allow=always submodule add ./ sub && test_tick && git commit -m add-submodule && echo changed >sub/file0 && git rebase -i --autostash HEAD ' test_expect_success 'branch is left alone when possible' ' git checkout -b unchanged-branch && echo changed >file0 && git rebase --autostash unchanged-branch && test changed = "$(cat file0)" && test unchanged-branch = "$(git rev-parse --abbrev-ref HEAD)" ' test_expect_success 'never change active branch' ' git checkout -b not-the-feature-branch unrelated-onto-branch && test_when_finished "git reset --hard && git checkout main" && echo changed >file0 && git rebase --autostash not-the-feature-branch feature-branch && test_cmp_rev not-the-feature-branch unrelated-onto-branch ' test_expect_success 'autostash commit is marked as reachable' ' echo changed >file0 && git rebase --autostash --exec "git prune --expire=now" \ feature-branch^ feature-branch && # git rebase succeeds if the stash cannot be applied so we need to check # the contents of file0 echo changed >expect && test_cmp expect file0 ' test_done
unknown
github
https://github.com/git/git
t/t3420-rebase-autostash.sh
import fnmatch import os from django.conf import settings from django.core.exceptions import ImproperlyConfigured def matches_patterns(path, patterns=None): """ Return True or False depending on whether the ``path`` should be ignored (if it matches any pattern in ``ignore_patterns``). """ if patterns is None: patterns = [] for pattern in patterns: if fnmatch.fnmatchcase(path, pattern): return True return False def get_files(storage, ignore_patterns=None, location=''): """ Recursively walk the storage directories yielding the paths of all files that should be copied. """ if ignore_patterns is None: ignore_patterns = [] directories, files = storage.listdir(location) for fn in files: if matches_patterns(fn, ignore_patterns): continue if location: fn = os.path.join(location, fn) yield fn for dir in directories: if matches_patterns(dir, ignore_patterns): continue if location: dir = os.path.join(location, dir) for fn in get_files(storage, ignore_patterns, dir): yield fn def check_settings(base_url=None): """ Checks if the staticfiles settings have sane values. """ if base_url is None: base_url = settings.STATIC_URL if not base_url: raise ImproperlyConfigured( "You're using the staticfiles app " "without having set the required STATIC_URL setting.") if settings.MEDIA_URL == base_url: raise ImproperlyConfigured("The MEDIA_URL and STATIC_URL " "settings must have different values") if ((settings.MEDIA_ROOT and settings.STATIC_ROOT) and (settings.MEDIA_ROOT == settings.STATIC_ROOT)): raise ImproperlyConfigured("The MEDIA_ROOT and STATIC_ROOT " "settings must have different values")
unknown
codeparrot/codeparrot-clean
/* * Implementation of safe memory reclamation scheme using * quiescent states. See InternalDocs/qsbr.md. * * This is derived from the "GUS" safe memory reclamation technique * in FreeBSD written by Jeffrey Roberson. It is heavily modified. Any bugs * in this code are likely due to the modifications. * * The original copyright is preserved below. * * Copyright (c) 2019,2020 Jeffrey Roberson <jeff@FreeBSD.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice unmodified, this list of conditions, and the following * disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Python.h" #include "pycore_interp.h" // PyInterpreterState #include "pycore_pystate.h" // _PyThreadState_GET() #include "pycore_qsbr.h" #include "pycore_tstate.h" // _PyThreadStateImpl #include "pycore_stats.h" // FT_STAT_QSBR_POLL_INC() // Starting size of the array of qsbr thread states #define MIN_ARRAY_SIZE 8 // Allocate a QSBR thread state from the freelist static struct _qsbr_thread_state * qsbr_allocate(struct _qsbr_shared *shared) { struct _qsbr_thread_state *qsbr = shared->freelist; if (qsbr == NULL) { return NULL; } shared->freelist = qsbr->freelist_next; qsbr->freelist_next = NULL; qsbr->shared = shared; qsbr->allocated = true; return qsbr; } // Initialize (or reinitialize) the freelist of QSBR thread states static void initialize_new_array(struct _qsbr_shared *shared) { for (Py_ssize_t i = 0; i != shared->size; i++) { struct _qsbr_thread_state *qsbr = &shared->array[i].qsbr; if (qsbr->tstate != NULL) { // Update the thread state pointer to its QSBR state _PyThreadStateImpl *tstate = (_PyThreadStateImpl *)qsbr->tstate; tstate->qsbr = qsbr; } if (!qsbr->allocated) { // Push to freelist qsbr->freelist_next = shared->freelist; shared->freelist = qsbr; } } } // Grow the array of QSBR thread states. Returns 0 on success, -1 on failure. static int grow_thread_array(struct _qsbr_shared *shared) { Py_ssize_t new_size = shared->size * 2; if (new_size < MIN_ARRAY_SIZE) { new_size = MIN_ARRAY_SIZE; } struct _qsbr_pad *array = PyMem_RawCalloc(new_size, sizeof(*array)); if (array == NULL) { return -1; } struct _qsbr_pad *old = shared->array; if (old != NULL) { memcpy(array, shared->array, shared->size * sizeof(*array)); } shared->array = array; shared->size = new_size; shared->freelist = NULL; initialize_new_array(shared); PyMem_RawFree(old); return 0; } uint64_t _Py_qsbr_advance(struct _qsbr_shared *shared) { // NOTE: with 64-bit sequence numbers, we don't have to worry too much // about the wr_seq getting too far ahead of rd_seq, but if we ever use // 32-bit sequence numbers, we'll need to be more careful. return _Py_atomic_add_uint64(&shared->wr_seq, QSBR_INCR) + QSBR_INCR; } uint64_t _Py_qsbr_shared_next(struct _qsbr_shared *shared) { return _Py_qsbr_shared_current(shared) + QSBR_INCR; } static uint64_t qsbr_poll_scan(struct _qsbr_shared *shared) { // Synchronize with store in _Py_qsbr_attach(). We need to ensure that // the reads from each thread's sequence number are not reordered to see // earlier "offline" states. _Py_atomic_fence_seq_cst(); // Compute the minimum sequence number of all attached threads uint64_t min_seq = _Py_atomic_load_uint64(&shared->wr_seq); struct _qsbr_pad *array = shared->array; for (Py_ssize_t i = 0, size = shared->size; i != size; i++) { struct _qsbr_thread_state *qsbr = &array[i].qsbr; uint64_t seq = _Py_atomic_load_uint64(&qsbr->seq); if (seq != QSBR_OFFLINE && QSBR_LT(seq, min_seq)) { min_seq = seq; } } // Update the shared read sequence uint64_t rd_seq = _Py_atomic_load_uint64(&shared->rd_seq); if (QSBR_LT(rd_seq, min_seq)) { // It's okay if the compare-exchange failed: another thread updated it (void)_Py_atomic_compare_exchange_uint64(&shared->rd_seq, &rd_seq, min_seq); rd_seq = min_seq; } return rd_seq; } bool _Py_qsbr_poll(struct _qsbr_thread_state *qsbr, uint64_t goal) { assert(_Py_atomic_load_int_relaxed(&_PyThreadState_GET()->state) == _Py_THREAD_ATTACHED); assert(((_PyThreadStateImpl *)_PyThreadState_GET())->qsbr == qsbr); if (_Py_qbsr_goal_reached(qsbr, goal)) { return true; } FT_STAT_QSBR_POLL_INC(); uint64_t rd_seq = qsbr_poll_scan(qsbr->shared); return QSBR_LEQ(goal, rd_seq); } void _Py_qsbr_attach(struct _qsbr_thread_state *qsbr) { assert(qsbr->seq == 0 && "already attached"); uint64_t seq = _Py_qsbr_shared_current(qsbr->shared); _Py_atomic_store_uint64(&qsbr->seq, seq); // needs seq_cst } void _Py_qsbr_detach(struct _qsbr_thread_state *qsbr) { assert(qsbr->seq != 0 && "already detached"); _Py_atomic_store_uint64_release(&qsbr->seq, QSBR_OFFLINE); } Py_ssize_t _Py_qsbr_reserve(PyInterpreterState *interp) { struct _qsbr_shared *shared = &interp->qsbr; PyMutex_Lock(&shared->mutex); // Try allocating from our internal freelist struct _qsbr_thread_state *qsbr = qsbr_allocate(shared); // If there are no free entries, we pause all threads, grow the array, // and update the pointers in PyThreadState to entries in the new array. if (qsbr == NULL) { _PyEval_StopTheWorld(interp); if (grow_thread_array(shared) == 0) { qsbr = qsbr_allocate(shared); } _PyEval_StartTheWorld(interp); } // Return an index rather than the pointer because the array may be // resized and the pointer invalidated. Py_ssize_t index = -1; if (qsbr != NULL) { index = (struct _qsbr_pad *)qsbr - shared->array; } PyMutex_Unlock(&shared->mutex); return index; } void _Py_qsbr_register(_PyThreadStateImpl *tstate, PyInterpreterState *interp, Py_ssize_t index) { // Associate the QSBR state with the thread state struct _qsbr_shared *shared = &interp->qsbr; PyMutex_Lock(&shared->mutex); struct _qsbr_thread_state *qsbr = &interp->qsbr.array[index].qsbr; assert(qsbr->allocated && qsbr->tstate == NULL); qsbr->tstate = (PyThreadState *)tstate; tstate->qsbr = qsbr; PyMutex_Unlock(&shared->mutex); } void _Py_qsbr_unregister(PyThreadState *tstate) { struct _qsbr_shared *shared = &tstate->interp->qsbr; struct _PyThreadStateImpl *tstate_imp = (_PyThreadStateImpl*) tstate; // gh-119369: GIL must be released (if held) to prevent deadlocks, because // we might not have an active tstate, which means that blocking on PyMutex // locks will not implicitly release the GIL. assert(!tstate->holds_gil); PyMutex_Lock(&shared->mutex); // NOTE: we must load (or reload) the thread state's qbsr inside the mutex // because the array may have been resized (changing tstate->qsbr) while // we waited to acquire the mutex. struct _qsbr_thread_state *qsbr = tstate_imp->qsbr; assert(qsbr->seq == 0 && "thread state must be detached"); assert(qsbr->allocated && qsbr->tstate == tstate); tstate_imp->qsbr = NULL; qsbr->tstate = NULL; qsbr->allocated = false; qsbr->freelist_next = shared->freelist; shared->freelist = qsbr; PyMutex_Unlock(&shared->mutex); } void _Py_qsbr_fini(PyInterpreterState *interp) { struct _qsbr_shared *shared = &interp->qsbr; PyMem_RawFree(shared->array); shared->array = NULL; shared->size = 0; shared->freelist = NULL; } void _Py_qsbr_after_fork(_PyThreadStateImpl *tstate) { struct _qsbr_thread_state *this_qsbr = tstate->qsbr; struct _qsbr_shared *shared = this_qsbr->shared; _PyMutex_at_fork_reinit(&shared->mutex); for (Py_ssize_t i = 0; i != shared->size; i++) { struct _qsbr_thread_state *qsbr = &shared->array[i].qsbr; if (qsbr != this_qsbr && qsbr->allocated) { qsbr->tstate = NULL; qsbr->allocated = false; qsbr->freelist_next = shared->freelist; shared->freelist = qsbr; } } }
c
github
https://github.com/python/cpython
Python/qsbr.c
# Copyright 2008 VIFF Development Team. # # This file is part of VIFF, the Virtual Ideal Functionality Framework. # # VIFF is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License (LGPL) as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # VIFF is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General # Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with VIFF. If not, see <http://www.gnu.org/licenses/>. """Tests of the equality protocol(s).""" import operator from viff.equality import ProbabilisticEqualityMixin from viff.test.util import RuntimeTestCase, BinaryOperatorTestCase from viff.passive import PassiveRuntime #: Declare doctests for Trial. __doctests__ = ['viff.equality'] class EqualRuntime(PassiveRuntime, ProbabilisticEqualityMixin): """A runtime with the equality mixin.""" pass class ProbabilisticEqualityTestDifferent(BinaryOperatorTestCase, RuntimeTestCase): """Testing the equality with *a* and *b* different.""" # Arbitrarily chosen. a = 12442 b = 91243 runtime_class = EqualRuntime operator = operator.eq class ProbabilisticEqualityTestEqual(BinaryOperatorTestCase, RuntimeTestCase): """Testing the equality with *a* and *b* equal.""" a = 4023 b = 4023 runtime_class = EqualRuntime operator = operator.eq class ProbabilisticEqualityTestDiff1_1(BinaryOperatorTestCase, RuntimeTestCase): """Testing ``a == b`` where ``b = a + 1``.""" a = 0 b = 1 runtime_class = EqualRuntime operator = operator.eq class ProbabilisticEqualityTestDiff1_2(BinaryOperatorTestCase, RuntimeTestCase): """Testing ``a == b`` where ``a = b + 1``.""" a = 1 b = 0 runtime_class = EqualRuntime operator = operator.eq
unknown
codeparrot/codeparrot-clean
from __future__ import unicode_literals import boto import sure # noqa from moto import mock_ec2 @mock_ec2 def test_virtual_private_gateways(): conn = boto.connect_vpc('the_key', 'the_secret') vpn_gateway = conn.create_vpn_gateway('ipsec.1', 'us-east-1a') vpn_gateway.should_not.be.none vpn_gateway.id.should.match(r'vgw-\w+') vpn_gateway.type.should.equal('ipsec.1') vpn_gateway.state.should.equal('available') vpn_gateway.availability_zone.should.equal('us-east-1a') @mock_ec2 def test_describe_vpn_gateway(): conn = boto.connect_vpc('the_key', 'the_secret') vpn_gateway = conn.create_vpn_gateway('ipsec.1', 'us-east-1a') vgws = conn.get_all_vpn_gateways() vgws.should.have.length_of(1) gateway = vgws[0] gateway.id.should.match(r'vgw-\w+') gateway.id.should.equal(vpn_gateway.id) vpn_gateway.type.should.equal('ipsec.1') vpn_gateway.state.should.equal('available') vpn_gateway.availability_zone.should.equal('us-east-1a') @mock_ec2 def test_vpn_gateway_vpc_attachment(): conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") vpn_gateway = conn.create_vpn_gateway('ipsec.1', 'us-east-1a') conn.attach_vpn_gateway( vpn_gateway_id=vpn_gateway.id, vpc_id=vpc.id ) gateway = conn.get_all_vpn_gateways()[0] attachments = gateway.attachments attachments.should.have.length_of(1) attachments[0].vpc_id.should.equal(vpc.id) attachments[0].state.should.equal('attached') @mock_ec2 def test_delete_vpn_gateway(): conn = boto.connect_vpc('the_key', 'the_secret') vpn_gateway = conn.create_vpn_gateway('ipsec.1', 'us-east-1a') conn.delete_vpn_gateway(vpn_gateway.id) vgws = conn.get_all_vpn_gateways() vgws.should.have.length_of(0) @mock_ec2 def test_vpn_gateway_tagging(): conn = boto.connect_vpc('the_key', 'the_secret') vpn_gateway = conn.create_vpn_gateway('ipsec.1', 'us-east-1a') vpn_gateway.add_tag("a key", "some value") tag = conn.get_all_tags()[0] tag.name.should.equal("a key") tag.value.should.equal("some value") # Refresh the subnet vpn_gateway = conn.get_all_vpn_gateways()[0] vpn_gateway.tags.should.have.length_of(1) vpn_gateway.tags["a key"].should.equal("some value") @mock_ec2 def test_detach_vpn_gateway(): conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") vpn_gateway = conn.create_vpn_gateway('ipsec.1', 'us-east-1a') conn.attach_vpn_gateway( vpn_gateway_id=vpn_gateway.id, vpc_id=vpc.id ) gateway = conn.get_all_vpn_gateways()[0] attachments = gateway.attachments attachments.should.have.length_of(1) attachments[0].vpc_id.should.equal(vpc.id) attachments[0].state.should.equal('attached') conn.detach_vpn_gateway( vpn_gateway_id=vpn_gateway.id, vpc_id=vpc.id ) gateway = conn.get_all_vpn_gateways()[0] attachments = gateway.attachments attachments.should.have.length_of(0)
unknown
codeparrot/codeparrot-clean
/*------------------------------------------------------------------------- * * pgoutput.c * Logical Replication output plugin * * Copyright (c) 2012-2026, PostgreSQL Global Development Group * * IDENTIFICATION * src/backend/replication/pgoutput/pgoutput.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "access/tupconvert.h" #include "catalog/partition.h" #include "catalog/pg_publication.h" #include "catalog/pg_publication_rel.h" #include "catalog/pg_subscription.h" #include "commands/defrem.h" #include "commands/subscriptioncmds.h" #include "executor/executor.h" #include "fmgr.h" #include "nodes/makefuncs.h" #include "parser/parse_relation.h" #include "replication/logical.h" #include "replication/logicalproto.h" #include "replication/origin.h" #include "replication/pgoutput.h" #include "rewrite/rewriteHandler.h" #include "utils/builtins.h" #include "utils/inval.h" #include "utils/lsyscache.h" #include "utils/memutils.h" #include "utils/rel.h" #include "utils/syscache.h" #include "utils/varlena.h" PG_MODULE_MAGIC_EXT( .name = "pgoutput", .version = PG_VERSION ); static void pgoutput_startup(LogicalDecodingContext *ctx, OutputPluginOptions *opt, bool is_init); static void pgoutput_shutdown(LogicalDecodingContext *ctx); static void pgoutput_begin_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn); static void pgoutput_commit_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr commit_lsn); static void pgoutput_change(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, Relation relation, ReorderBufferChange *change); static void pgoutput_truncate(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, int nrelations, Relation relations[], ReorderBufferChange *change); static void pgoutput_message(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr message_lsn, bool transactional, const char *prefix, Size sz, const char *message); static bool pgoutput_origin_filter(LogicalDecodingContext *ctx, ReplOriginId origin_id); static void pgoutput_begin_prepare_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn); static void pgoutput_prepare_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr prepare_lsn); static void pgoutput_commit_prepared_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr commit_lsn); static void pgoutput_rollback_prepared_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr prepare_end_lsn, TimestampTz prepare_time); static void pgoutput_stream_start(struct LogicalDecodingContext *ctx, ReorderBufferTXN *txn); static void pgoutput_stream_stop(struct LogicalDecodingContext *ctx, ReorderBufferTXN *txn); static void pgoutput_stream_abort(struct LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr abort_lsn); static void pgoutput_stream_commit(struct LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr commit_lsn); static void pgoutput_stream_prepare_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr prepare_lsn); static bool publications_valid; static List *LoadPublications(List *pubnames); static void publication_invalidation_cb(Datum arg, int cacheid, uint32 hashvalue); static void send_repl_origin(LogicalDecodingContext *ctx, ReplOriginId origin_id, XLogRecPtr origin_lsn, bool send_origin); /* * Only 3 publication actions are used for row filtering ("insert", "update", * "delete"). See RelationSyncEntry.exprstate[]. */ enum RowFilterPubAction { PUBACTION_INSERT, PUBACTION_UPDATE, PUBACTION_DELETE, }; #define NUM_ROWFILTER_PUBACTIONS (PUBACTION_DELETE+1) /* * Entry in the map used to remember which relation schemas we sent. * * The schema_sent flag determines if the current schema record for the * relation (and for its ancestor if publish_as_relid is set) was already * sent to the subscriber (in which case we don't need to send it again). * * The schema cache on downstream is however updated only at commit time, * and with streamed transactions the commit order may be different from * the order the transactions are sent in. Also, the (sub) transactions * might get aborted so we need to send the schema for each (sub) transaction * so that we don't lose the schema information on abort. For handling this, * we maintain the list of xids (streamed_txns) for those we have already sent * the schema. * * For partitions, 'pubactions' considers not only the table's own * publications, but also those of all of its ancestors. */ typedef struct RelationSyncEntry { Oid relid; /* relation oid */ bool replicate_valid; /* overall validity flag for entry */ bool schema_sent; /* * This will be PUBLISH_GENCOLS_STORED if the relation contains generated * columns and the 'publish_generated_columns' parameter is set to * PUBLISH_GENCOLS_STORED. Otherwise, it will be PUBLISH_GENCOLS_NONE, * indicating that no generated columns should be published, unless * explicitly specified in the column list. */ PublishGencolsType include_gencols_type; List *streamed_txns; /* streamed toplevel transactions with this * schema */ /* are we publishing this rel? */ PublicationActions pubactions; /* * ExprState array for row filter. Different publication actions don't * allow multiple expressions to always be combined into one, because * updates or deletes restrict the column in expression to be part of the * replica identity index whereas inserts do not have this restriction, so * there is one ExprState per publication action. */ ExprState *exprstate[NUM_ROWFILTER_PUBACTIONS]; EState *estate; /* executor state used for row filter */ TupleTableSlot *new_slot; /* slot for storing new tuple */ TupleTableSlot *old_slot; /* slot for storing old tuple */ /* * OID of the relation to publish changes as. For a partition, this may * be set to one of its ancestors whose schema will be used when * replicating changes, if publish_via_partition_root is set for the * publication. */ Oid publish_as_relid; /* * Map used when replicating using an ancestor's schema to convert tuples * from partition's type to the ancestor's; NULL if publish_as_relid is * same as 'relid' or if unnecessary due to partition and the ancestor * having identical TupleDesc. */ AttrMap *attrmap; /* * Columns included in the publication, or NULL if all columns are * included implicitly. Note that the attnums in this bitmap are not * shifted by FirstLowInvalidHeapAttributeNumber. */ Bitmapset *columns; /* * Private context to store additional data for this entry - state for the * row filter expressions, column list, etc. */ MemoryContext entry_cxt; } RelationSyncEntry; /* * Maintain a per-transaction level variable to track whether the transaction * has sent BEGIN. BEGIN is only sent when the first change in a transaction * is processed. This makes it possible to skip sending a pair of BEGIN/COMMIT * messages for empty transactions which saves network bandwidth. * * This optimization is not used for prepared transactions because if the * WALSender restarts after prepare of a transaction and before commit prepared * of the same transaction then we won't be able to figure out if we have * skipped sending BEGIN/PREPARE of a transaction as it was empty. This is * because we would have lost the in-memory txndata information that was * present prior to the restart. This will result in sending a spurious * COMMIT PREPARED without a corresponding prepared transaction at the * downstream which would lead to an error when it tries to process it. * * XXX We could achieve this optimization by changing protocol to send * additional information so that downstream can detect that the corresponding * prepare has not been sent. However, adding such a check for every * transaction in the downstream could be costly so we might want to do it * optionally. * * We also don't have this optimization for streamed transactions because * they can contain prepared transactions. */ typedef struct PGOutputTxnData { bool sent_begin_txn; /* flag indicating whether BEGIN has been sent */ } PGOutputTxnData; /* Map used to remember which relation schemas we sent. */ static HTAB *RelationSyncCache = NULL; static void init_rel_sync_cache(MemoryContext cachectx); static void cleanup_rel_sync_cache(TransactionId xid, bool is_commit); static RelationSyncEntry *get_rel_sync_entry(PGOutputData *data, Relation relation); static void send_relation_and_attrs(Relation relation, TransactionId xid, LogicalDecodingContext *ctx, RelationSyncEntry *relentry); static void rel_sync_cache_relation_cb(Datum arg, Oid relid); static void rel_sync_cache_publication_cb(Datum arg, int cacheid, uint32 hashvalue); static void set_schema_sent_in_streamed_txn(RelationSyncEntry *entry, TransactionId xid); static bool get_schema_sent_in_streamed_txn(RelationSyncEntry *entry, TransactionId xid); static void init_tuple_slot(PGOutputData *data, Relation relation, RelationSyncEntry *entry); static void pgoutput_memory_context_reset(void *arg); /* row filter routines */ static EState *create_estate_for_relation(Relation rel); static void pgoutput_row_filter_init(PGOutputData *data, List *publications, RelationSyncEntry *entry); static bool pgoutput_row_filter_exec_expr(ExprState *state, ExprContext *econtext); static bool pgoutput_row_filter(Relation relation, TupleTableSlot *old_slot, TupleTableSlot **new_slot_ptr, RelationSyncEntry *entry, ReorderBufferChangeType *action); /* column list routines */ static void pgoutput_column_list_init(PGOutputData *data, List *publications, RelationSyncEntry *entry); /* * Specify output plugin callbacks */ void _PG_output_plugin_init(OutputPluginCallbacks *cb) { cb->startup_cb = pgoutput_startup; cb->begin_cb = pgoutput_begin_txn; cb->change_cb = pgoutput_change; cb->truncate_cb = pgoutput_truncate; cb->message_cb = pgoutput_message; cb->commit_cb = pgoutput_commit_txn; cb->begin_prepare_cb = pgoutput_begin_prepare_txn; cb->prepare_cb = pgoutput_prepare_txn; cb->commit_prepared_cb = pgoutput_commit_prepared_txn; cb->rollback_prepared_cb = pgoutput_rollback_prepared_txn; cb->filter_by_origin_cb = pgoutput_origin_filter; cb->shutdown_cb = pgoutput_shutdown; /* transaction streaming */ cb->stream_start_cb = pgoutput_stream_start; cb->stream_stop_cb = pgoutput_stream_stop; cb->stream_abort_cb = pgoutput_stream_abort; cb->stream_commit_cb = pgoutput_stream_commit; cb->stream_change_cb = pgoutput_change; cb->stream_message_cb = pgoutput_message; cb->stream_truncate_cb = pgoutput_truncate; /* transaction streaming - two-phase commit */ cb->stream_prepare_cb = pgoutput_stream_prepare_txn; } static void parse_output_parameters(List *options, PGOutputData *data) { ListCell *lc; bool protocol_version_given = false; bool publication_names_given = false; bool binary_option_given = false; bool messages_option_given = false; bool streaming_given = false; bool two_phase_option_given = false; bool origin_option_given = false; /* Initialize optional parameters to defaults */ data->binary = false; data->streaming = LOGICALREP_STREAM_OFF; data->messages = false; data->two_phase = false; data->publish_no_origin = false; foreach(lc, options) { DefElem *defel = (DefElem *) lfirst(lc); Assert(defel->arg == NULL || IsA(defel->arg, String)); /* Check each param, whether or not we recognize it */ if (strcmp(defel->defname, "proto_version") == 0) { unsigned long parsed; char *endptr; if (protocol_version_given) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("conflicting or redundant options"))); protocol_version_given = true; errno = 0; parsed = strtoul(strVal(defel->arg), &endptr, 10); if (errno != 0 || *endptr != '\0') ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("invalid proto_version"))); if (parsed > PG_UINT32_MAX) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("proto_version \"%s\" out of range", strVal(defel->arg)))); data->protocol_version = (uint32) parsed; } else if (strcmp(defel->defname, "publication_names") == 0) { if (publication_names_given) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("conflicting or redundant options"))); publication_names_given = true; /* * Pass a copy of the DefElem->arg since SplitIdentifierString * modifies its input. */ if (!SplitIdentifierString(pstrdup(strVal(defel->arg)), ',', &data->publication_names)) ereport(ERROR, (errcode(ERRCODE_INVALID_NAME), errmsg("invalid publication_names syntax"))); } else if (strcmp(defel->defname, "binary") == 0) { if (binary_option_given) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("conflicting or redundant options"))); binary_option_given = true; data->binary = defGetBoolean(defel); } else if (strcmp(defel->defname, "messages") == 0) { if (messages_option_given) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("conflicting or redundant options"))); messages_option_given = true; data->messages = defGetBoolean(defel); } else if (strcmp(defel->defname, "streaming") == 0) { if (streaming_given) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("conflicting or redundant options"))); streaming_given = true; data->streaming = defGetStreamingMode(defel); } else if (strcmp(defel->defname, "two_phase") == 0) { if (two_phase_option_given) ereport(ERROR, (errcode(ERRCODE_SYNTAX_ERROR), errmsg("conflicting or redundant options"))); two_phase_option_given = true; data->two_phase = defGetBoolean(defel); } else if (strcmp(defel->defname, "origin") == 0) { char *origin; if (origin_option_given) ereport(ERROR, errcode(ERRCODE_SYNTAX_ERROR), errmsg("conflicting or redundant options")); origin_option_given = true; origin = defGetString(defel); if (pg_strcasecmp(origin, LOGICALREP_ORIGIN_NONE) == 0) data->publish_no_origin = true; else if (pg_strcasecmp(origin, LOGICALREP_ORIGIN_ANY) == 0) data->publish_no_origin = false; else ereport(ERROR, errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("unrecognized origin value: \"%s\"", origin)); } else elog(ERROR, "unrecognized pgoutput option: %s", defel->defname); } /* Check required options */ if (!protocol_version_given) ereport(ERROR, errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("option \"%s\" missing", "proto_version")); if (!publication_names_given) ereport(ERROR, errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("option \"%s\" missing", "publication_names")); } /* * Memory context reset callback of PGOutputData->context. */ static void pgoutput_memory_context_reset(void *arg) { if (RelationSyncCache) { hash_destroy(RelationSyncCache); RelationSyncCache = NULL; } } /* * Initialize this plugin */ static void pgoutput_startup(LogicalDecodingContext *ctx, OutputPluginOptions *opt, bool is_init) { PGOutputData *data = palloc0_object(PGOutputData); static bool publication_callback_registered = false; MemoryContextCallback *mcallback; /* Create our memory context for private allocations. */ data->context = AllocSetContextCreate(ctx->context, "logical replication output context", ALLOCSET_DEFAULT_SIZES); data->cachectx = AllocSetContextCreate(ctx->context, "logical replication cache context", ALLOCSET_DEFAULT_SIZES); data->pubctx = AllocSetContextCreate(ctx->context, "logical replication publication list context", ALLOCSET_SMALL_SIZES); /* * Ensure to cleanup RelationSyncCache even when logical decoding invoked * via SQL interface ends up with an error. */ mcallback = palloc0_object(MemoryContextCallback); mcallback->func = pgoutput_memory_context_reset; MemoryContextRegisterResetCallback(ctx->context, mcallback); ctx->output_plugin_private = data; /* This plugin uses binary protocol. */ opt->output_type = OUTPUT_PLUGIN_BINARY_OUTPUT; /* * This is replication start and not slot initialization. * * Parse and validate options passed by the client. */ if (!is_init) { /* Parse the params and ERROR if we see any we don't recognize */ parse_output_parameters(ctx->output_plugin_options, data); /* Check if we support requested protocol */ if (data->protocol_version > LOGICALREP_PROTO_MAX_VERSION_NUM) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("client sent proto_version=%d but server only supports protocol %d or lower", data->protocol_version, LOGICALREP_PROTO_MAX_VERSION_NUM))); if (data->protocol_version < LOGICALREP_PROTO_MIN_VERSION_NUM) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("client sent proto_version=%d but server only supports protocol %d or higher", data->protocol_version, LOGICALREP_PROTO_MIN_VERSION_NUM))); /* * Decide whether to enable streaming. It is disabled by default, in * which case we just update the flag in decoding context. Otherwise * we only allow it with sufficient version of the protocol, and when * the output plugin supports it. */ if (data->streaming == LOGICALREP_STREAM_OFF) ctx->streaming = false; else if (data->streaming == LOGICALREP_STREAM_ON && data->protocol_version < LOGICALREP_PROTO_STREAM_VERSION_NUM) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("requested proto_version=%d does not support streaming, need %d or higher", data->protocol_version, LOGICALREP_PROTO_STREAM_VERSION_NUM))); else if (data->streaming == LOGICALREP_STREAM_PARALLEL && data->protocol_version < LOGICALREP_PROTO_STREAM_PARALLEL_VERSION_NUM) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("requested proto_version=%d does not support parallel streaming, need %d or higher", data->protocol_version, LOGICALREP_PROTO_STREAM_PARALLEL_VERSION_NUM))); else if (!ctx->streaming) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("streaming requested, but not supported by output plugin"))); /* * Here, we just check whether the two-phase option is passed by * plugin and decide whether to enable it at later point of time. It * remains enabled if the previous start-up has done so. But we only * allow the option to be passed in with sufficient version of the * protocol, and when the output plugin supports it. */ if (!data->two_phase) ctx->twophase_opt_given = false; else if (data->protocol_version < LOGICALREP_PROTO_TWOPHASE_VERSION_NUM) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("requested proto_version=%d does not support two-phase commit, need %d or higher", data->protocol_version, LOGICALREP_PROTO_TWOPHASE_VERSION_NUM))); else if (!ctx->twophase) ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("two-phase commit requested, but not supported by output plugin"))); else ctx->twophase_opt_given = true; /* Init publication state. */ data->publications = NIL; publications_valid = false; /* * Register callback for pg_publication if we didn't already do that * during some previous call in this process. */ if (!publication_callback_registered) { CacheRegisterSyscacheCallback(PUBLICATIONOID, publication_invalidation_cb, (Datum) 0); CacheRegisterRelSyncCallback(rel_sync_cache_relation_cb, (Datum) 0); publication_callback_registered = true; } /* Initialize relation schema cache. */ init_rel_sync_cache(CacheMemoryContext); } else { /* * Disable the streaming and prepared transactions during the slot * initialization mode. */ ctx->streaming = false; ctx->twophase = false; } } /* * BEGIN callback. * * Don't send the BEGIN message here instead postpone it until the first * change. In logical replication, a common scenario is to replicate a set of * tables (instead of all tables) and transactions whose changes were on * the table(s) that are not published will produce empty transactions. These * empty transactions will send BEGIN and COMMIT messages to subscribers, * using bandwidth on something with little/no use for logical replication. */ static void pgoutput_begin_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn) { PGOutputTxnData *txndata = MemoryContextAllocZero(ctx->context, sizeof(PGOutputTxnData)); txn->output_plugin_private = txndata; } /* * Send BEGIN. * * This is called while processing the first change of the transaction. */ static void pgoutput_send_begin(LogicalDecodingContext *ctx, ReorderBufferTXN *txn) { bool send_replication_origin = txn->origin_id != InvalidReplOriginId; PGOutputTxnData *txndata = (PGOutputTxnData *) txn->output_plugin_private; Assert(txndata); Assert(!txndata->sent_begin_txn); OutputPluginPrepareWrite(ctx, !send_replication_origin); logicalrep_write_begin(ctx->out, txn); txndata->sent_begin_txn = true; send_repl_origin(ctx, txn->origin_id, txn->origin_lsn, send_replication_origin); OutputPluginWrite(ctx, true); } /* * COMMIT callback */ static void pgoutput_commit_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr commit_lsn) { PGOutputTxnData *txndata = (PGOutputTxnData *) txn->output_plugin_private; bool sent_begin_txn; Assert(txndata); /* * We don't need to send the commit message unless some relevant change * from this transaction has been sent to the downstream. */ sent_begin_txn = txndata->sent_begin_txn; OutputPluginUpdateProgress(ctx, !sent_begin_txn); pfree(txndata); txn->output_plugin_private = NULL; if (!sent_begin_txn) { elog(DEBUG1, "skipped replication of an empty transaction with XID: %u", txn->xid); return; } OutputPluginPrepareWrite(ctx, true); logicalrep_write_commit(ctx->out, txn, commit_lsn); OutputPluginWrite(ctx, true); } /* * BEGIN PREPARE callback */ static void pgoutput_begin_prepare_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn) { bool send_replication_origin = txn->origin_id != InvalidReplOriginId; OutputPluginPrepareWrite(ctx, !send_replication_origin); logicalrep_write_begin_prepare(ctx->out, txn); send_repl_origin(ctx, txn->origin_id, txn->origin_lsn, send_replication_origin); OutputPluginWrite(ctx, true); } /* * PREPARE callback */ static void pgoutput_prepare_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr prepare_lsn) { OutputPluginUpdateProgress(ctx, false); OutputPluginPrepareWrite(ctx, true); logicalrep_write_prepare(ctx->out, txn, prepare_lsn); OutputPluginWrite(ctx, true); } /* * COMMIT PREPARED callback */ static void pgoutput_commit_prepared_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr commit_lsn) { OutputPluginUpdateProgress(ctx, false); OutputPluginPrepareWrite(ctx, true); logicalrep_write_commit_prepared(ctx->out, txn, commit_lsn); OutputPluginWrite(ctx, true); } /* * ROLLBACK PREPARED callback */ static void pgoutput_rollback_prepared_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr prepare_end_lsn, TimestampTz prepare_time) { OutputPluginUpdateProgress(ctx, false); OutputPluginPrepareWrite(ctx, true); logicalrep_write_rollback_prepared(ctx->out, txn, prepare_end_lsn, prepare_time); OutputPluginWrite(ctx, true); } /* * Write the current schema of the relation and its ancestor (if any) if not * done yet. */ static void maybe_send_schema(LogicalDecodingContext *ctx, ReorderBufferChange *change, Relation relation, RelationSyncEntry *relentry) { PGOutputData *data = (PGOutputData *) ctx->output_plugin_private; bool schema_sent; TransactionId xid = InvalidTransactionId; TransactionId topxid = InvalidTransactionId; /* * Remember XID of the (sub)transaction for the change. We don't care if * it's top-level transaction or not (we have already sent that XID in * start of the current streaming block). * * If we're not in a streaming block, just use InvalidTransactionId and * the write methods will not include it. */ if (data->in_streaming) xid = change->txn->xid; if (rbtxn_is_subtxn(change->txn)) topxid = rbtxn_get_toptxn(change->txn)->xid; else topxid = xid; /* * Do we need to send the schema? We do track streamed transactions * separately, because those may be applied later (and the regular * transactions won't see their effects until then) and in an order that * we don't know at this point. * * XXX There is a scope of optimization here. Currently, we always send * the schema first time in a streaming transaction but we can probably * avoid that by checking 'relentry->schema_sent' flag. However, before * doing that we need to study its impact on the case where we have a mix * of streaming and non-streaming transactions. */ if (data->in_streaming) schema_sent = get_schema_sent_in_streamed_txn(relentry, topxid); else schema_sent = relentry->schema_sent; /* Nothing to do if we already sent the schema. */ if (schema_sent) return; /* * Send the schema. If the changes will be published using an ancestor's * schema, not the relation's own, send that ancestor's schema before * sending relation's own (XXX - maybe sending only the former suffices?). */ if (relentry->publish_as_relid != RelationGetRelid(relation)) { Relation ancestor = RelationIdGetRelation(relentry->publish_as_relid); send_relation_and_attrs(ancestor, xid, ctx, relentry); RelationClose(ancestor); } send_relation_and_attrs(relation, xid, ctx, relentry); if (data->in_streaming) set_schema_sent_in_streamed_txn(relentry, topxid); else relentry->schema_sent = true; } /* * Sends a relation */ static void send_relation_and_attrs(Relation relation, TransactionId xid, LogicalDecodingContext *ctx, RelationSyncEntry *relentry) { TupleDesc desc = RelationGetDescr(relation); Bitmapset *columns = relentry->columns; PublishGencolsType include_gencols_type = relentry->include_gencols_type; int i; /* * Write out type info if needed. We do that only for user-created types. * We use FirstGenbkiObjectId as the cutoff, so that we only consider * objects with hand-assigned OIDs to be "built in", not for instance any * function or type defined in the information_schema. This is important * because only hand-assigned OIDs can be expected to remain stable across * major versions. */ for (i = 0; i < desc->natts; i++) { Form_pg_attribute att = TupleDescAttr(desc, i); if (!logicalrep_should_publish_column(att, columns, include_gencols_type)) continue; if (att->atttypid < FirstGenbkiObjectId) continue; OutputPluginPrepareWrite(ctx, false); logicalrep_write_typ(ctx->out, xid, att->atttypid); OutputPluginWrite(ctx, false); } OutputPluginPrepareWrite(ctx, false); logicalrep_write_rel(ctx->out, xid, relation, columns, include_gencols_type); OutputPluginWrite(ctx, false); } /* * Executor state preparation for evaluation of row filter expressions for the * specified relation. */ static EState * create_estate_for_relation(Relation rel) { EState *estate; RangeTblEntry *rte; List *perminfos = NIL; estate = CreateExecutorState(); rte = makeNode(RangeTblEntry); rte->rtekind = RTE_RELATION; rte->relid = RelationGetRelid(rel); rte->relkind = rel->rd_rel->relkind; rte->rellockmode = AccessShareLock; addRTEPermissionInfo(&perminfos, rte); ExecInitRangeTable(estate, list_make1(rte), perminfos, bms_make_singleton(1)); estate->es_output_cid = GetCurrentCommandId(false); return estate; } /* * Evaluates row filter. * * If the row filter evaluates to NULL, it is taken as false i.e. the change * isn't replicated. */ static bool pgoutput_row_filter_exec_expr(ExprState *state, ExprContext *econtext) { Datum ret; bool isnull; Assert(state != NULL); ret = ExecEvalExprSwitchContext(state, econtext, &isnull); elog(DEBUG3, "row filter evaluates to %s (isnull: %s)", isnull ? "false" : DatumGetBool(ret) ? "true" : "false", isnull ? "true" : "false"); if (isnull) return false; return DatumGetBool(ret); } /* * Make sure the per-entry memory context exists. */ static void pgoutput_ensure_entry_cxt(PGOutputData *data, RelationSyncEntry *entry) { Relation relation; /* The context may already exist, in which case bail out. */ if (entry->entry_cxt) return; relation = RelationIdGetRelation(entry->publish_as_relid); entry->entry_cxt = AllocSetContextCreate(data->cachectx, "entry private context", ALLOCSET_SMALL_SIZES); MemoryContextCopyAndSetIdentifier(entry->entry_cxt, RelationGetRelationName(relation)); } /* * Initialize the row filter. */ static void pgoutput_row_filter_init(PGOutputData *data, List *publications, RelationSyncEntry *entry) { ListCell *lc; List *rfnodes[] = {NIL, NIL, NIL}; /* One per pubaction */ bool no_filter[] = {false, false, false}; /* One per pubaction */ MemoryContext oldctx; int idx; bool has_filter = true; Oid schemaid = get_rel_namespace(entry->publish_as_relid); /* * Find if there are any row filters for this relation. If there are, then * prepare the necessary ExprState and cache it in entry->exprstate. To * build an expression state, we need to ensure the following: * * All the given publication-table mappings must be checked. * * Multiple publications might have multiple row filters for this * relation. Since row filter usage depends on the DML operation, there * are multiple lists (one for each operation) to which row filters will * be appended. * * FOR ALL TABLES and FOR TABLES IN SCHEMA implies "don't use row filter * expression" so it takes precedence. */ foreach(lc, publications) { Publication *pub = lfirst(lc); HeapTuple rftuple = NULL; Datum rfdatum = 0; bool pub_no_filter = true; /* * If the publication is FOR ALL TABLES, or the publication includes a * FOR TABLES IN SCHEMA where the table belongs to the referred * schema, then it is treated the same as if there are no row filters * (even if other publications have a row filter). */ if (!pub->alltables && !SearchSysCacheExists2(PUBLICATIONNAMESPACEMAP, ObjectIdGetDatum(schemaid), ObjectIdGetDatum(pub->oid))) { /* * Check for the presence of a row filter in this publication. */ rftuple = SearchSysCache2(PUBLICATIONRELMAP, ObjectIdGetDatum(entry->publish_as_relid), ObjectIdGetDatum(pub->oid)); if (HeapTupleIsValid(rftuple)) { /* Null indicates no filter. */ rfdatum = SysCacheGetAttr(PUBLICATIONRELMAP, rftuple, Anum_pg_publication_rel_prqual, &pub_no_filter); } } if (pub_no_filter) { if (rftuple) ReleaseSysCache(rftuple); no_filter[PUBACTION_INSERT] |= pub->pubactions.pubinsert; no_filter[PUBACTION_UPDATE] |= pub->pubactions.pubupdate; no_filter[PUBACTION_DELETE] |= pub->pubactions.pubdelete; /* * Quick exit if all the DML actions are publicized via this * publication. */ if (no_filter[PUBACTION_INSERT] && no_filter[PUBACTION_UPDATE] && no_filter[PUBACTION_DELETE]) { has_filter = false; break; } /* No additional work for this publication. Next one. */ continue; } /* Form the per pubaction row filter lists. */ if (pub->pubactions.pubinsert && !no_filter[PUBACTION_INSERT]) rfnodes[PUBACTION_INSERT] = lappend(rfnodes[PUBACTION_INSERT], TextDatumGetCString(rfdatum)); if (pub->pubactions.pubupdate && !no_filter[PUBACTION_UPDATE]) rfnodes[PUBACTION_UPDATE] = lappend(rfnodes[PUBACTION_UPDATE], TextDatumGetCString(rfdatum)); if (pub->pubactions.pubdelete && !no_filter[PUBACTION_DELETE]) rfnodes[PUBACTION_DELETE] = lappend(rfnodes[PUBACTION_DELETE], TextDatumGetCString(rfdatum)); ReleaseSysCache(rftuple); } /* loop all subscribed publications */ /* Clean the row filter */ for (idx = 0; idx < NUM_ROWFILTER_PUBACTIONS; idx++) { if (no_filter[idx]) { list_free_deep(rfnodes[idx]); rfnodes[idx] = NIL; } } if (has_filter) { Relation relation = RelationIdGetRelation(entry->publish_as_relid); pgoutput_ensure_entry_cxt(data, entry); /* * Now all the filters for all pubactions are known. Combine them when * their pubactions are the same. */ oldctx = MemoryContextSwitchTo(entry->entry_cxt); entry->estate = create_estate_for_relation(relation); for (idx = 0; idx < NUM_ROWFILTER_PUBACTIONS; idx++) { List *filters = NIL; Expr *rfnode; if (rfnodes[idx] == NIL) continue; foreach(lc, rfnodes[idx]) filters = lappend(filters, expand_generated_columns_in_expr(stringToNode((char *) lfirst(lc)), relation, 1)); /* combine the row filter and cache the ExprState */ rfnode = make_orclause(filters); entry->exprstate[idx] = ExecPrepareExpr(rfnode, entry->estate); } /* for each pubaction */ MemoryContextSwitchTo(oldctx); RelationClose(relation); } } /* * If the table contains a generated column, check for any conflicting * values of 'publish_generated_columns' parameter in the publications. */ static void check_and_init_gencol(PGOutputData *data, List *publications, RelationSyncEntry *entry) { Relation relation = RelationIdGetRelation(entry->publish_as_relid); TupleDesc desc = RelationGetDescr(relation); bool gencolpresent = false; bool first = true; /* Check if there is any generated column present. */ for (int i = 0; i < desc->natts; i++) { CompactAttribute *att = TupleDescCompactAttr(desc, i); if (att->attgenerated) { gencolpresent = true; break; } } /* There are no generated columns to be published. */ if (!gencolpresent) { entry->include_gencols_type = PUBLISH_GENCOLS_NONE; return; } /* * There may be a conflicting value for 'publish_generated_columns' * parameter in the publications. */ foreach_ptr(Publication, pub, publications) { /* * The column list takes precedence over the * 'publish_generated_columns' parameter. Those will be checked later, * see pgoutput_column_list_init. */ if (check_and_fetch_column_list(pub, entry->publish_as_relid, NULL, NULL)) continue; if (first) { entry->include_gencols_type = pub->pubgencols_type; first = false; } else if (entry->include_gencols_type != pub->pubgencols_type) ereport(ERROR, errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("cannot use different values of publish_generated_columns for table \"%s.%s\" in different publications", get_namespace_name(RelationGetNamespace(relation)), RelationGetRelationName(relation))); } } /* * Initialize the column list. */ static void pgoutput_column_list_init(PGOutputData *data, List *publications, RelationSyncEntry *entry) { ListCell *lc; bool first = true; Relation relation = RelationIdGetRelation(entry->publish_as_relid); bool found_pub_collist = false; Bitmapset *relcols = NULL; pgoutput_ensure_entry_cxt(data, entry); /* * Find if there are any column lists for this relation. If there are, * build a bitmap using the column lists. * * Multiple publications might have multiple column lists for this * relation. * * Note that we don't support the case where the column list is different * for the same table when combining publications. See comments atop * fetch_relation_list. But one can later change the publication so we * still need to check all the given publication-table mappings and report * an error if any publications have a different column list. */ foreach(lc, publications) { Publication *pub = lfirst(lc); Bitmapset *cols = NULL; /* Retrieve the bitmap of columns for a column list publication. */ found_pub_collist |= check_and_fetch_column_list(pub, entry->publish_as_relid, entry->entry_cxt, &cols); /* * For non-column list publications — e.g. TABLE (without a column * list), ALL TABLES, or ALL TABLES IN SCHEMA, we consider all columns * of the table (including generated columns when * 'publish_generated_columns' parameter is true). */ if (!cols) { /* * Cache the table columns for the first publication with no * specified column list to detect publication with a different * column list. */ if (!relcols && (list_length(publications) > 1)) { MemoryContext oldcxt = MemoryContextSwitchTo(entry->entry_cxt); relcols = pub_form_cols_map(relation, entry->include_gencols_type); MemoryContextSwitchTo(oldcxt); } cols = relcols; } if (first) { entry->columns = cols; first = false; } else if (!bms_equal(entry->columns, cols)) ereport(ERROR, errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("cannot use different column lists for table \"%s.%s\" in different publications", get_namespace_name(RelationGetNamespace(relation)), RelationGetRelationName(relation))); } /* loop all subscribed publications */ /* * If no column list publications exist, columns to be published will be * computed later according to the 'publish_generated_columns' parameter. */ if (!found_pub_collist) entry->columns = NULL; RelationClose(relation); } /* * Initialize the slot for storing new and old tuples, and build the map that * will be used to convert the relation's tuples into the ancestor's format. */ static void init_tuple_slot(PGOutputData *data, Relation relation, RelationSyncEntry *entry) { MemoryContext oldctx; TupleDesc oldtupdesc; TupleDesc newtupdesc; oldctx = MemoryContextSwitchTo(data->cachectx); /* * Create tuple table slots. Create a copy of the TupleDesc as it needs to * live as long as the cache remains. */ oldtupdesc = CreateTupleDescCopyConstr(RelationGetDescr(relation)); newtupdesc = CreateTupleDescCopyConstr(RelationGetDescr(relation)); entry->old_slot = MakeSingleTupleTableSlot(oldtupdesc, &TTSOpsHeapTuple); entry->new_slot = MakeSingleTupleTableSlot(newtupdesc, &TTSOpsHeapTuple); MemoryContextSwitchTo(oldctx); /* * Cache the map that will be used to convert the relation's tuples into * the ancestor's format, if needed. */ if (entry->publish_as_relid != RelationGetRelid(relation)) { Relation ancestor = RelationIdGetRelation(entry->publish_as_relid); TupleDesc indesc = RelationGetDescr(relation); TupleDesc outdesc = RelationGetDescr(ancestor); /* Map must live as long as the logical decoding context. */ oldctx = MemoryContextSwitchTo(data->cachectx); entry->attrmap = build_attrmap_by_name_if_req(indesc, outdesc, false); MemoryContextSwitchTo(oldctx); RelationClose(ancestor); } } /* * Change is checked against the row filter if any. * * Returns true if the change is to be replicated, else false. * * For inserts, evaluate the row filter for new tuple. * For deletes, evaluate the row filter for old tuple. * For updates, evaluate the row filter for old and new tuple. * * For updates, if both evaluations are true, we allow sending the UPDATE and * if both the evaluations are false, it doesn't replicate the UPDATE. Now, if * only one of the tuples matches the row filter expression, we transform * UPDATE to DELETE or INSERT to avoid any data inconsistency based on the * following rules: * * Case 1: old-row (no match) new-row (no match) -> (drop change) * Case 2: old-row (no match) new row (match) -> INSERT * Case 3: old-row (match) new-row (no match) -> DELETE * Case 4: old-row (match) new row (match) -> UPDATE * * The new action is updated in the action parameter. * * The new slot could be updated when transforming the UPDATE into INSERT, * because the original new tuple might not have column values from the replica * identity. * * Examples: * Let's say the old tuple satisfies the row filter but the new tuple doesn't. * Since the old tuple satisfies, the initial table synchronization copied this * row (or another method was used to guarantee that there is data * consistency). However, after the UPDATE the new tuple doesn't satisfy the * row filter, so from a data consistency perspective, that row should be * removed on the subscriber. The UPDATE should be transformed into a DELETE * statement and be sent to the subscriber. Keeping this row on the subscriber * is undesirable because it doesn't reflect what was defined in the row filter * expression on the publisher. This row on the subscriber would likely not be * modified by replication again. If someone inserted a new row with the same * old identifier, replication could stop due to a constraint violation. * * Let's say the old tuple doesn't match the row filter but the new tuple does. * Since the old tuple doesn't satisfy, the initial table synchronization * probably didn't copy this row. However, after the UPDATE the new tuple does * satisfy the row filter, so from a data consistency perspective, that row * should be inserted on the subscriber. Otherwise, subsequent UPDATE or DELETE * statements have no effect (it matches no row -- see * apply_handle_update_internal()). So, the UPDATE should be transformed into a * INSERT statement and be sent to the subscriber. However, this might surprise * someone who expects the data set to satisfy the row filter expression on the * provider. */ static bool pgoutput_row_filter(Relation relation, TupleTableSlot *old_slot, TupleTableSlot **new_slot_ptr, RelationSyncEntry *entry, ReorderBufferChangeType *action) { TupleDesc desc; int i; bool old_matched, new_matched, result; TupleTableSlot *tmp_new_slot; TupleTableSlot *new_slot = *new_slot_ptr; ExprContext *ecxt; ExprState *filter_exprstate; /* * We need this map to avoid relying on ReorderBufferChangeType enums * having specific values. */ static const int map_changetype_pubaction[] = { [REORDER_BUFFER_CHANGE_INSERT] = PUBACTION_INSERT, [REORDER_BUFFER_CHANGE_UPDATE] = PUBACTION_UPDATE, [REORDER_BUFFER_CHANGE_DELETE] = PUBACTION_DELETE }; Assert(*action == REORDER_BUFFER_CHANGE_INSERT || *action == REORDER_BUFFER_CHANGE_UPDATE || *action == REORDER_BUFFER_CHANGE_DELETE); Assert(new_slot || old_slot); /* Get the corresponding row filter */ filter_exprstate = entry->exprstate[map_changetype_pubaction[*action]]; /* Bail out if there is no row filter */ if (!filter_exprstate) return true; elog(DEBUG3, "table \"%s.%s\" has row filter", get_namespace_name(RelationGetNamespace(relation)), RelationGetRelationName(relation)); ResetPerTupleExprContext(entry->estate); ecxt = GetPerTupleExprContext(entry->estate); /* * For the following occasions where there is only one tuple, we can * evaluate the row filter for that tuple and return. * * For inserts, we only have the new tuple. * * For updates, we can have only a new tuple when none of the replica * identity columns changed and none of those columns have external data * but we still need to evaluate the row filter for the new tuple as the * existing values of those columns might not match the filter. Also, * users can use constant expressions in the row filter, so we anyway need * to evaluate it for the new tuple. * * For deletes, we only have the old tuple. */ if (!new_slot || !old_slot) { ecxt->ecxt_scantuple = new_slot ? new_slot : old_slot; result = pgoutput_row_filter_exec_expr(filter_exprstate, ecxt); return result; } /* * Both the old and new tuples must be valid only for updates and need to * be checked against the row filter. */ Assert(map_changetype_pubaction[*action] == PUBACTION_UPDATE); slot_getallattrs(new_slot); slot_getallattrs(old_slot); tmp_new_slot = NULL; desc = RelationGetDescr(relation); /* * The new tuple might not have all the replica identity columns, in which * case it needs to be copied over from the old tuple. */ for (i = 0; i < desc->natts; i++) { CompactAttribute *att = TupleDescCompactAttr(desc, i); /* * if the column in the new tuple or old tuple is null, nothing to do */ if (new_slot->tts_isnull[i] || old_slot->tts_isnull[i]) continue; /* * Unchanged toasted replica identity columns are only logged in the * old tuple. Copy this over to the new tuple. The changed (or WAL * Logged) toast values are always assembled in memory and set as * VARTAG_INDIRECT. See ReorderBufferToastReplace. */ if (att->attlen == -1 && VARATT_IS_EXTERNAL_ONDISK(DatumGetPointer(new_slot->tts_values[i])) && !VARATT_IS_EXTERNAL_ONDISK(DatumGetPointer(old_slot->tts_values[i]))) { if (!tmp_new_slot) { tmp_new_slot = MakeSingleTupleTableSlot(desc, &TTSOpsVirtual); ExecClearTuple(tmp_new_slot); memcpy(tmp_new_slot->tts_values, new_slot->tts_values, desc->natts * sizeof(Datum)); memcpy(tmp_new_slot->tts_isnull, new_slot->tts_isnull, desc->natts * sizeof(bool)); } tmp_new_slot->tts_values[i] = old_slot->tts_values[i]; tmp_new_slot->tts_isnull[i] = old_slot->tts_isnull[i]; } } ecxt->ecxt_scantuple = old_slot; old_matched = pgoutput_row_filter_exec_expr(filter_exprstate, ecxt); if (tmp_new_slot) { ExecStoreVirtualTuple(tmp_new_slot); ecxt->ecxt_scantuple = tmp_new_slot; } else ecxt->ecxt_scantuple = new_slot; new_matched = pgoutput_row_filter_exec_expr(filter_exprstate, ecxt); /* * Case 1: if both tuples don't match the row filter, bailout. Send * nothing. */ if (!old_matched && !new_matched) return false; /* * Case 2: if the old tuple doesn't satisfy the row filter but the new * tuple does, transform the UPDATE into INSERT. * * Use the newly transformed tuple that must contain the column values for * all the replica identity columns. This is required to ensure that the * while inserting the tuple in the downstream node, we have all the * required column values. */ if (!old_matched && new_matched) { *action = REORDER_BUFFER_CHANGE_INSERT; if (tmp_new_slot) *new_slot_ptr = tmp_new_slot; } /* * Case 3: if the old tuple satisfies the row filter but the new tuple * doesn't, transform the UPDATE into DELETE. * * This transformation does not require another tuple. The Old tuple will * be used for DELETE. */ else if (old_matched && !new_matched) *action = REORDER_BUFFER_CHANGE_DELETE; /* * Case 4: if both tuples match the row filter, transformation isn't * required. (*action is default UPDATE). */ return true; } /* * Sends the decoded DML over wire. * * This is called both in streaming and non-streaming modes. */ static void pgoutput_change(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, Relation relation, ReorderBufferChange *change) { PGOutputData *data = (PGOutputData *) ctx->output_plugin_private; PGOutputTxnData *txndata = (PGOutputTxnData *) txn->output_plugin_private; MemoryContext old; RelationSyncEntry *relentry; TransactionId xid = InvalidTransactionId; Relation ancestor = NULL; Relation targetrel = relation; ReorderBufferChangeType action = change->action; TupleTableSlot *old_slot = NULL; TupleTableSlot *new_slot = NULL; if (!is_publishable_relation(relation)) return; /* * Remember the xid for the change in streaming mode. We need to send xid * with each change in the streaming mode so that subscriber can make * their association and on aborts, it can discard the corresponding * changes. */ if (data->in_streaming) xid = change->txn->xid; relentry = get_rel_sync_entry(data, relation); /* First check the table filter */ switch (action) { case REORDER_BUFFER_CHANGE_INSERT: if (!relentry->pubactions.pubinsert) return; break; case REORDER_BUFFER_CHANGE_UPDATE: if (!relentry->pubactions.pubupdate) return; break; case REORDER_BUFFER_CHANGE_DELETE: if (!relentry->pubactions.pubdelete) return; /* * This is only possible if deletes are allowed even when replica * identity is not defined for a table. Since the DELETE action * can't be published, we simply return. */ if (!change->data.tp.oldtuple) { elog(DEBUG1, "didn't send DELETE change because of missing oldtuple"); return; } break; default: Assert(false); } /* Avoid leaking memory by using and resetting our own context */ old = MemoryContextSwitchTo(data->context); /* Switch relation if publishing via root. */ if (relentry->publish_as_relid != RelationGetRelid(relation)) { Assert(relation->rd_rel->relispartition); ancestor = RelationIdGetRelation(relentry->publish_as_relid); targetrel = ancestor; } if (change->data.tp.oldtuple) { old_slot = relentry->old_slot; ExecStoreHeapTuple(change->data.tp.oldtuple, old_slot, false); /* Convert tuple if needed. */ if (relentry->attrmap) { TupleTableSlot *slot = MakeTupleTableSlot(RelationGetDescr(targetrel), &TTSOpsVirtual); old_slot = execute_attr_map_slot(relentry->attrmap, old_slot, slot); } } if (change->data.tp.newtuple) { new_slot = relentry->new_slot; ExecStoreHeapTuple(change->data.tp.newtuple, new_slot, false); /* Convert tuple if needed. */ if (relentry->attrmap) { TupleTableSlot *slot = MakeTupleTableSlot(RelationGetDescr(targetrel), &TTSOpsVirtual); new_slot = execute_attr_map_slot(relentry->attrmap, new_slot, slot); } } /* * Check row filter. * * Updates could be transformed to inserts or deletes based on the results * of the row filter for old and new tuple. */ if (!pgoutput_row_filter(targetrel, old_slot, &new_slot, relentry, &action)) goto cleanup; /* * Send BEGIN if we haven't yet. * * We send the BEGIN message after ensuring that we will actually send the * change. This avoids sending a pair of BEGIN/COMMIT messages for empty * transactions. */ if (txndata && !txndata->sent_begin_txn) pgoutput_send_begin(ctx, txn); /* * Schema should be sent using the original relation because it also sends * the ancestor's relation. */ maybe_send_schema(ctx, change, relation, relentry); OutputPluginPrepareWrite(ctx, true); /* Send the data */ switch (action) { case REORDER_BUFFER_CHANGE_INSERT: logicalrep_write_insert(ctx->out, xid, targetrel, new_slot, data->binary, relentry->columns, relentry->include_gencols_type); break; case REORDER_BUFFER_CHANGE_UPDATE: logicalrep_write_update(ctx->out, xid, targetrel, old_slot, new_slot, data->binary, relentry->columns, relentry->include_gencols_type); break; case REORDER_BUFFER_CHANGE_DELETE: logicalrep_write_delete(ctx->out, xid, targetrel, old_slot, data->binary, relentry->columns, relentry->include_gencols_type); break; default: Assert(false); } OutputPluginWrite(ctx, true); cleanup: if (RelationIsValid(ancestor)) { RelationClose(ancestor); ancestor = NULL; } /* Drop the new slots that were used to store the converted tuples. */ if (relentry->attrmap) { if (old_slot) ExecDropSingleTupleTableSlot(old_slot); if (new_slot) ExecDropSingleTupleTableSlot(new_slot); } MemoryContextSwitchTo(old); MemoryContextReset(data->context); } static void pgoutput_truncate(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, int nrelations, Relation relations[], ReorderBufferChange *change) { PGOutputData *data = (PGOutputData *) ctx->output_plugin_private; PGOutputTxnData *txndata = (PGOutputTxnData *) txn->output_plugin_private; MemoryContext old; RelationSyncEntry *relentry; int i; int nrelids; Oid *relids; TransactionId xid = InvalidTransactionId; /* Remember the xid for the change in streaming mode. See pgoutput_change. */ if (data->in_streaming) xid = change->txn->xid; old = MemoryContextSwitchTo(data->context); relids = palloc0(nrelations * sizeof(Oid)); nrelids = 0; for (i = 0; i < nrelations; i++) { Relation relation = relations[i]; Oid relid = RelationGetRelid(relation); if (!is_publishable_relation(relation)) continue; relentry = get_rel_sync_entry(data, relation); if (!relentry->pubactions.pubtruncate) continue; /* * Don't send partitions if the publication wants to send only the * root tables through it. */ if (relation->rd_rel->relispartition && relentry->publish_as_relid != relid) continue; relids[nrelids++] = relid; /* Send BEGIN if we haven't yet */ if (txndata && !txndata->sent_begin_txn) pgoutput_send_begin(ctx, txn); maybe_send_schema(ctx, change, relation, relentry); } if (nrelids > 0) { OutputPluginPrepareWrite(ctx, true); logicalrep_write_truncate(ctx->out, xid, nrelids, relids, change->data.truncate.cascade, change->data.truncate.restart_seqs); OutputPluginWrite(ctx, true); } MemoryContextSwitchTo(old); MemoryContextReset(data->context); } static void pgoutput_message(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr message_lsn, bool transactional, const char *prefix, Size sz, const char *message) { PGOutputData *data = (PGOutputData *) ctx->output_plugin_private; TransactionId xid = InvalidTransactionId; if (!data->messages) return; /* * Remember the xid for the message in streaming mode. See * pgoutput_change. */ if (data->in_streaming) xid = txn->xid; /* * Output BEGIN if we haven't yet. Avoid for non-transactional messages. */ if (transactional) { PGOutputTxnData *txndata = (PGOutputTxnData *) txn->output_plugin_private; /* Send BEGIN if we haven't yet */ if (txndata && !txndata->sent_begin_txn) pgoutput_send_begin(ctx, txn); } OutputPluginPrepareWrite(ctx, true); logicalrep_write_message(ctx->out, xid, message_lsn, transactional, prefix, sz, message); OutputPluginWrite(ctx, true); } /* * Return true if the data is associated with an origin and the user has * requested the changes that don't have an origin, false otherwise. */ static bool pgoutput_origin_filter(LogicalDecodingContext *ctx, ReplOriginId origin_id) { PGOutputData *data = (PGOutputData *) ctx->output_plugin_private; if (data->publish_no_origin && origin_id != InvalidReplOriginId) return true; return false; } /* * Shutdown the output plugin. * * Note, we don't need to clean the data->context, data->cachectx, and * data->pubctx as they are child contexts of the ctx->context so they * will be cleaned up by logical decoding machinery. */ static void pgoutput_shutdown(LogicalDecodingContext *ctx) { pgoutput_memory_context_reset(NULL); } /* * Load publications from the list of publication names. * * Here, we skip the publications that don't exist yet. This will allow us * to silently continue the replication in the absence of a missing publication. * This is required because we allow the users to create publications after they * have specified the required publications at the time of replication start. */ static List * LoadPublications(List *pubnames) { List *result = NIL; ListCell *lc; foreach(lc, pubnames) { char *pubname = (char *) lfirst(lc); Publication *pub = GetPublicationByName(pubname, true); if (pub) result = lappend(result, pub); else ereport(WARNING, errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("skipped loading publication \"%s\"", pubname), errdetail("The publication does not exist at this point in the WAL."), errhint("Create the publication if it does not exist.")); } return result; } /* * Publication syscache invalidation callback. * * Called for invalidations on pg_publication. */ static void publication_invalidation_cb(Datum arg, int cacheid, uint32 hashvalue) { publications_valid = false; } /* * START STREAM callback */ static void pgoutput_stream_start(struct LogicalDecodingContext *ctx, ReorderBufferTXN *txn) { PGOutputData *data = (PGOutputData *) ctx->output_plugin_private; bool send_replication_origin = txn->origin_id != InvalidReplOriginId; /* we can't nest streaming of transactions */ Assert(!data->in_streaming); /* * If we already sent the first stream for this transaction then don't * send the origin id in the subsequent streams. */ if (rbtxn_is_streamed(txn)) send_replication_origin = false; OutputPluginPrepareWrite(ctx, !send_replication_origin); logicalrep_write_stream_start(ctx->out, txn->xid, !rbtxn_is_streamed(txn)); send_repl_origin(ctx, txn->origin_id, InvalidXLogRecPtr, send_replication_origin); OutputPluginWrite(ctx, true); /* we're streaming a chunk of transaction now */ data->in_streaming = true; } /* * STOP STREAM callback */ static void pgoutput_stream_stop(struct LogicalDecodingContext *ctx, ReorderBufferTXN *txn) { PGOutputData *data = (PGOutputData *) ctx->output_plugin_private; /* we should be streaming a transaction */ Assert(data->in_streaming); OutputPluginPrepareWrite(ctx, true); logicalrep_write_stream_stop(ctx->out); OutputPluginWrite(ctx, true); /* we've stopped streaming a transaction */ data->in_streaming = false; } /* * Notify downstream to discard the streamed transaction (along with all * its subtransactions, if it's a toplevel transaction). */ static void pgoutput_stream_abort(struct LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr abort_lsn) { ReorderBufferTXN *toptxn; PGOutputData *data = (PGOutputData *) ctx->output_plugin_private; bool write_abort_info = (data->streaming == LOGICALREP_STREAM_PARALLEL); /* * The abort should happen outside streaming block, even for streamed * transactions. The transaction has to be marked as streamed, though. */ Assert(!data->in_streaming); /* determine the toplevel transaction */ toptxn = rbtxn_get_toptxn(txn); Assert(rbtxn_is_streamed(toptxn)); OutputPluginPrepareWrite(ctx, true); logicalrep_write_stream_abort(ctx->out, toptxn->xid, txn->xid, abort_lsn, txn->abort_time, write_abort_info); OutputPluginWrite(ctx, true); cleanup_rel_sync_cache(toptxn->xid, false); } /* * Notify downstream to apply the streamed transaction (along with all * its subtransactions). */ static void pgoutput_stream_commit(struct LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr commit_lsn) { PGOutputData *data PG_USED_FOR_ASSERTS_ONLY = (PGOutputData *) ctx->output_plugin_private; /* * The commit should happen outside streaming block, even for streamed * transactions. The transaction has to be marked as streamed, though. */ Assert(!data->in_streaming); Assert(rbtxn_is_streamed(txn)); OutputPluginUpdateProgress(ctx, false); OutputPluginPrepareWrite(ctx, true); logicalrep_write_stream_commit(ctx->out, txn, commit_lsn); OutputPluginWrite(ctx, true); cleanup_rel_sync_cache(txn->xid, true); } /* * PREPARE callback (for streaming two-phase commit). * * Notify the downstream to prepare the transaction. */ static void pgoutput_stream_prepare_txn(LogicalDecodingContext *ctx, ReorderBufferTXN *txn, XLogRecPtr prepare_lsn) { Assert(rbtxn_is_streamed(txn)); OutputPluginUpdateProgress(ctx, false); OutputPluginPrepareWrite(ctx, true); logicalrep_write_stream_prepare(ctx->out, txn, prepare_lsn); OutputPluginWrite(ctx, true); } /* * Initialize the relation schema sync cache for a decoding session. * * The hash table is destroyed at the end of a decoding session. While * relcache invalidations still exist and will still be invoked, they * will just see the null hash table global and take no action. */ static void init_rel_sync_cache(MemoryContext cachectx) { HASHCTL ctl; static bool relation_callbacks_registered = false; /* Nothing to do if hash table already exists */ if (RelationSyncCache != NULL) return; /* Make a new hash table for the cache */ ctl.keysize = sizeof(Oid); ctl.entrysize = sizeof(RelationSyncEntry); ctl.hcxt = cachectx; RelationSyncCache = hash_create("logical replication output relation cache", 128, &ctl, HASH_ELEM | HASH_CONTEXT | HASH_BLOBS); Assert(RelationSyncCache != NULL); /* No more to do if we already registered callbacks */ if (relation_callbacks_registered) return; /* We must update the cache entry for a relation after a relcache flush */ CacheRegisterRelcacheCallback(rel_sync_cache_relation_cb, (Datum) 0); /* * Flush all cache entries after a pg_namespace change, in case it was a * schema rename affecting a relation being replicated. * * XXX: It is not a good idea to invalidate all the relation entries in * RelationSyncCache on schema rename. We can optimize it to invalidate * only the required relations by either having a specific invalidation * message containing impacted relations or by having schema information * in each RelationSyncCache entry and using hashvalue of pg_namespace.oid * passed to the callback. */ CacheRegisterSyscacheCallback(NAMESPACEOID, rel_sync_cache_publication_cb, (Datum) 0); relation_callbacks_registered = true; } /* * We expect relatively small number of streamed transactions. */ static bool get_schema_sent_in_streamed_txn(RelationSyncEntry *entry, TransactionId xid) { return list_member_xid(entry->streamed_txns, xid); } /* * Add the xid in the rel sync entry for which we have already sent the schema * of the relation. */ static void set_schema_sent_in_streamed_txn(RelationSyncEntry *entry, TransactionId xid) { MemoryContext oldctx; oldctx = MemoryContextSwitchTo(CacheMemoryContext); entry->streamed_txns = lappend_xid(entry->streamed_txns, xid); MemoryContextSwitchTo(oldctx); } /* * Find or create entry in the relation schema cache. * * This looks up publications that the given relation is directly or * indirectly part of (the latter if it's really the relation's ancestor that * is part of a publication) and fills up the found entry with the information * about which operations to publish and whether to use an ancestor's schema * when publishing. */ static RelationSyncEntry * get_rel_sync_entry(PGOutputData *data, Relation relation) { RelationSyncEntry *entry; bool found; MemoryContext oldctx; Oid relid = RelationGetRelid(relation); Assert(RelationSyncCache != NULL); /* Find cached relation info, creating if not found */ entry = (RelationSyncEntry *) hash_search(RelationSyncCache, &relid, HASH_ENTER, &found); Assert(entry != NULL); /* initialize entry, if it's new */ if (!found) { entry->replicate_valid = false; entry->schema_sent = false; entry->include_gencols_type = PUBLISH_GENCOLS_NONE; entry->streamed_txns = NIL; entry->pubactions.pubinsert = entry->pubactions.pubupdate = entry->pubactions.pubdelete = entry->pubactions.pubtruncate = false; entry->new_slot = NULL; entry->old_slot = NULL; memset(entry->exprstate, 0, sizeof(entry->exprstate)); entry->entry_cxt = NULL; entry->publish_as_relid = InvalidOid; entry->columns = NULL; entry->attrmap = NULL; } /* Validate the entry */ if (!entry->replicate_valid) { Oid schemaId = get_rel_namespace(relid); List *pubids = GetRelationPublications(relid); /* * We don't acquire a lock on the namespace system table as we build * the cache entry using a historic snapshot and all the later changes * are absorbed while decoding WAL. */ List *schemaPubids = GetSchemaPublications(schemaId); ListCell *lc; Oid publish_as_relid = relid; int publish_ancestor_level = 0; bool am_partition = get_rel_relispartition(relid); char relkind = get_rel_relkind(relid); List *rel_publications = NIL; /* Reload publications if needed before use. */ if (!publications_valid) { MemoryContextReset(data->pubctx); oldctx = MemoryContextSwitchTo(data->pubctx); data->publications = LoadPublications(data->publication_names); MemoryContextSwitchTo(oldctx); publications_valid = true; } /* * Reset schema_sent status as the relation definition may have * changed. Also reset pubactions to empty in case rel was dropped * from a publication. Also free any objects that depended on the * earlier definition. */ entry->schema_sent = false; entry->include_gencols_type = PUBLISH_GENCOLS_NONE; list_free(entry->streamed_txns); entry->streamed_txns = NIL; bms_free(entry->columns); entry->columns = NULL; entry->pubactions.pubinsert = false; entry->pubactions.pubupdate = false; entry->pubactions.pubdelete = false; entry->pubactions.pubtruncate = false; /* * Tuple slots cleanups. (Will be rebuilt later if needed). */ if (entry->old_slot) { TupleDesc desc = entry->old_slot->tts_tupleDescriptor; Assert(desc->tdrefcount == -1); ExecDropSingleTupleTableSlot(entry->old_slot); /* * ExecDropSingleTupleTableSlot() would not free the TupleDesc, so * do it now to avoid any leaks. */ FreeTupleDesc(desc); } if (entry->new_slot) { TupleDesc desc = entry->new_slot->tts_tupleDescriptor; Assert(desc->tdrefcount == -1); ExecDropSingleTupleTableSlot(entry->new_slot); /* * ExecDropSingleTupleTableSlot() would not free the TupleDesc, so * do it now to avoid any leaks. */ FreeTupleDesc(desc); } entry->old_slot = NULL; entry->new_slot = NULL; if (entry->attrmap) free_attrmap(entry->attrmap); entry->attrmap = NULL; /* * Row filter cache cleanups. */ if (entry->entry_cxt) MemoryContextDelete(entry->entry_cxt); entry->entry_cxt = NULL; entry->estate = NULL; memset(entry->exprstate, 0, sizeof(entry->exprstate)); /* * Build publication cache. We can't use one provided by relcache as * relcache considers all publications that the given relation is in, * but here we only need to consider ones that the subscriber * requested. */ foreach(lc, data->publications) { Publication *pub = lfirst(lc); bool publish = false; /* * Under what relid should we publish changes in this publication? * We'll use the top-most relid across all publications. Also * track the ancestor level for this publication. */ Oid pub_relid = relid; int ancestor_level = 0; /* * If this is a FOR ALL TABLES publication, pick the partition * root and set the ancestor level accordingly. */ if (pub->alltables) { publish = true; if (pub->pubviaroot && am_partition) { List *ancestors = get_partition_ancestors(relid); pub_relid = llast_oid(ancestors); ancestor_level = list_length(ancestors); } } if (!publish) { bool ancestor_published = false; /* * For a partition, check if any of the ancestors are * published. If so, note down the topmost ancestor that is * published via this publication, which will be used as the * relation via which to publish the partition's changes. */ if (am_partition) { Oid ancestor; int level; List *ancestors = get_partition_ancestors(relid); ancestor = GetTopMostAncestorInPublication(pub->oid, ancestors, &level); if (ancestor != InvalidOid) { ancestor_published = true; if (pub->pubviaroot) { pub_relid = ancestor; ancestor_level = level; } } } if (list_member_oid(pubids, pub->oid) || list_member_oid(schemaPubids, pub->oid) || ancestor_published) publish = true; } /* * If the relation is to be published, determine actions to * publish, and list of columns, if appropriate. * * Don't publish changes for partitioned tables, because * publishing those of its partitions suffices, unless partition * changes won't be published due to pubviaroot being set. */ if (publish && (relkind != RELKIND_PARTITIONED_TABLE || pub->pubviaroot)) { entry->pubactions.pubinsert |= pub->pubactions.pubinsert; entry->pubactions.pubupdate |= pub->pubactions.pubupdate; entry->pubactions.pubdelete |= pub->pubactions.pubdelete; entry->pubactions.pubtruncate |= pub->pubactions.pubtruncate; /* * We want to publish the changes as the top-most ancestor * across all publications. So we need to check if the already * calculated level is higher than the new one. If yes, we can * ignore the new value (as it's a child). Otherwise the new * value is an ancestor, so we keep it. */ if (publish_ancestor_level > ancestor_level) continue; /* * If we found an ancestor higher up in the tree, discard the * list of publications through which we replicate it, and use * the new ancestor. */ if (publish_ancestor_level < ancestor_level) { publish_as_relid = pub_relid; publish_ancestor_level = ancestor_level; /* reset the publication list for this relation */ rel_publications = NIL; } else { /* Same ancestor level, has to be the same OID. */ Assert(publish_as_relid == pub_relid); } /* Track publications for this ancestor. */ rel_publications = lappend(rel_publications, pub); } } entry->publish_as_relid = publish_as_relid; /* * Initialize the tuple slot, map, and row filter. These are only used * when publishing inserts, updates, or deletes. */ if (entry->pubactions.pubinsert || entry->pubactions.pubupdate || entry->pubactions.pubdelete) { /* Initialize the tuple slot and map */ init_tuple_slot(data, relation, entry); /* Initialize the row filter */ pgoutput_row_filter_init(data, rel_publications, entry); /* Check whether to publish generated columns. */ check_and_init_gencol(data, rel_publications, entry); /* Initialize the column list */ pgoutput_column_list_init(data, rel_publications, entry); } list_free(pubids); list_free(schemaPubids); list_free(rel_publications); entry->replicate_valid = true; } return entry; } /* * Cleanup list of streamed transactions and update the schema_sent flag. * * When a streamed transaction commits or aborts, we need to remove the * toplevel XID from the schema cache. If the transaction aborted, the * subscriber will simply throw away the schema records we streamed, so * we don't need to do anything else. * * If the transaction is committed, the subscriber will update the relation * cache - so tweak the schema_sent flag accordingly. */ static void cleanup_rel_sync_cache(TransactionId xid, bool is_commit) { HASH_SEQ_STATUS hash_seq; RelationSyncEntry *entry; Assert(RelationSyncCache != NULL); hash_seq_init(&hash_seq, RelationSyncCache); while ((entry = hash_seq_search(&hash_seq)) != NULL) { /* * We can set the schema_sent flag for an entry that has committed xid * in the list as that ensures that the subscriber would have the * corresponding schema and we don't need to send it unless there is * any invalidation for that relation. */ foreach_xid(streamed_txn, entry->streamed_txns) { if (xid == streamed_txn) { if (is_commit) entry->schema_sent = true; entry->streamed_txns = foreach_delete_current(entry->streamed_txns, streamed_txn); break; } } } } /* * Relcache invalidation callback */ static void rel_sync_cache_relation_cb(Datum arg, Oid relid) { RelationSyncEntry *entry; /* * We can get here if the plugin was used in SQL interface as the * RelationSyncCache is destroyed when the decoding finishes, but there is * no way to unregister the relcache invalidation callback. */ if (RelationSyncCache == NULL) return; /* * Nobody keeps pointers to entries in this hash table around outside * logical decoding callback calls - but invalidation events can come in * *during* a callback if we do any syscache access in the callback. * Because of that we must mark the cache entry as invalid but not damage * any of its substructure here. The next get_rel_sync_entry() call will * rebuild it all. */ if (OidIsValid(relid)) { /* * Getting invalidations for relations that aren't in the table is * entirely normal. So we don't care if it's found or not. */ entry = (RelationSyncEntry *) hash_search(RelationSyncCache, &relid, HASH_FIND, NULL); if (entry != NULL) entry->replicate_valid = false; } else { /* Whole cache must be flushed. */ HASH_SEQ_STATUS status; hash_seq_init(&status, RelationSyncCache); while ((entry = (RelationSyncEntry *) hash_seq_search(&status)) != NULL) { entry->replicate_valid = false; } } } /* * Publication relation/schema map syscache invalidation callback * * Called for invalidations on pg_namespace. */ static void rel_sync_cache_publication_cb(Datum arg, int cacheid, uint32 hashvalue) { HASH_SEQ_STATUS status; RelationSyncEntry *entry; /* * We can get here if the plugin was used in SQL interface as the * RelationSyncCache is destroyed when the decoding finishes, but there is * no way to unregister the invalidation callbacks. */ if (RelationSyncCache == NULL) return; /* * We have no easy way to identify which cache entries this invalidation * event might have affected, so just mark them all invalid. */ hash_seq_init(&status, RelationSyncCache); while ((entry = (RelationSyncEntry *) hash_seq_search(&status)) != NULL) { entry->replicate_valid = false; } } /* Send Replication origin */ static void send_repl_origin(LogicalDecodingContext *ctx, ReplOriginId origin_id, XLogRecPtr origin_lsn, bool send_origin) { if (send_origin) { char *origin; /*---------- * XXX: which behaviour do we want here? * * Alternatives: * - don't send origin message if origin name not found * (that's what we do now) * - throw error - that will break replication, not good * - send some special "unknown" origin *---------- */ if (replorigin_by_oid(origin_id, true, &origin)) { /* Message boundary */ OutputPluginWrite(ctx, false); OutputPluginPrepareWrite(ctx, true); logicalrep_write_origin(ctx->out, origin, origin_lsn); } } }
c
github
https://github.com/postgres/postgres
src/backend/replication/pgoutput/pgoutput.c
# Deliberately use "from dataclasses import *". Every name in __all__ # is tested, so they all must be present. This is a way to catch # missing ones. from dataclasses import * import abc import annotationlib import io import pickle import inspect import builtins import types import weakref import traceback import sys import textwrap import unittest from unittest.mock import Mock from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict from typing import get_type_hints from collections import deque, OrderedDict, namedtuple, defaultdict from copy import deepcopy from functools import total_ordering, wraps import typing # Needed for the string "typing.ClassVar[int]" to work as an annotation. import dataclasses # Needed for the string "dataclasses.InitVar[int]" to work as an annotation. from test import support from test.support import import_helper # Just any custom exception we can catch. class CustomError(Exception): pass class TestCase(unittest.TestCase): def test_no_fields(self): @dataclass class C: pass o = C() self.assertEqual(len(fields(C)), 0) def test_no_fields_but_member_variable(self): @dataclass class C: i = 0 o = C() self.assertEqual(len(fields(C)), 0) def test_one_field_no_default(self): @dataclass class C: x: int o = C(42) self.assertEqual(o.x, 42) def test_field_default_default_factory_error(self): msg = "cannot specify both default and default_factory" with self.assertRaisesRegex(ValueError, msg): @dataclass class C: x: int = field(default=1, default_factory=int) def test_field_repr(self): int_field = field(default=1, init=True, repr=False, doc='Docstring') int_field.name = "id" repr_output = repr(int_field) expected_output = "Field(name='id',type=None," \ f"default=1,default_factory={MISSING!r}," \ "init=True,repr=False,hash=None," \ "compare=True,metadata=mappingproxy({})," \ f"kw_only={MISSING!r}," \ "doc='Docstring'," \ "_field_type=None)" self.assertEqual(repr_output, expected_output) def test_field_recursive_repr(self): rec_field = field() rec_field.type = rec_field rec_field.name = "id" repr_output = repr(rec_field) self.assertIn(",type=...,", repr_output) def test_recursive_annotation(self): class C: pass @dataclass class D: C: C = field() self.assertIn(",type=...,", repr(D.__dataclass_fields__["C"])) def test_dataclass_params_repr(self): # Even though this is testing an internal implementation detail, # it's testing a feature we want to make sure is correctly implemented # for the sake of dataclasses itself @dataclass(slots=True, frozen=True) class Some: pass repr_output = repr(Some.__dataclass_params__) expected_output = "_DataclassParams(init=True,repr=True," \ "eq=True,order=False,unsafe_hash=False,frozen=True," \ "match_args=True,kw_only=False," \ "slots=True,weakref_slot=False)" self.assertEqual(repr_output, expected_output) def test_dataclass_params_signature(self): # Even though this is testing an internal implementation detail, # it's testing a feature we want to make sure is correctly implemented # for the sake of dataclasses itself @dataclass class Some: pass for param in inspect.signature(dataclass).parameters: if param == 'cls': continue self.assertHasAttr(Some.__dataclass_params__, param) def test_named_init_params(self): @dataclass class C: x: int o = C(x=32) self.assertEqual(o.x, 32) def test_two_fields_one_default(self): @dataclass class C: x: int y: int = 0 o = C(3) self.assertEqual((o.x, o.y), (3, 0)) # Non-defaults following defaults. with self.assertRaisesRegex(TypeError, "non-default argument 'y' follows " "default argument 'x'"): @dataclass class C: x: int = 0 y: int # A derived class adds a non-default field after a default one. with self.assertRaisesRegex(TypeError, "non-default argument 'y' follows " "default argument 'x'"): @dataclass class B: x: int = 0 @dataclass class C(B): y: int # Override a base class field and add a default to # a field which didn't use to have a default. with self.assertRaisesRegex(TypeError, "non-default argument 'y' follows " "default argument 'x'"): @dataclass class B: x: int y: int @dataclass class C(B): x: int = 0 def test_overwrite_hash(self): # Test that declaring this class isn't an error. It should # use the user-provided __hash__. @dataclass(frozen=True) class C: x: int def __hash__(self): return 301 self.assertEqual(hash(C(100)), 301) # Test that declaring this class isn't an error. It should # use the generated __hash__. @dataclass(frozen=True) class C: x: int def __eq__(self, other): return False self.assertEqual(hash(C(100)), hash((100,))) # But this one should generate an exception, because with # unsafe_hash=True, it's an error to have a __hash__ defined. with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __hash__'): @dataclass(unsafe_hash=True) class C: def __hash__(self): pass # Creating this class should not generate an exception, # because even though __hash__ exists before @dataclass is # called, (due to __eq__ being defined), since it's None # that's okay. @dataclass(unsafe_hash=True) class C: x: int def __eq__(self): pass # The generated hash function works as we'd expect. self.assertEqual(hash(C(10)), hash((10,))) # Creating this class should generate an exception, because # __hash__ exists and is not None, which it would be if it # had been auto-generated due to __eq__ being defined. with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __hash__'): @dataclass(unsafe_hash=True) class C: x: int def __eq__(self): pass def __hash__(self): pass def test_overwrite_fields_in_derived_class(self): # Note that x from C1 replaces x in Base, but the order remains # the same as defined in Base. @dataclass class Base: x: Any = 15.0 y: int = 0 @dataclass class C1(Base): z: int = 10 x: int = 15 o = Base() self.assertEqual(repr(o), 'TestCase.test_overwrite_fields_in_derived_class.<locals>.Base(x=15.0, y=0)') o = C1() self.assertEqual(repr(o), 'TestCase.test_overwrite_fields_in_derived_class.<locals>.C1(x=15, y=0, z=10)') o = C1(x=5) self.assertEqual(repr(o), 'TestCase.test_overwrite_fields_in_derived_class.<locals>.C1(x=5, y=0, z=10)') def test_field_named_self(self): @dataclass class C: self: str c=C('foo') self.assertEqual(c.self, 'foo') # Make sure the first parameter is not named 'self'. sig = inspect.signature(C.__init__) first = next(iter(sig.parameters)) self.assertNotEqual('self', first) # But we do use 'self' if no field named self. @dataclass class C: selfx: str # Make sure the first parameter is named 'self'. sig = inspect.signature(C.__init__) first = next(iter(sig.parameters)) self.assertEqual('self', first) def test_field_named_object(self): @dataclass class C: object: str c = C('foo') self.assertEqual(c.object, 'foo') def test_field_named_object_frozen(self): @dataclass(frozen=True) class C: object: str c = C('foo') self.assertEqual(c.object, 'foo') def test_field_named_BUILTINS_frozen(self): # gh-96151 @dataclass(frozen=True) class C: BUILTINS: int c = C(5) self.assertEqual(c.BUILTINS, 5) def test_field_with_special_single_underscore_names(self): # gh-98886 @dataclass class X: x: int = field(default_factory=lambda: 111) _dflt_x: int = field(default_factory=lambda: 222) X() @dataclass class Y: y: int = field(default_factory=lambda: 111) _HAS_DEFAULT_FACTORY: int = 222 assert Y(y=222).y == 222 def test_field_named_like_builtin(self): # Attribute names can shadow built-in names # since code generation is used. # Ensure that this is not happening. exclusions = {'None', 'True', 'False'} builtins_names = sorted( b for b in builtins.__dict__.keys() if not b.startswith('__') and b not in exclusions ) attributes = [(name, str) for name in builtins_names] C = make_dataclass('C', attributes) c = C(*[name for name in builtins_names]) for name in builtins_names: self.assertEqual(getattr(c, name), name) def test_field_named_like_builtin_frozen(self): # Attribute names can shadow built-in names # since code generation is used. # Ensure that this is not happening # for frozen data classes. exclusions = {'None', 'True', 'False'} builtins_names = sorted( b for b in builtins.__dict__.keys() if not b.startswith('__') and b not in exclusions ) attributes = [(name, str) for name in builtins_names] C = make_dataclass('C', attributes, frozen=True) c = C(*[name for name in builtins_names]) for name in builtins_names: self.assertEqual(getattr(c, name), name) def test_0_field_compare(self): # Ensure that order=False is the default. @dataclass class C0: pass @dataclass(order=False) class C1: pass for cls in [C0, C1]: with self.subTest(cls=cls): self.assertEqual(cls(), cls()) for idx, fn in enumerate([lambda a, b: a < b, lambda a, b: a <= b, lambda a, b: a > b, lambda a, b: a >= b]): with self.subTest(idx=idx): with self.assertRaisesRegex(TypeError, f"not supported between instances of '{cls.__name__}' and '{cls.__name__}'"): fn(cls(), cls()) @dataclass(order=True) class C: pass self.assertLessEqual(C(), C()) self.assertGreaterEqual(C(), C()) def test_1_field_compare(self): # Ensure that order=False is the default. @dataclass class C0: x: int @dataclass(order=False) class C1: x: int for cls in [C0, C1]: with self.subTest(cls=cls): self.assertEqual(cls(1), cls(1)) self.assertNotEqual(cls(0), cls(1)) for idx, fn in enumerate([lambda a, b: a < b, lambda a, b: a <= b, lambda a, b: a > b, lambda a, b: a >= b]): with self.subTest(idx=idx): with self.assertRaisesRegex(TypeError, f"not supported between instances of '{cls.__name__}' and '{cls.__name__}'"): fn(cls(0), cls(0)) @dataclass(order=True) class C: x: int self.assertLess(C(0), C(1)) self.assertLessEqual(C(0), C(1)) self.assertLessEqual(C(1), C(1)) self.assertGreater(C(1), C(0)) self.assertGreaterEqual(C(1), C(0)) self.assertGreaterEqual(C(1), C(1)) def test_simple_compare(self): # Ensure that order=False is the default. @dataclass class C0: x: int y: int @dataclass(order=False) class C1: x: int y: int for cls in [C0, C1]: with self.subTest(cls=cls): self.assertEqual(cls(0, 0), cls(0, 0)) self.assertEqual(cls(1, 2), cls(1, 2)) self.assertNotEqual(cls(1, 0), cls(0, 0)) self.assertNotEqual(cls(1, 0), cls(1, 1)) for idx, fn in enumerate([lambda a, b: a < b, lambda a, b: a <= b, lambda a, b: a > b, lambda a, b: a >= b]): with self.subTest(idx=idx): with self.assertRaisesRegex(TypeError, f"not supported between instances of '{cls.__name__}' and '{cls.__name__}'"): fn(cls(0, 0), cls(0, 0)) @dataclass(order=True) class C: x: int y: int for idx, fn in enumerate([lambda a, b: a == b, lambda a, b: a <= b, lambda a, b: a >= b]): with self.subTest(idx=idx): self.assertTrue(fn(C(0, 0), C(0, 0))) for idx, fn in enumerate([lambda a, b: a < b, lambda a, b: a <= b, lambda a, b: a != b]): with self.subTest(idx=idx): self.assertTrue(fn(C(0, 0), C(0, 1))) self.assertTrue(fn(C(0, 1), C(1, 0))) self.assertTrue(fn(C(1, 0), C(1, 1))) for idx, fn in enumerate([lambda a, b: a > b, lambda a, b: a >= b, lambda a, b: a != b]): with self.subTest(idx=idx): self.assertTrue(fn(C(0, 1), C(0, 0))) self.assertTrue(fn(C(1, 0), C(0, 1))) self.assertTrue(fn(C(1, 1), C(1, 0))) def test_compare_subclasses(self): # Comparisons fail for subclasses, even if no fields # are added. @dataclass class B: i: int @dataclass class C(B): pass for idx, (fn, expected) in enumerate([(lambda a, b: a == b, False), (lambda a, b: a != b, True)]): with self.subTest(idx=idx): self.assertEqual(fn(B(0), C(0)), expected) for idx, fn in enumerate([lambda a, b: a < b, lambda a, b: a <= b, lambda a, b: a > b, lambda a, b: a >= b]): with self.subTest(idx=idx): with self.assertRaisesRegex(TypeError, "not supported between instances of 'B' and 'C'"): fn(B(0), C(0)) def test_eq_order(self): # Test combining eq and order. for (eq, order, result ) in [ (False, False, 'neither'), (False, True, 'exception'), (True, False, 'eq_only'), (True, True, 'both'), ]: with self.subTest(eq=eq, order=order): if result == 'exception': with self.assertRaisesRegex(ValueError, 'eq must be true if order is true'): @dataclass(eq=eq, order=order) class C: pass else: @dataclass(eq=eq, order=order) class C: pass if result == 'neither': self.assertNotIn('__eq__', C.__dict__) self.assertNotIn('__lt__', C.__dict__) self.assertNotIn('__le__', C.__dict__) self.assertNotIn('__gt__', C.__dict__) self.assertNotIn('__ge__', C.__dict__) elif result == 'both': self.assertIn('__eq__', C.__dict__) self.assertIn('__lt__', C.__dict__) self.assertIn('__le__', C.__dict__) self.assertIn('__gt__', C.__dict__) self.assertIn('__ge__', C.__dict__) elif result == 'eq_only': self.assertIn('__eq__', C.__dict__) self.assertNotIn('__lt__', C.__dict__) self.assertNotIn('__le__', C.__dict__) self.assertNotIn('__gt__', C.__dict__) self.assertNotIn('__ge__', C.__dict__) else: assert False, f'unknown result {result!r}' def test_field_no_default(self): @dataclass class C: x: int = field() self.assertEqual(C(5).x, 5) with self.assertRaisesRegex(TypeError, r"__init__\(\) missing 1 required " "positional argument: 'x'"): C() def test_field_default(self): default = object() @dataclass class C: x: object = field(default=default) self.assertIs(C.x, default) c = C(10) self.assertEqual(c.x, 10) # If we delete the instance attribute, we should then see the # class attribute. del c.x self.assertIs(c.x, default) self.assertIs(C().x, default) def test_not_in_repr(self): @dataclass class C: x: int = field(repr=False) with self.assertRaises(TypeError): C() c = C(10) self.assertEqual(repr(c), 'TestCase.test_not_in_repr.<locals>.C()') @dataclass class C: x: int = field(repr=False) y: int c = C(10, 20) self.assertEqual(repr(c), 'TestCase.test_not_in_repr.<locals>.C(y=20)') def test_not_in_compare(self): @dataclass class C: x: int = 0 y: int = field(compare=False, default=4) self.assertEqual(C(), C(0, 20)) self.assertEqual(C(1, 10), C(1, 20)) self.assertNotEqual(C(3), C(4, 10)) self.assertNotEqual(C(3, 10), C(4, 10)) def test_no_unhashable_default(self): # See bpo-44674. class Unhashable: __hash__ = None unhashable_re = 'mutable default .* for field a is not allowed' with self.assertRaisesRegex(ValueError, unhashable_re): @dataclass class A: a: dict = {} with self.assertRaisesRegex(ValueError, unhashable_re): @dataclass class A: a: Any = Unhashable() # Make sure that the machinery looking for hashability is using the # class's __hash__, not the instance's __hash__. with self.assertRaisesRegex(ValueError, unhashable_re): unhashable = Unhashable() # This shouldn't make the variable hashable. unhashable.__hash__ = lambda: 0 @dataclass class A: a: Any = unhashable def test_hash_field_rules(self): # Test all 6 cases of: # hash=True/False/None # compare=True/False for (hash_, compare, result ) in [ (True, False, 'field' ), (True, True, 'field' ), (False, False, 'absent'), (False, True, 'absent'), (None, False, 'absent'), (None, True, 'field' ), ]: with self.subTest(hash=hash_, compare=compare): @dataclass(unsafe_hash=True) class C: x: int = field(compare=compare, hash=hash_, default=5) if result == 'field': # __hash__ contains the field. self.assertEqual(hash(C(5)), hash((5,))) elif result == 'absent': # The field is not present in the hash. self.assertEqual(hash(C(5)), hash(())) else: assert False, f'unknown result {result!r}' def test_init_false_no_default(self): # If init=False and no default value, then the field won't be # present in the instance. @dataclass class C: x: int = field(init=False) self.assertNotIn('x', C().__dict__) @dataclass class C: x: int y: int = 0 z: int = field(init=False) t: int = 10 self.assertNotIn('z', C(0).__dict__) self.assertEqual(vars(C(5)), {'t': 10, 'x': 5, 'y': 0}) def test_class_marker(self): @dataclass class C: x: int y: str = field(init=False, default=None) z: str = field(repr=False) the_fields = fields(C) # the_fields is a tuple of 3 items, each value # is in __annotations__. self.assertIsInstance(the_fields, tuple) for f in the_fields: self.assertIs(type(f), Field) self.assertIn(f.name, C.__annotations__) self.assertEqual(len(the_fields), 3) self.assertEqual(the_fields[0].name, 'x') self.assertEqual(the_fields[0].type, int) self.assertNotHasAttr(C, 'x') self.assertTrue (the_fields[0].init) self.assertTrue (the_fields[0].repr) self.assertEqual(the_fields[1].name, 'y') self.assertEqual(the_fields[1].type, str) self.assertIsNone(getattr(C, 'y')) self.assertFalse(the_fields[1].init) self.assertTrue (the_fields[1].repr) self.assertEqual(the_fields[2].name, 'z') self.assertEqual(the_fields[2].type, str) self.assertNotHasAttr(C, 'z') self.assertTrue (the_fields[2].init) self.assertFalse(the_fields[2].repr) def test_field_order(self): @dataclass class B: a: str = 'B:a' b: str = 'B:b' c: str = 'B:c' @dataclass class C(B): b: str = 'C:b' self.assertEqual([(f.name, f.default) for f in fields(C)], [('a', 'B:a'), ('b', 'C:b'), ('c', 'B:c')]) @dataclass class D(B): c: str = 'D:c' self.assertEqual([(f.name, f.default) for f in fields(D)], [('a', 'B:a'), ('b', 'B:b'), ('c', 'D:c')]) @dataclass class E(D): a: str = 'E:a' d: str = 'E:d' self.assertEqual([(f.name, f.default) for f in fields(E)], [('a', 'E:a'), ('b', 'B:b'), ('c', 'D:c'), ('d', 'E:d')]) def test_class_attrs(self): # We only have a class attribute if a default value is # specified, either directly or via a field with a default. default = object() @dataclass class C: x: int y: int = field(repr=False) z: object = default t: int = field(default=100) self.assertNotHasAttr(C, 'x') self.assertNotHasAttr(C, 'y') self.assertIs (C.z, default) self.assertEqual(C.t, 100) def test_disallowed_mutable_defaults(self): # For the known types, don't allow mutable default values. for typ, empty, non_empty in [(list, [], [1]), (dict, {}, {0:1}), (set, set(), set([1])), ]: with self.subTest(typ=typ): # Can't use a zero-length value. with self.assertRaisesRegex(ValueError, f'mutable default {typ} for field ' 'x is not allowed'): @dataclass class Point: x: typ = empty # Nor a non-zero-length value with self.assertRaisesRegex(ValueError, f'mutable default {typ} for field ' 'y is not allowed'): @dataclass class Point: y: typ = non_empty # Check subtypes also fail. class Subclass(typ): pass with self.assertRaisesRegex(ValueError, "mutable default .*Subclass'>" " for field z is not allowed" ): @dataclass class Point: z: typ = Subclass() # Because this is a ClassVar, it can be mutable. @dataclass class UsesMutableClassVar: z: ClassVar[typ] = typ() # Because this is a ClassVar, it can be mutable. @dataclass class UsesMutableClassVarWithSubType: x: ClassVar[typ] = Subclass() def test_deliberately_mutable_defaults(self): # If a mutable default isn't in the known list of # (list, dict, set), then it's okay. class Mutable: def __init__(self): self.l = [] @dataclass class C: x: Mutable # These 2 instances will share this value of x. lst = Mutable() o1 = C(lst) o2 = C(lst) self.assertEqual(o1, o2) o1.x.l.extend([1, 2]) self.assertEqual(o1, o2) self.assertEqual(o1.x.l, [1, 2]) self.assertIs(o1.x, o2.x) def test_no_options(self): # Call with dataclass(). @dataclass() class C: x: int self.assertEqual(C(42).x, 42) def test_not_tuple(self): # Make sure we can't be compared to a tuple. @dataclass class Point: x: int y: int self.assertNotEqual(Point(1, 2), (1, 2)) # And that we can't compare to another unrelated dataclass. @dataclass class C: x: int y: int self.assertNotEqual(Point(1, 3), C(1, 3)) def test_not_other_dataclass(self): # Test that some of the problems with namedtuple don't happen # here. @dataclass class Point3D: x: int y: int z: int @dataclass class Date: year: int month: int day: int self.assertNotEqual(Point3D(2017, 6, 3), Date(2017, 6, 3)) self.assertNotEqual(Point3D(1, 2, 3), (1, 2, 3)) # Make sure we can't unpack. with self.assertRaisesRegex(TypeError, 'unpack'): x, y, z = Point3D(4, 5, 6) # Make sure another class with the same field names isn't # equal. @dataclass class Point3Dv1: x: int = 0 y: int = 0 z: int = 0 self.assertNotEqual(Point3D(0, 0, 0), Point3Dv1()) def test_function_annotations(self): # Some dummy class and instance to use as a default. class F: pass f = F() def validate_class(cls): # First, check __annotations__, even though they're not # function annotations. self.assertEqual(cls.__annotations__['i'], int) self.assertEqual(cls.__annotations__['j'], str) self.assertEqual(cls.__annotations__['k'], F) self.assertEqual(cls.__annotations__['l'], float) self.assertEqual(cls.__annotations__['z'], complex) # Verify __init__. signature = inspect.signature(cls.__init__) # Check the return type, should be None. self.assertIs(signature.return_annotation, None) # Check each parameter. params = iter(signature.parameters.values()) param = next(params) # This is testing an internal name, and probably shouldn't be tested. self.assertEqual(param.name, 'self') param = next(params) self.assertEqual(param.name, 'i') self.assertIs (param.annotation, int) self.assertEqual(param.default, inspect.Parameter.empty) self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD) param = next(params) self.assertEqual(param.name, 'j') self.assertIs (param.annotation, str) self.assertEqual(param.default, inspect.Parameter.empty) self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD) param = next(params) self.assertEqual(param.name, 'k') self.assertIs (param.annotation, F) # Don't test for the default, since it's set to MISSING. self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD) param = next(params) self.assertEqual(param.name, 'l') self.assertIs (param.annotation, float) # Don't test for the default, since it's set to MISSING. self.assertEqual(param.kind, inspect.Parameter.POSITIONAL_OR_KEYWORD) self.assertRaises(StopIteration, next, params) @dataclass class C: i: int j: str k: F = f l: float=field(default=None) z: complex=field(default=3+4j, init=False) validate_class(C) # Now repeat with __hash__. @dataclass(frozen=True, unsafe_hash=True) class C: i: int j: str k: F = f l: float=field(default=None) z: complex=field(default=3+4j, init=False) validate_class(C) def test_incomplete_annotations(self): # gh-142214 @dataclass class C: "doc" # needed because otherwise we fetch the annotations at the wrong time x: int C.__annotate__ = lambda _: {} self.assertEqual( annotationlib.get_annotations(C.__init__), {"return": None} ) def test_missing_default(self): # Test that MISSING works the same as a default not being # specified. @dataclass class C: x: int=field(default=MISSING) with self.assertRaisesRegex(TypeError, r'__init__\(\) missing 1 required ' 'positional argument'): C() self.assertNotIn('x', C.__dict__) @dataclass class D: x: int with self.assertRaisesRegex(TypeError, r'__init__\(\) missing 1 required ' 'positional argument'): D() self.assertNotIn('x', D.__dict__) def test_missing_default_factory(self): # Test that MISSING works the same as a default factory not # being specified (which is really the same as a default not # being specified, too). @dataclass class C: x: int=field(default_factory=MISSING) with self.assertRaisesRegex(TypeError, r'__init__\(\) missing 1 required ' 'positional argument'): C() self.assertNotIn('x', C.__dict__) @dataclass class D: x: int=field(default=MISSING, default_factory=MISSING) with self.assertRaisesRegex(TypeError, r'__init__\(\) missing 1 required ' 'positional argument'): D() self.assertNotIn('x', D.__dict__) def test_missing_repr(self): self.assertIn('MISSING_TYPE object', repr(MISSING)) def test_dont_include_other_annotations(self): @dataclass class C: i: int def foo(self) -> int: return 4 @property def bar(self) -> int: return 5 self.assertEqual(list(C.__annotations__), ['i']) self.assertEqual(C(10).foo(), 4) self.assertEqual(C(10).bar, 5) self.assertEqual(C(10).i, 10) def test_post_init(self): # Just make sure it gets called @dataclass class C: def __post_init__(self): raise CustomError() with self.assertRaises(CustomError): C() @dataclass class C: i: int = 10 def __post_init__(self): if self.i == 10: raise CustomError() with self.assertRaises(CustomError): C() # post-init gets called, but doesn't raise. This is just # checking that self is used correctly. C(5) # If there's not an __init__, then post-init won't get called. @dataclass(init=False) class C: def __post_init__(self): raise CustomError() # Creating the class won't raise C() @dataclass class C: x: int = 0 def __post_init__(self): self.x *= 2 self.assertEqual(C().x, 0) self.assertEqual(C(2).x, 4) # Make sure that if we're frozen, post-init can't set # attributes. @dataclass(frozen=True) class C: x: int = 0 def __post_init__(self): self.x *= 2 with self.assertRaises(FrozenInstanceError): C() def test_post_init_super(self): # Make sure super() post-init isn't called by default. class B: def __post_init__(self): raise CustomError() @dataclass class C(B): def __post_init__(self): self.x = 5 self.assertEqual(C().x, 5) # Now call super(), and it will raise. @dataclass class C(B): def __post_init__(self): super().__post_init__() with self.assertRaises(CustomError): C() # Make sure post-init is called, even if not defined in our # class. @dataclass class C(B): pass with self.assertRaises(CustomError): C() def test_post_init_staticmethod(self): flag = False @dataclass class C: x: int y: int @staticmethod def __post_init__(): nonlocal flag flag = True self.assertFalse(flag) c = C(3, 4) self.assertEqual((c.x, c.y), (3, 4)) self.assertTrue(flag) def test_post_init_classmethod(self): @dataclass class C: flag = False x: int y: int @classmethod def __post_init__(cls): cls.flag = True self.assertFalse(C.flag) c = C(3, 4) self.assertEqual((c.x, c.y), (3, 4)) self.assertTrue(C.flag) def test_post_init_not_auto_added(self): # See bpo-46757, which had proposed always adding __post_init__. As # Raymond Hettinger pointed out, that would be a breaking change. So, # add a test to make sure that the current behavior doesn't change. @dataclass class A0: pass @dataclass class B0: b_called: bool = False def __post_init__(self): self.b_called = True @dataclass class C0(A0, B0): c_called: bool = False def __post_init__(self): super().__post_init__() self.c_called = True # Since A0 has no __post_init__, and one wasn't automatically added # (because that's the rule: it's never added by @dataclass, it's only # the class author that can add it), then B0.__post_init__ is called. # Verify that. c = C0() self.assertTrue(c.b_called) self.assertTrue(c.c_called) ###################################### # Now, the same thing, except A1 defines __post_init__. @dataclass class A1: def __post_init__(self): pass @dataclass class B1: b_called: bool = False def __post_init__(self): self.b_called = True @dataclass class C1(A1, B1): c_called: bool = False def __post_init__(self): super().__post_init__() self.c_called = True # This time, B1.__post_init__ isn't being called. This mimics what # would happen if A1.__post_init__ had been automatically added, # instead of manually added as we see here. This test isn't really # needed, but I'm including it just to demonstrate the changed # behavior when A1 does define __post_init__. c = C1() self.assertFalse(c.b_called) self.assertTrue(c.c_called) def test_class_var(self): # Make sure ClassVars are ignored in __init__, __repr__, etc. @dataclass class C: x: int y: int = 10 z: ClassVar[int] = 1000 w: ClassVar[int] = 2000 t: ClassVar[int] = 3000 s: ClassVar = 4000 c = C(5) self.assertEqual(repr(c), 'TestCase.test_class_var.<locals>.C(x=5, y=10)') self.assertEqual(len(fields(C)), 2) # We have 2 fields. self.assertEqual(len(C.__annotations__), 6) # And 4 ClassVars. self.assertEqual(c.z, 1000) self.assertEqual(c.w, 2000) self.assertEqual(c.t, 3000) self.assertEqual(c.s, 4000) C.z += 1 self.assertEqual(c.z, 1001) c = C(20) self.assertEqual((c.x, c.y), (20, 10)) self.assertEqual(c.z, 1001) self.assertEqual(c.w, 2000) self.assertEqual(c.t, 3000) self.assertEqual(c.s, 4000) def test_class_var_no_default(self): # If a ClassVar has no default value, it should not be set on the class. @dataclass class C: x: ClassVar[int] self.assertNotIn('x', C.__dict__) def test_class_var_default_factory(self): # It makes no sense for a ClassVar to have a default factory. When # would it be called? Call it yourself, since it's class-wide. with self.assertRaisesRegex(TypeError, 'cannot have a default factory'): @dataclass class C: x: ClassVar[int] = field(default_factory=int) self.assertNotIn('x', C.__dict__) def test_class_var_with_default(self): # If a ClassVar has a default value, it should be set on the class. @dataclass class C: x: ClassVar[int] = 10 self.assertEqual(C.x, 10) @dataclass class C: x: ClassVar[int] = field(default=10) self.assertEqual(C.x, 10) def test_class_var_frozen(self): # Make sure ClassVars work even if we're frozen. @dataclass(frozen=True) class C: x: int y: int = 10 z: ClassVar[int] = 1000 w: ClassVar[int] = 2000 t: ClassVar[int] = 3000 c = C(5) self.assertEqual(repr(C(5)), 'TestCase.test_class_var_frozen.<locals>.C(x=5, y=10)') self.assertEqual(len(fields(C)), 2) # We have 2 fields self.assertEqual(len(C.__annotations__), 5) # And 3 ClassVars self.assertEqual(c.z, 1000) self.assertEqual(c.w, 2000) self.assertEqual(c.t, 3000) # We can still modify the ClassVar, it's only instances that are # frozen. C.z += 1 self.assertEqual(c.z, 1001) c = C(20) self.assertEqual((c.x, c.y), (20, 10)) self.assertEqual(c.z, 1001) self.assertEqual(c.w, 2000) self.assertEqual(c.t, 3000) def test_init_var_no_default(self): # If an InitVar has no default value, it should not be set on the class. @dataclass class C: x: InitVar[int] self.assertNotIn('x', C.__dict__) def test_init_var_default_factory(self): # It makes no sense for an InitVar to have a default factory. When # would it be called? Call it yourself, since it's class-wide. with self.assertRaisesRegex(TypeError, 'cannot have a default factory'): @dataclass class C: x: InitVar[int] = field(default_factory=int) self.assertNotIn('x', C.__dict__) def test_init_var_with_default(self): # If an InitVar has a default value, it should be set on the class. @dataclass class C: x: InitVar[int] = 10 self.assertEqual(C.x, 10) @dataclass class C: x: InitVar[int] = field(default=10) self.assertEqual(C.x, 10) def test_init_var(self): @dataclass class C: x: int = None init_param: InitVar[int] = None def __post_init__(self, init_param): if self.x is None: self.x = init_param*2 c = C(init_param=10) self.assertEqual(c.x, 20) def test_init_var_preserve_type(self): self.assertEqual(InitVar[int].type, int) # Make sure the repr is correct. self.assertEqual(repr(InitVar[int]), 'dataclasses.InitVar[int]') self.assertEqual(repr(InitVar[List[int]]), 'dataclasses.InitVar[typing.List[int]]') self.assertEqual(repr(InitVar[list[int]]), 'dataclasses.InitVar[list[int]]') self.assertEqual(repr(InitVar[int|str]), 'dataclasses.InitVar[int | str]') def test_init_var_inheritance(self): # Note that this deliberately tests that a dataclass need not # have a __post_init__ function if it has an InitVar field. # It could just be used in a derived class, as shown here. @dataclass class Base: x: int init_base: InitVar[int] # We can instantiate by passing the InitVar, even though # it's not used. b = Base(0, 10) self.assertEqual(vars(b), {'x': 0}) @dataclass class C(Base): y: int init_derived: InitVar[int] def __post_init__(self, init_base, init_derived): self.x = self.x + init_base self.y = self.y + init_derived c = C(10, 11, 50, 51) self.assertEqual(vars(c), {'x': 21, 'y': 101}) def test_init_var_name_shadowing(self): # Because dataclasses rely exclusively on `__annotations__` for # handling InitVar and `__annotations__` preserves shadowed definitions, # you can actually shadow an InitVar with a method or property. # # This only works when there is no default value; `dataclasses` uses the # actual name (which will be bound to the shadowing method) for default # values. @dataclass class C: shadowed: InitVar[int] _shadowed: int = field(init=False) def __post_init__(self, shadowed): self._shadowed = shadowed * 2 @property def shadowed(self): return self._shadowed * 3 c = C(5) self.assertEqual(c.shadowed, 30) def test_default_factory(self): # Test a factory that returns a new list. @dataclass class C: x: int y: list = field(default_factory=list) c0 = C(3) c1 = C(3) self.assertEqual(c0.x, 3) self.assertEqual(c0.y, []) self.assertEqual(c0, c1) self.assertIsNot(c0.y, c1.y) self.assertEqual(astuple(C(5, [1])), (5, [1])) # Test a factory that returns a shared list. l = [] @dataclass class C: x: int y: list = field(default_factory=lambda: l) c0 = C(3) c1 = C(3) self.assertEqual(c0.x, 3) self.assertEqual(c0.y, []) self.assertEqual(c0, c1) self.assertIs(c0.y, c1.y) self.assertEqual(astuple(C(5, [1])), (5, [1])) # Test various other field flags. # repr @dataclass class C: x: list = field(default_factory=list, repr=False) self.assertEqual(repr(C()), 'TestCase.test_default_factory.<locals>.C()') self.assertEqual(C().x, []) # hash @dataclass(unsafe_hash=True) class C: x: list = field(default_factory=list, hash=False) self.assertEqual(astuple(C()), ([],)) self.assertEqual(hash(C()), hash(())) # init (see also test_default_factory_with_no_init) @dataclass class C: x: list = field(default_factory=list, init=False) self.assertEqual(astuple(C()), ([],)) # compare @dataclass class C: x: list = field(default_factory=list, compare=False) self.assertEqual(C(), C([1])) def test_default_factory_with_no_init(self): # We need a factory with a side effect. factory = Mock() @dataclass class C: x: list = field(default_factory=factory, init=False) # Make sure the default factory is called for each new instance. C().x self.assertEqual(factory.call_count, 1) C().x self.assertEqual(factory.call_count, 2) def test_default_factory_not_called_if_value_given(self): # We need a factory that we can test if it's been called. factory = Mock() @dataclass class C: x: int = field(default_factory=factory) # Make sure that if a field has a default factory function, # it's not called if a value is specified. C().x self.assertEqual(factory.call_count, 1) self.assertEqual(C(10).x, 10) self.assertEqual(factory.call_count, 1) C().x self.assertEqual(factory.call_count, 2) def test_default_factory_derived(self): # See bpo-32896. @dataclass class Foo: x: dict = field(default_factory=dict) @dataclass class Bar(Foo): y: int = 1 self.assertEqual(Foo().x, {}) self.assertEqual(Bar().x, {}) self.assertEqual(Bar().y, 1) @dataclass class Baz(Foo): pass self.assertEqual(Baz().x, {}) def test_intermediate_non_dataclass(self): # Test that an intermediate class that defines # annotations does not define fields. @dataclass class A: x: int class B(A): y: int @dataclass class C(B): z: int c = C(1, 3) self.assertEqual((c.x, c.z), (1, 3)) # .y was not initialized. with self.assertRaisesRegex(AttributeError, 'object has no attribute'): c.y # And if we again derive a non-dataclass, no fields are added. class D(C): t: int d = D(4, 5) self.assertEqual((d.x, d.z), (4, 5)) def test_classvar_default_factory(self): # It's an error for a ClassVar to have a factory function. with self.assertRaisesRegex(TypeError, 'cannot have a default factory'): @dataclass class C: x: ClassVar[int] = field(default_factory=int) def test_is_dataclass(self): class NotDataClass: pass self.assertFalse(is_dataclass(0)) self.assertFalse(is_dataclass(int)) self.assertFalse(is_dataclass(NotDataClass)) self.assertFalse(is_dataclass(NotDataClass())) @dataclass class C: x: int @dataclass class D: d: C e: int c = C(10) d = D(c, 4) self.assertTrue(is_dataclass(C)) self.assertTrue(is_dataclass(c)) self.assertFalse(is_dataclass(c.x)) self.assertTrue(is_dataclass(d.d)) self.assertFalse(is_dataclass(d.e)) def test_is_dataclass_when_getattr_always_returns(self): # See bpo-37868. class A: def __getattr__(self, key): return 0 self.assertFalse(is_dataclass(A)) a = A() # Also test for an instance attribute. class B: pass b = B() b.__dataclass_fields__ = [] for obj in a, b: with self.subTest(obj=obj): self.assertFalse(is_dataclass(obj)) # Indirect tests for _is_dataclass_instance(). with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'): asdict(obj) with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'): astuple(obj) with self.assertRaisesRegex(TypeError, 'should be called on dataclass instances'): replace(obj, x=0) def test_is_dataclass_genericalias(self): @dataclass class A(types.GenericAlias): origin: type args: type self.assertTrue(is_dataclass(A)) a = A(list, int) self.assertTrue(is_dataclass(type(a))) self.assertTrue(is_dataclass(a)) def test_is_dataclass_inheritance(self): @dataclass class X: y: int class Z(X): pass self.assertTrue(is_dataclass(X), "X should be a dataclass") self.assertTrue( is_dataclass(Z), "Z should be a dataclass because it inherits from X", ) z_instance = Z(y=5) self.assertTrue( is_dataclass(z_instance), "z_instance should be a dataclass because it is an instance of Z", ) def test_helper_fields_with_class_instance(self): # Check that we can call fields() on either a class or instance, # and get back the same thing. @dataclass class C: x: int y: float self.assertEqual(fields(C), fields(C(0, 0.0))) def test_helper_fields_exception(self): # Check that TypeError is raised if not passed a dataclass or # instance. with self.assertRaisesRegex(TypeError, 'dataclass type or instance'): fields(0) class C: pass with self.assertRaisesRegex(TypeError, 'dataclass type or instance'): fields(C) with self.assertRaisesRegex(TypeError, 'dataclass type or instance'): fields(C()) def test_clean_traceback_from_fields_exception(self): stdout = io.StringIO() try: fields(object) except TypeError as exc: traceback.print_exception(exc, file=stdout) printed_traceback = stdout.getvalue() self.assertNotIn("AttributeError", printed_traceback) self.assertNotIn("__dataclass_fields__", printed_traceback) def test_helper_asdict(self): # Basic tests for asdict(), it should return a new dictionary. @dataclass class C: x: int y: int c = C(1, 2) self.assertEqual(asdict(c), {'x': 1, 'y': 2}) self.assertEqual(asdict(c), asdict(c)) self.assertIsNot(asdict(c), asdict(c)) c.x = 42 self.assertEqual(asdict(c), {'x': 42, 'y': 2}) self.assertIs(type(asdict(c)), dict) def test_helper_asdict_raises_on_classes(self): # asdict() should raise on a class object. @dataclass class C: x: int y: int with self.assertRaisesRegex(TypeError, 'dataclass instance'): asdict(C) with self.assertRaisesRegex(TypeError, 'dataclass instance'): asdict(int) def test_helper_asdict_copy_values(self): @dataclass class C: x: int y: List[int] = field(default_factory=list) initial = [] c = C(1, initial) d = asdict(c) self.assertEqual(d['y'], initial) self.assertIsNot(d['y'], initial) c = C(1) d = asdict(c) d['y'].append(1) self.assertEqual(c.y, []) def test_helper_asdict_nested(self): @dataclass class UserId: token: int group: int @dataclass class User: name: str id: UserId u = User('Joe', UserId(123, 1)) d = asdict(u) self.assertEqual(d, {'name': 'Joe', 'id': {'token': 123, 'group': 1}}) self.assertIsNot(asdict(u), asdict(u)) u.id.group = 2 self.assertEqual(asdict(u), {'name': 'Joe', 'id': {'token': 123, 'group': 2}}) def test_helper_asdict_builtin_containers(self): @dataclass class User: name: str id: int @dataclass class GroupList: id: int users: List[User] @dataclass class GroupTuple: id: int users: Tuple[User, ...] @dataclass class GroupDict: id: int users: Dict[str, User] a = User('Alice', 1) b = User('Bob', 2) gl = GroupList(0, [a, b]) gt = GroupTuple(0, (a, b)) gd = GroupDict(0, {'first': a, 'second': b}) self.assertEqual(asdict(gl), {'id': 0, 'users': [{'name': 'Alice', 'id': 1}, {'name': 'Bob', 'id': 2}]}) self.assertEqual(asdict(gt), {'id': 0, 'users': ({'name': 'Alice', 'id': 1}, {'name': 'Bob', 'id': 2})}) self.assertEqual(asdict(gd), {'id': 0, 'users': {'first': {'name': 'Alice', 'id': 1}, 'second': {'name': 'Bob', 'id': 2}}}) def test_helper_asdict_builtin_object_containers(self): @dataclass class Child: d: object @dataclass class Parent: child: Child self.assertEqual(asdict(Parent(Child([1]))), {'child': {'d': [1]}}) self.assertEqual(asdict(Parent(Child({1: 2}))), {'child': {'d': {1: 2}}}) def test_helper_asdict_factory(self): @dataclass class C: x: int y: int c = C(1, 2) d = asdict(c, dict_factory=OrderedDict) self.assertEqual(d, OrderedDict([('x', 1), ('y', 2)])) self.assertIsNot(d, asdict(c, dict_factory=OrderedDict)) c.x = 42 d = asdict(c, dict_factory=OrderedDict) self.assertEqual(d, OrderedDict([('x', 42), ('y', 2)])) self.assertIs(type(d), OrderedDict) def test_helper_asdict_namedtuple(self): T = namedtuple('T', 'a b c') @dataclass class C: x: str y: T c = C('outer', T(1, C('inner', T(11, 12, 13)), 2)) d = asdict(c) self.assertEqual(d, {'x': 'outer', 'y': T(1, {'x': 'inner', 'y': T(11, 12, 13)}, 2), } ) # Now with a dict_factory. OrderedDict is convenient, but # since it compares to dicts, we also need to have separate # assertIs tests. d = asdict(c, dict_factory=OrderedDict) self.assertEqual(d, {'x': 'outer', 'y': T(1, {'x': 'inner', 'y': T(11, 12, 13)}, 2), } ) # Make sure that the returned dicts are actually OrderedDicts. self.assertIs(type(d), OrderedDict) self.assertIs(type(d['y'][1]), OrderedDict) def test_helper_asdict_namedtuple_key(self): # Ensure that a field that contains a dict which has a # namedtuple as a key works with asdict(). @dataclass class C: f: dict T = namedtuple('T', 'a') c = C({T('an a'): 0}) self.assertEqual(asdict(c), {'f': {T(a='an a'): 0}}) def test_helper_asdict_namedtuple_derived(self): class T(namedtuple('Tbase', 'a')): def my_a(self): return self.a @dataclass class C: f: T t = T(6) c = C(t) d = asdict(c) self.assertEqual(d, {'f': T(a=6)}) # Make sure that t has been copied, not used directly. self.assertIsNot(d['f'], t) self.assertEqual(d['f'].my_a(), 6) def test_helper_asdict_defaultdict(self): # Ensure asdict() does not throw exceptions when a # defaultdict is a member of a dataclass @dataclass class C: mp: DefaultDict[str, List] dd = defaultdict(list) dd["x"].append(12) c = C(mp=dd) d = asdict(c) self.assertEqual(d, {"mp": {"x": [12]}}) self.assertTrue(d["mp"] is not c.mp) # make sure defaultdict is copied def test_helper_astuple(self): # Basic tests for astuple(), it should return a new tuple. @dataclass class C: x: int y: int = 0 c = C(1) self.assertEqual(astuple(c), (1, 0)) self.assertEqual(astuple(c), astuple(c)) self.assertIsNot(astuple(c), astuple(c)) c.y = 42 self.assertEqual(astuple(c), (1, 42)) self.assertIs(type(astuple(c)), tuple) def test_helper_astuple_raises_on_classes(self): # astuple() should raise on a class object. @dataclass class C: x: int y: int with self.assertRaisesRegex(TypeError, 'dataclass instance'): astuple(C) with self.assertRaisesRegex(TypeError, 'dataclass instance'): astuple(int) def test_helper_astuple_copy_values(self): @dataclass class C: x: int y: List[int] = field(default_factory=list) initial = [] c = C(1, initial) t = astuple(c) self.assertEqual(t[1], initial) self.assertIsNot(t[1], initial) c = C(1) t = astuple(c) t[1].append(1) self.assertEqual(c.y, []) def test_helper_astuple_nested(self): @dataclass class UserId: token: int group: int @dataclass class User: name: str id: UserId u = User('Joe', UserId(123, 1)) t = astuple(u) self.assertEqual(t, ('Joe', (123, 1))) self.assertIsNot(astuple(u), astuple(u)) u.id.group = 2 self.assertEqual(astuple(u), ('Joe', (123, 2))) def test_helper_astuple_builtin_containers(self): @dataclass class User: name: str id: int @dataclass class GroupList: id: int users: List[User] @dataclass class GroupTuple: id: int users: Tuple[User, ...] @dataclass class GroupDict: id: int users: Dict[str, User] a = User('Alice', 1) b = User('Bob', 2) gl = GroupList(0, [a, b]) gt = GroupTuple(0, (a, b)) gd = GroupDict(0, {'first': a, 'second': b}) self.assertEqual(astuple(gl), (0, [('Alice', 1), ('Bob', 2)])) self.assertEqual(astuple(gt), (0, (('Alice', 1), ('Bob', 2)))) self.assertEqual(astuple(gd), (0, {'first': ('Alice', 1), 'second': ('Bob', 2)})) def test_helper_astuple_builtin_object_containers(self): @dataclass class Child: d: object @dataclass class Parent: child: Child self.assertEqual(astuple(Parent(Child([1]))), (([1],),)) self.assertEqual(astuple(Parent(Child({1: 2}))), (({1: 2},),)) def test_helper_astuple_factory(self): @dataclass class C: x: int y: int NT = namedtuple('NT', 'x y') def nt(lst): return NT(*lst) c = C(1, 2) t = astuple(c, tuple_factory=nt) self.assertEqual(t, NT(1, 2)) self.assertIsNot(t, astuple(c, tuple_factory=nt)) c.x = 42 t = astuple(c, tuple_factory=nt) self.assertEqual(t, NT(42, 2)) self.assertIs(type(t), NT) def test_helper_astuple_namedtuple(self): T = namedtuple('T', 'a b c') @dataclass class C: x: str y: T c = C('outer', T(1, C('inner', T(11, 12, 13)), 2)) t = astuple(c) self.assertEqual(t, ('outer', T(1, ('inner', (11, 12, 13)), 2))) # Now, using a tuple_factory. list is convenient here. t = astuple(c, tuple_factory=list) self.assertEqual(t, ['outer', T(1, ['inner', T(11, 12, 13)], 2)]) def test_helper_astuple_defaultdict(self): # Ensure astuple() does not throw exceptions when a # defaultdict is a member of a dataclass @dataclass class C: mp: DefaultDict[str, List] dd = defaultdict(list) dd["x"].append(12) c = C(mp=dd) t = astuple(c) self.assertEqual(t, ({"x": [12]},)) self.assertTrue(t[0] is not dd) # make sure defaultdict is copied def test_dynamic_class_creation(self): cls_dict = {'__annotations__': {'x': int, 'y': int}, } # Create the class. cls = type('C', (), cls_dict) # Make it a dataclass. cls1 = dataclass(cls) self.assertEqual(cls1, cls) self.assertEqual(asdict(cls(1, 2)), {'x': 1, 'y': 2}) def test_dynamic_class_creation_using_field(self): cls_dict = {'__annotations__': {'x': int, 'y': int}, 'y': field(default=5), } # Create the class. cls = type('C', (), cls_dict) # Make it a dataclass. cls1 = dataclass(cls) self.assertEqual(cls1, cls) self.assertEqual(asdict(cls1(1)), {'x': 1, 'y': 5}) def test_init_in_order(self): @dataclass class C: a: int b: int = field() c: list = field(default_factory=list, init=False) d: list = field(default_factory=list) e: int = field(default=4, init=False) f: int = 4 calls = [] def setattr(self, name, value): calls.append((name, value)) C.__setattr__ = setattr c = C(0, 1) self.assertEqual(('a', 0), calls[0]) self.assertEqual(('b', 1), calls[1]) self.assertEqual(('c', []), calls[2]) self.assertEqual(('d', []), calls[3]) self.assertNotIn(('e', 4), calls) self.assertEqual(('f', 4), calls[4]) def test_items_in_dicts(self): @dataclass class C: a: int b: list = field(default_factory=list, init=False) c: list = field(default_factory=list) d: int = field(default=4, init=False) e: int = 0 c = C(0) # Class dict self.assertNotIn('a', C.__dict__) self.assertNotIn('b', C.__dict__) self.assertNotIn('c', C.__dict__) self.assertIn('d', C.__dict__) self.assertEqual(C.d, 4) self.assertIn('e', C.__dict__) self.assertEqual(C.e, 0) # Instance dict self.assertIn('a', c.__dict__) self.assertEqual(c.a, 0) self.assertIn('b', c.__dict__) self.assertEqual(c.b, []) self.assertIn('c', c.__dict__) self.assertEqual(c.c, []) self.assertNotIn('d', c.__dict__) self.assertIn('e', c.__dict__) self.assertEqual(c.e, 0) def test_alternate_classmethod_constructor(self): # Since __post_init__ can't take params, use a classmethod # alternate constructor. This is mostly an example to show # how to use this technique. @dataclass class C: x: int @classmethod def from_file(cls, filename): # In a real example, create a new instance # and populate 'x' from contents of a file. value_in_file = 20 return cls(value_in_file) self.assertEqual(C.from_file('filename').x, 20) def test_field_metadata_default(self): # Make sure the default metadata is read-only and of # zero length. @dataclass class C: i: int self.assertFalse(fields(C)[0].metadata) self.assertEqual(len(fields(C)[0].metadata), 0) with self.assertRaisesRegex(TypeError, 'does not support item assignment'): fields(C)[0].metadata['test'] = 3 def test_field_metadata_mapping(self): # Make sure only a mapping can be passed as metadata # zero length. with self.assertRaises(TypeError): @dataclass class C: i: int = field(metadata=0) # Make sure an empty dict works. d = {} @dataclass class C: i: int = field(metadata=d) self.assertFalse(fields(C)[0].metadata) self.assertEqual(len(fields(C)[0].metadata), 0) # Update should work (see bpo-35960). d['foo'] = 1 self.assertEqual(len(fields(C)[0].metadata), 1) self.assertEqual(fields(C)[0].metadata['foo'], 1) with self.assertRaisesRegex(TypeError, 'does not support item assignment'): fields(C)[0].metadata['test'] = 3 # Make sure a non-empty dict works. d = {'test': 10, 'bar': '42', 3: 'three'} @dataclass class C: i: int = field(metadata=d) self.assertEqual(len(fields(C)[0].metadata), 3) self.assertEqual(fields(C)[0].metadata['test'], 10) self.assertEqual(fields(C)[0].metadata['bar'], '42') self.assertEqual(fields(C)[0].metadata[3], 'three') # Update should work. d['foo'] = 1 self.assertEqual(len(fields(C)[0].metadata), 4) self.assertEqual(fields(C)[0].metadata['foo'], 1) with self.assertRaises(KeyError): # Non-existent key. fields(C)[0].metadata['baz'] with self.assertRaisesRegex(TypeError, 'does not support item assignment'): fields(C)[0].metadata['test'] = 3 def test_field_metadata_custom_mapping(self): # Try a custom mapping. class SimpleNameSpace: def __init__(self, **kw): self.__dict__.update(kw) def __getitem__(self, item): if item == 'xyzzy': return 'plugh' return getattr(self, item) def __len__(self): return self.__dict__.__len__() @dataclass class C: i: int = field(metadata=SimpleNameSpace(a=10)) self.assertEqual(len(fields(C)[0].metadata), 1) self.assertEqual(fields(C)[0].metadata['a'], 10) with self.assertRaises(AttributeError): fields(C)[0].metadata['b'] # Make sure we're still talking to our custom mapping. self.assertEqual(fields(C)[0].metadata['xyzzy'], 'plugh') def test_generic_dataclasses(self): T = TypeVar('T') @dataclass class LabeledBox(Generic[T]): content: T label: str = '<unknown>' box = LabeledBox(42) self.assertEqual(box.content, 42) self.assertEqual(box.label, '<unknown>') # Subscripting the resulting class should work, etc. Alias = List[LabeledBox[int]] def test_generic_extending(self): S = TypeVar('S') T = TypeVar('T') @dataclass class Base(Generic[T, S]): x: T y: S @dataclass class DataDerived(Base[int, T]): new_field: str Alias = DataDerived[str] c = Alias(0, 'test1', 'test2') self.assertEqual(astuple(c), (0, 'test1', 'test2')) class NonDataDerived(Base[int, T]): def new_method(self): return self.y Alias = NonDataDerived[float] c = Alias(10, 1.0) self.assertEqual(c.new_method(), 1.0) def test_generic_dynamic(self): T = TypeVar('T') @dataclass class Parent(Generic[T]): x: T Child = make_dataclass('Child', [('y', T), ('z', Optional[T], None)], bases=(Parent[int], Generic[T]), namespace={'other': 42}) self.assertIs(Child[int](1, 2).z, None) self.assertEqual(Child[int](1, 2, 3).z, 3) self.assertEqual(Child[int](1, 2, 3).other, 42) # Check that type aliases work correctly. Alias = Child[T] self.assertEqual(Alias[int](1, 2).x, 1) # Check MRO resolution. self.assertEqual(Child.__mro__, (Child, Parent, Generic, object)) def test_dataclasses_pickleable(self): global P, Q, R @dataclass class P: x: int y: int = 0 @dataclass class Q: x: int y: int = field(default=0, init=False) @dataclass class R: x: int y: List[int] = field(default_factory=list) q = Q(1) q.y = 2 samples = [P(1), P(1, 2), Q(1), q, R(1), R(1, [2, 3, 4])] for sample in samples: for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(sample=sample, proto=proto): new_sample = pickle.loads(pickle.dumps(sample, proto)) self.assertEqual(sample.x, new_sample.x) self.assertEqual(sample.y, new_sample.y) self.assertIsNot(sample, new_sample) new_sample.x = 42 another_new_sample = pickle.loads(pickle.dumps(new_sample, proto)) self.assertEqual(new_sample.x, another_new_sample.x) self.assertEqual(sample.y, another_new_sample.y) def test_dataclasses_qualnames(self): @dataclass(order=True, unsafe_hash=True, frozen=True) class A: x: int y: int self.assertEqual(A.__init__.__name__, "__init__") for function in ( '__eq__', '__lt__', '__le__', '__gt__', '__ge__', '__hash__', '__init__', '__repr__', '__setattr__', '__delattr__', ): self.assertEqual(getattr(A, function).__qualname__, f"TestCase.test_dataclasses_qualnames.<locals>.A.{function}") with self.assertRaisesRegex(TypeError, r"A\.__init__\(\) missing"): A() class TestFieldNoAnnotation(unittest.TestCase): def test_field_without_annotation(self): with self.assertRaisesRegex(TypeError, "'f' is a field but has no type annotation"): @dataclass class C: f = field() def test_field_without_annotation_but_annotation_in_base(self): @dataclass class B: f: int with self.assertRaisesRegex(TypeError, "'f' is a field but has no type annotation"): # This is still an error: make sure we don't pick up the # type annotation in the base class. @dataclass class C(B): f = field() def test_field_without_annotation_but_annotation_in_base_not_dataclass(self): # Same test, but with the base class not a dataclass. class B: f: int with self.assertRaisesRegex(TypeError, "'f' is a field but has no type annotation"): # This is still an error: make sure we don't pick up the # type annotation in the base class. @dataclass class C(B): f = field() class TestDocString(unittest.TestCase): def assertDocStrEqual(self, a, b): # Because 3.6 and 3.7 differ in how inspect.signature work # (see bpo #32108), for the time being just compare them with # whitespace stripped. self.assertEqual(a.replace(' ', ''), b.replace(' ', '')) @support.requires_docstrings def test_existing_docstring_not_overridden(self): @dataclass class C: """Lorem ipsum""" x: int self.assertEqual(C.__doc__, "Lorem ipsum") def test_docstring_no_fields(self): @dataclass class C: pass self.assertDocStrEqual(C.__doc__, "C()") def test_docstring_one_field(self): @dataclass class C: x: int self.assertDocStrEqual(C.__doc__, "C(x:int)") def test_docstring_two_fields(self): @dataclass class C: x: int y: int self.assertDocStrEqual(C.__doc__, "C(x:int, y:int)") def test_docstring_three_fields(self): @dataclass class C: x: int y: int z: str self.assertDocStrEqual(C.__doc__, "C(x:int, y:int, z:str)") def test_docstring_one_field_with_default(self): @dataclass class C: x: int = 3 self.assertDocStrEqual(C.__doc__, "C(x:int=3)") def test_docstring_one_field_with_default_none(self): @dataclass class C: x: Union[int, type(None)] = None self.assertDocStrEqual(C.__doc__, "C(x:int|None=None)") def test_docstring_list_field(self): @dataclass class C: x: List[int] self.assertDocStrEqual(C.__doc__, "C(x:List[int])") def test_docstring_list_field_with_default_factory(self): @dataclass class C: x: List[int] = field(default_factory=list) self.assertDocStrEqual(C.__doc__, "C(x:List[int]=<factory>)") def test_docstring_deque_field(self): @dataclass class C: x: deque self.assertDocStrEqual(C.__doc__, "C(x:collections.deque)") def test_docstring_deque_field_with_default_factory(self): @dataclass class C: x: deque = field(default_factory=deque) self.assertDocStrEqual(C.__doc__, "C(x:collections.deque=<factory>)") def test_docstring_undefined_name(self): @dataclass class C: x: undef self.assertDocStrEqual(C.__doc__, "C(x:undef)") def test_docstring_with_unsolvable_forward_ref_in_init(self): # See: https://github.com/python/cpython/issues/128184 ns = {} exec( textwrap.dedent( """ from dataclasses import dataclass @dataclass class C: def __init__(self, x: X, num: int) -> None: ... """, ), ns, ) self.assertDocStrEqual(ns['C'].__doc__, "C(x:X,num:int)") def test_docstring_with_no_signature(self): # See https://github.com/python/cpython/issues/103449 class Meta(type): __call__ = dict class Base(metaclass=Meta): pass @dataclass class C(Base): pass self.assertDocStrEqual(C.__doc__, "C") class TestInit(unittest.TestCase): def test_base_has_init(self): class B: def __init__(self): self.z = 100 # Make sure that declaring this class doesn't raise an error. # The issue is that we can't override __init__ in our class, # but it should be okay to add __init__ to us if our base has # an __init__. @dataclass class C(B): x: int = 0 c = C(10) self.assertEqual(c.x, 10) self.assertNotIn('z', vars(c)) # Make sure that if we don't add an init, the base __init__ # gets called. @dataclass(init=False) class C(B): x: int = 10 c = C() self.assertEqual(c.x, 10) self.assertEqual(c.z, 100) def test_no_init(self): @dataclass(init=False) class C: i: int = 0 self.assertEqual(C().i, 0) @dataclass(init=False) class C: i: int = 2 def __init__(self): self.i = 3 self.assertEqual(C().i, 3) def test_overwriting_init(self): # If the class has __init__, use it no matter the value of # init=. @dataclass class C: x: int def __init__(self, x): self.x = 2 * x self.assertEqual(C(3).x, 6) @dataclass(init=True) class C: x: int def __init__(self, x): self.x = 2 * x self.assertEqual(C(4).x, 8) @dataclass(init=False) class C: x: int def __init__(self, x): self.x = 2 * x self.assertEqual(C(5).x, 10) def test_inherit_from_protocol(self): # Dataclasses inheriting from protocol should preserve their own `__init__`. # See bpo-45081. class P(Protocol): a: int @dataclass class C(P): a: int self.assertEqual(C(5).a, 5) @dataclass class D(P): def __init__(self, a): self.a = a * 2 self.assertEqual(D(5).a, 10) class TestInitAnnotate(unittest.TestCase): # Tests for the generated __annotate__ function for __init__ # See: https://github.com/python/cpython/issues/137530 def test_annotate_function(self): # No forward references @dataclass class A: a: int value_annos = annotationlib.get_annotations(A.__init__, format=annotationlib.Format.VALUE) forwardref_annos = annotationlib.get_annotations(A.__init__, format=annotationlib.Format.FORWARDREF) string_annos = annotationlib.get_annotations(A.__init__, format=annotationlib.Format.STRING) self.assertEqual(value_annos, {'a': int, 'return': None}) self.assertEqual(forwardref_annos, {'a': int, 'return': None}) self.assertEqual(string_annos, {'a': 'int', 'return': 'None'}) self.assertTrue(getattr(A.__init__.__annotate__, "__generated_by_dataclasses__")) def test_annotate_function_forwardref(self): # With forward references @dataclass class B: b: undefined # VALUE annotations should raise while unresolvable with self.assertRaises(NameError): _ = annotationlib.get_annotations(B.__init__, format=annotationlib.Format.VALUE) forwardref_annos = annotationlib.get_annotations(B.__init__, format=annotationlib.Format.FORWARDREF) string_annos = annotationlib.get_annotations(B.__init__, format=annotationlib.Format.STRING) self.assertEqual(forwardref_annos, {'b': support.EqualToForwardRef('undefined', owner=B, is_class=True), 'return': None}) self.assertEqual(string_annos, {'b': 'undefined', 'return': 'None'}) # Now VALUE and FORWARDREF should resolve, STRING should be unchanged undefined = int value_annos = annotationlib.get_annotations(B.__init__, format=annotationlib.Format.VALUE) forwardref_annos = annotationlib.get_annotations(B.__init__, format=annotationlib.Format.FORWARDREF) string_annos = annotationlib.get_annotations(B.__init__, format=annotationlib.Format.STRING) self.assertEqual(value_annos, {'b': int, 'return': None}) self.assertEqual(forwardref_annos, {'b': int, 'return': None}) self.assertEqual(string_annos, {'b': 'undefined', 'return': 'None'}) def test_annotate_function_init_false(self): # Check `init=False` attributes don't get into the annotations of the __init__ function @dataclass class C: c: str = field(init=False) self.assertEqual(annotationlib.get_annotations(C.__init__), {'return': None}) def test_annotate_function_contains_forwardref(self): # Check string annotations on objects containing a ForwardRef @dataclass class D: d: list[undefined] with self.assertRaises(NameError): annotationlib.get_annotations(D.__init__) self.assertEqual( annotationlib.get_annotations(D.__init__, format=annotationlib.Format.FORWARDREF), {"d": list[support.EqualToForwardRef("undefined", is_class=True, owner=D)], "return": None} ) self.assertEqual( annotationlib.get_annotations(D.__init__, format=annotationlib.Format.STRING), {"d": "list[undefined]", "return": "None"} ) # Now test when it is defined undefined = str # VALUE should now resolve self.assertEqual( annotationlib.get_annotations(D.__init__), {"d": list[str], "return": None} ) self.assertEqual( annotationlib.get_annotations(D.__init__, format=annotationlib.Format.FORWARDREF), {"d": list[str], "return": None} ) self.assertEqual( annotationlib.get_annotations(D.__init__, format=annotationlib.Format.STRING), {"d": "list[undefined]", "return": "None"} ) def test_annotate_function_not_replaced(self): # Check that __annotate__ is not replaced on non-generated __init__ functions @dataclass(slots=True) class E: x: str def __init__(self, x: int) -> None: self.x = x self.assertEqual( annotationlib.get_annotations(E.__init__), {"x": int, "return": None} ) self.assertFalse(hasattr(E.__init__.__annotate__, "__generated_by_dataclasses__")) def test_slots_true_init_false(self): # Test that slots=True and init=False work together and # that __annotate__ is not added to __init__. @dataclass(slots=True, init=False) class F: x: int f = F() f.x = 10 self.assertEqual(f.x, 10) self.assertFalse(hasattr(F.__init__, "__annotate__")) def test_init_false_forwardref(self): # Test forward references in fields not required for __init__ annotations. # At the moment this raises a NameError for VALUE annotations even though the # undefined annotation is not required for the __init__ annotations. # Ideally this will be fixed but currently there is no good way to resolve this @dataclass class F: not_in_init: list[undefined] = field(init=False, default=None) in_init: int annos = annotationlib.get_annotations(F.__init__, format=annotationlib.Format.FORWARDREF) self.assertEqual( annos, {"in_init": int, "return": None}, ) with self.assertRaises(NameError): annos = annotationlib.get_annotations(F.__init__) # NameError on not_in_init class TestRepr(unittest.TestCase): def test_repr(self): @dataclass class B: x: int @dataclass class C(B): y: int = 10 o = C(4) self.assertEqual(repr(o), 'TestRepr.test_repr.<locals>.C(x=4, y=10)') @dataclass class D(C): x: int = 20 self.assertEqual(repr(D()), 'TestRepr.test_repr.<locals>.D(x=20, y=10)') @dataclass class C: @dataclass class D: i: int @dataclass class E: pass self.assertEqual(repr(C.D(0)), 'TestRepr.test_repr.<locals>.C.D(i=0)') self.assertEqual(repr(C.E()), 'TestRepr.test_repr.<locals>.C.E()') def test_no_repr(self): # Test a class with no __repr__ and repr=False. @dataclass(repr=False) class C: x: int self.assertIn(f'{__name__}.TestRepr.test_no_repr.<locals>.C object at', repr(C(3))) # Test a class with a __repr__ and repr=False. @dataclass(repr=False) class C: x: int def __repr__(self): return 'C-class' self.assertEqual(repr(C(3)), 'C-class') def test_overwriting_repr(self): # If the class has __repr__, use it no matter the value of # repr=. @dataclass class C: x: int def __repr__(self): return 'x' self.assertEqual(repr(C(0)), 'x') @dataclass(repr=True) class C: x: int def __repr__(self): return 'x' self.assertEqual(repr(C(0)), 'x') @dataclass(repr=False) class C: x: int def __repr__(self): return 'x' self.assertEqual(repr(C(0)), 'x') class TestEq(unittest.TestCase): def test_recursive_eq(self): # Test a class with recursive child @dataclass class C: recursive: object = ... c = C() c.recursive = c self.assertEqual(c, c) def test_no_eq(self): # Test a class with no __eq__ and eq=False. @dataclass(eq=False) class C: x: int self.assertNotEqual(C(0), C(0)) c = C(3) self.assertEqual(c, c) # Test a class with an __eq__ and eq=False. @dataclass(eq=False) class C: x: int def __eq__(self, other): return other == 10 self.assertEqual(C(3), 10) def test_overwriting_eq(self): # If the class has __eq__, use it no matter the value of # eq=. @dataclass class C: x: int def __eq__(self, other): return other == 3 self.assertEqual(C(1), 3) self.assertNotEqual(C(1), 1) @dataclass(eq=True) class C: x: int def __eq__(self, other): return other == 4 self.assertEqual(C(1), 4) self.assertNotEqual(C(1), 1) @dataclass(eq=False) class C: x: int def __eq__(self, other): return other == 5 self.assertEqual(C(1), 5) self.assertNotEqual(C(1), 1) class TestOrdering(unittest.TestCase): def test_functools_total_ordering(self): # Test that functools.total_ordering works with this class. @total_ordering @dataclass class C: x: int def __lt__(self, other): # Perform the test "backward", just to make # sure this is being called. return self.x >= other self.assertLess(C(0), -1) self.assertLessEqual(C(0), -1) self.assertGreater(C(0), 1) self.assertGreaterEqual(C(0), 1) def test_no_order(self): # Test that no ordering functions are added by default. @dataclass(order=False) class C: x: int # Make sure no order methods are added. self.assertNotIn('__le__', C.__dict__) self.assertNotIn('__lt__', C.__dict__) self.assertNotIn('__ge__', C.__dict__) self.assertNotIn('__gt__', C.__dict__) # Test that __lt__ is still called @dataclass(order=False) class C: x: int def __lt__(self, other): return False # Make sure other methods aren't added. self.assertNotIn('__le__', C.__dict__) self.assertNotIn('__ge__', C.__dict__) self.assertNotIn('__gt__', C.__dict__) def test_overwriting_order(self): with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __lt__' '.*using functools.total_ordering'): @dataclass(order=True) class C: x: int def __lt__(self): pass with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __le__' '.*using functools.total_ordering'): @dataclass(order=True) class C: x: int def __le__(self): pass with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __gt__' '.*using functools.total_ordering'): @dataclass(order=True) class C: x: int def __gt__(self): pass with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __ge__' '.*using functools.total_ordering'): @dataclass(order=True) class C: x: int def __ge__(self): pass class TestHash(unittest.TestCase): def test_unsafe_hash(self): @dataclass(unsafe_hash=True) class C: x: int y: str self.assertEqual(hash(C(1, 'foo')), hash((1, 'foo'))) def test_hash_rules(self): def non_bool(value): # Map to something else that's True, but not a bool. if value is None: return None if value: return (3,) return 0 def test(case, unsafe_hash, eq, frozen, with_hash, result): with self.subTest(case=case, unsafe_hash=unsafe_hash, eq=eq, frozen=frozen): if result != 'exception': if with_hash: @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen) class C: def __hash__(self): return 0 else: @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen) class C: pass # See if the result matches what's expected. if result == 'fn': # __hash__ contains the function we generated. self.assertIn('__hash__', C.__dict__) self.assertIsNotNone(C.__dict__['__hash__']) elif result == '': # __hash__ is not present in our class. if not with_hash: self.assertNotIn('__hash__', C.__dict__) elif result == 'none': # __hash__ is set to None. self.assertIn('__hash__', C.__dict__) self.assertIsNone(C.__dict__['__hash__']) elif result == 'exception': # Creating the class should cause an exception. # This only happens with with_hash==True. assert(with_hash) with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __hash__'): @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen) class C: def __hash__(self): return 0 else: assert False, f'unknown result {result!r}' # There are 8 cases of: # unsafe_hash=True/False # eq=True/False # frozen=True/False # And for each of these, a different result if # __hash__ is defined or not. for case, (unsafe_hash, eq, frozen, res_no_defined_hash, res_defined_hash) in enumerate([ (False, False, False, '', ''), (False, False, True, '', ''), (False, True, False, 'none', ''), (False, True, True, 'fn', ''), (True, False, False, 'fn', 'exception'), (True, False, True, 'fn', 'exception'), (True, True, False, 'fn', 'exception'), (True, True, True, 'fn', 'exception'), ], 1): test(case, unsafe_hash, eq, frozen, False, res_no_defined_hash) test(case, unsafe_hash, eq, frozen, True, res_defined_hash) # Test non-bool truth values, too. This is just to # make sure the data-driven table in the decorator # handles non-bool values. test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), False, res_no_defined_hash) test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), True, res_defined_hash) def test_eq_only(self): # If a class defines __eq__, __hash__ is automatically added # and set to None. This is normal Python behavior, not # related to dataclasses. Make sure we don't interfere with # that (see bpo=32546). @dataclass class C: i: int def __eq__(self, other): return self.i == other.i self.assertEqual(C(1), C(1)) self.assertNotEqual(C(1), C(4)) # And make sure things work in this case if we specify # unsafe_hash=True. @dataclass(unsafe_hash=True) class C: i: int def __eq__(self, other): return self.i == other.i self.assertEqual(C(1), C(1.0)) self.assertEqual(hash(C(1)), hash(C(1.0))) # And check that the classes __eq__ is being used, despite # specifying eq=True. @dataclass(unsafe_hash=True, eq=True) class C: i: int def __eq__(self, other): return self.i == 3 and self.i == other.i self.assertEqual(C(3), C(3)) self.assertNotEqual(C(1), C(1)) self.assertEqual(hash(C(1)), hash(C(1.0))) def test_0_field_hash(self): @dataclass(frozen=True) class C: pass self.assertEqual(hash(C()), hash(())) @dataclass(unsafe_hash=True) class C: pass self.assertEqual(hash(C()), hash(())) def test_1_field_hash(self): @dataclass(frozen=True) class C: x: int self.assertEqual(hash(C(4)), hash((4,))) self.assertEqual(hash(C(42)), hash((42,))) @dataclass(unsafe_hash=True) class C: x: int self.assertEqual(hash(C(4)), hash((4,))) self.assertEqual(hash(C(42)), hash((42,))) def test_hash_no_args(self): # Test dataclasses with no hash= argument. This exists to # make sure that if the @dataclass parameter name is changed # or the non-default hashing behavior changes, the default # hashability keeps working the same way. class Base: def __hash__(self): return 301 # If frozen or eq is None, then use the default value (do not # specify any value in the decorator). for frozen, eq, base, expected in [ (None, None, object, 'unhashable'), (None, None, Base, 'unhashable'), (None, False, object, 'object'), (None, False, Base, 'base'), (None, True, object, 'unhashable'), (None, True, Base, 'unhashable'), (False, None, object, 'unhashable'), (False, None, Base, 'unhashable'), (False, False, object, 'object'), (False, False, Base, 'base'), (False, True, object, 'unhashable'), (False, True, Base, 'unhashable'), (True, None, object, 'tuple'), (True, None, Base, 'tuple'), (True, False, object, 'object'), (True, False, Base, 'base'), (True, True, object, 'tuple'), (True, True, Base, 'tuple'), ]: with self.subTest(frozen=frozen, eq=eq, base=base, expected=expected): # First, create the class. if frozen is None and eq is None: @dataclass class C(base): i: int elif frozen is None: @dataclass(eq=eq) class C(base): i: int elif eq is None: @dataclass(frozen=frozen) class C(base): i: int else: @dataclass(frozen=frozen, eq=eq) class C(base): i: int # Now, make sure it hashes as expected. if expected == 'unhashable': c = C(10) with self.assertRaisesRegex(TypeError, 'unhashable type'): hash(c) elif expected == 'base': self.assertEqual(hash(C(10)), 301) elif expected == 'object': # I'm not sure what test to use here. object's # hash isn't based on id(), so calling hash() # won't tell us much. So, just check the # function used is object's. self.assertIs(C.__hash__, object.__hash__) elif expected == 'tuple': self.assertEqual(hash(C(42)), hash((42,))) else: assert False, f'unknown value for expected={expected!r}' class TestFrozen(unittest.TestCase): def test_frozen(self): @dataclass(frozen=True) class C: i: int c = C(10) self.assertEqual(c.i, 10) with self.assertRaises(FrozenInstanceError): c.i = 5 self.assertEqual(c.i, 10) def test_frozen_empty(self): @dataclass(frozen=True) class C: pass c = C() self.assertNotHasAttr(c, 'i') with self.assertRaises(FrozenInstanceError): c.i = 5 self.assertNotHasAttr(c, 'i') with self.assertRaises(FrozenInstanceError): del c.i def test_inherit(self): @dataclass(frozen=True) class C: i: int @dataclass(frozen=True) class D(C): j: int d = D(0, 10) with self.assertRaises(FrozenInstanceError): d.i = 5 with self.assertRaises(FrozenInstanceError): d.j = 6 self.assertEqual(d.i, 0) self.assertEqual(d.j, 10) def test_inherit_nonfrozen_from_empty_frozen(self): @dataclass(frozen=True) class C: pass with self.assertRaisesRegex(TypeError, 'cannot inherit non-frozen dataclass from a frozen one'): @dataclass class D(C): j: int def test_inherit_frozen_mutliple_inheritance(self): @dataclass class NotFrozen: pass @dataclass(frozen=True) class Frozen: pass class NotDataclass: pass for bases in ( (NotFrozen, Frozen), (Frozen, NotFrozen), (Frozen, NotDataclass), (NotDataclass, Frozen), ): with self.subTest(bases=bases): with self.assertRaisesRegex( TypeError, 'cannot inherit non-frozen dataclass from a frozen one', ): @dataclass class NotFrozenChild(*bases): pass for bases in ( (NotFrozen, Frozen), (Frozen, NotFrozen), (NotFrozen, NotDataclass), (NotDataclass, NotFrozen), ): with self.subTest(bases=bases): with self.assertRaisesRegex( TypeError, 'cannot inherit frozen dataclass from a non-frozen one', ): @dataclass(frozen=True) class FrozenChild(*bases): pass def test_inherit_frozen_mutliple_inheritance_regular_mixins(self): @dataclass(frozen=True) class Frozen: pass class NotDataclass: pass class C1(Frozen, NotDataclass): pass self.assertEqual(C1.__mro__, (C1, Frozen, NotDataclass, object)) class C2(NotDataclass, Frozen): pass self.assertEqual(C2.__mro__, (C2, NotDataclass, Frozen, object)) @dataclass(frozen=True) class C3(Frozen, NotDataclass): pass self.assertEqual(C3.__mro__, (C3, Frozen, NotDataclass, object)) @dataclass(frozen=True) class C4(NotDataclass, Frozen): pass self.assertEqual(C4.__mro__, (C4, NotDataclass, Frozen, object)) def test_multiple_frozen_dataclasses_inheritance(self): @dataclass(frozen=True) class FrozenA: pass @dataclass(frozen=True) class FrozenB: pass class C1(FrozenA, FrozenB): pass self.assertEqual(C1.__mro__, (C1, FrozenA, FrozenB, object)) class C2(FrozenB, FrozenA): pass self.assertEqual(C2.__mro__, (C2, FrozenB, FrozenA, object)) @dataclass(frozen=True) class C3(FrozenA, FrozenB): pass self.assertEqual(C3.__mro__, (C3, FrozenA, FrozenB, object)) @dataclass(frozen=True) class C4(FrozenB, FrozenA): pass self.assertEqual(C4.__mro__, (C4, FrozenB, FrozenA, object)) def test_inherit_nonfrozen_from_empty(self): @dataclass class C: pass @dataclass class D(C): j: int d = D(3) self.assertEqual(d.j, 3) self.assertIsInstance(d, C) # Test both ways: with an intermediate normal (non-dataclass) # class and without an intermediate class. def test_inherit_nonfrozen_from_frozen(self): for intermediate_class in [True, False]: with self.subTest(intermediate_class=intermediate_class): @dataclass(frozen=True) class C: i: int if intermediate_class: class I(C): pass else: I = C with self.assertRaisesRegex(TypeError, 'cannot inherit non-frozen dataclass from a frozen one'): @dataclass class D(I): pass def test_inherit_frozen_from_nonfrozen(self): for intermediate_class in [True, False]: with self.subTest(intermediate_class=intermediate_class): @dataclass class C: i: int if intermediate_class: class I(C): pass else: I = C with self.assertRaisesRegex(TypeError, 'cannot inherit frozen dataclass from a non-frozen one'): @dataclass(frozen=True) class D(I): pass def test_inherit_from_normal_class(self): for intermediate_class in [True, False]: with self.subTest(intermediate_class=intermediate_class): class C: pass if intermediate_class: class I(C): pass else: I = C @dataclass(frozen=True) class D(I): i: int d = D(10) with self.assertRaises(FrozenInstanceError): d.i = 5 def test_non_frozen_normal_derived(self): # See bpo-32953. @dataclass(frozen=True) class D: x: int y: int = 10 class S(D): pass s = S(3) self.assertEqual(s.x, 3) self.assertEqual(s.y, 10) s.cached = True # But can't change the frozen attributes. with self.assertRaises(FrozenInstanceError): s.x = 5 with self.assertRaises(FrozenInstanceError): s.y = 5 self.assertEqual(s.x, 3) self.assertEqual(s.y, 10) self.assertEqual(s.cached, True) with self.assertRaises(FrozenInstanceError): del s.x self.assertEqual(s.x, 3) with self.assertRaises(FrozenInstanceError): del s.y self.assertEqual(s.y, 10) del s.cached self.assertNotHasAttr(s, 'cached') with self.assertRaises(AttributeError) as cm: del s.cached self.assertNotIsInstance(cm.exception, FrozenInstanceError) def test_non_frozen_normal_derived_from_empty_frozen(self): @dataclass(frozen=True) class D: pass class S(D): pass s = S() self.assertNotHasAttr(s, 'x') s.x = 5 self.assertEqual(s.x, 5) del s.x self.assertNotHasAttr(s, 'x') with self.assertRaises(AttributeError) as cm: del s.x self.assertNotIsInstance(cm.exception, FrozenInstanceError) def test_overwriting_frozen(self): # frozen uses __setattr__ and __delattr__. with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __setattr__'): @dataclass(frozen=True) class C: x: int def __setattr__(self): pass with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __delattr__'): @dataclass(frozen=True) class C: x: int def __delattr__(self): pass @dataclass(frozen=False) class C: x: int def __setattr__(self, name, value): self.__dict__['x'] = value * 2 self.assertEqual(C(10).x, 20) def test_frozen_hash(self): @dataclass(frozen=True) class C: x: Any # If x is immutable, we can compute the hash. No exception is # raised. hash(C(3)) # If x is mutable, computing the hash is an error. with self.assertRaisesRegex(TypeError, 'unhashable type'): hash(C({})) def test_frozen_deepcopy_without_slots(self): # see: https://github.com/python/cpython/issues/89683 @dataclass(frozen=True, slots=False) class C: s: str c = C('hello') self.assertEqual(deepcopy(c), c) def test_frozen_deepcopy_with_slots(self): # see: https://github.com/python/cpython/issues/89683 with self.subTest('generated __slots__'): @dataclass(frozen=True, slots=True) class C: s: str c = C('hello') self.assertEqual(deepcopy(c), c) with self.subTest('user-defined __slots__ and no __{get,set}state__'): @dataclass(frozen=True, slots=False) class C: __slots__ = ('s',) s: str # with user-defined slots, __getstate__ and __setstate__ are not # automatically added, hence the error err = r"^cannot\ assign\ to\ field\ 's'$" self.assertRaisesRegex(FrozenInstanceError, err, deepcopy, C('')) with self.subTest('user-defined __slots__ and __{get,set}state__'): @dataclass(frozen=True, slots=False) class C: __slots__ = ('s',) __getstate__ = dataclasses._dataclass_getstate __setstate__ = dataclasses._dataclass_setstate s: str c = C('hello') self.assertEqual(deepcopy(c), c) class TestSlots(unittest.TestCase): def test_simple(self): @dataclass class C: __slots__ = ('x',) x: Any # There was a bug where a variable in a slot was assumed to # also have a default value (of type # types.MemberDescriptorType). with self.assertRaisesRegex(TypeError, r"__init__\(\) missing 1 required positional argument: 'x'"): C() # We can create an instance, and assign to x. c = C(10) self.assertEqual(c.x, 10) c.x = 5 self.assertEqual(c.x, 5) # We can't assign to anything else. with self.assertRaisesRegex(AttributeError, "'C' object has no attribute 'y'"): c.y = 5 def test_derived_added_field(self): # See bpo-33100. @dataclass class Base: __slots__ = ('x',) x: Any @dataclass class Derived(Base): x: int y: int d = Derived(1, 2) self.assertEqual((d.x, d.y), (1, 2)) # We can add a new field to the derived instance. d.z = 10 def test_generated_slots(self): @dataclass(slots=True) class C: x: int y: int c = C(1, 2) self.assertEqual((c.x, c.y), (1, 2)) c.x = 3 c.y = 4 self.assertEqual((c.x, c.y), (3, 4)) with self.assertRaisesRegex(AttributeError, "'C' object has no attribute 'z'"): c.z = 5 def test_add_slots_when_slots_exists(self): with self.assertRaisesRegex(TypeError, '^C already specifies __slots__$'): @dataclass(slots=True) class C: __slots__ = ('x',) x: int def test_generated_slots_value(self): class Root: __slots__ = {'x'} class Root2(Root): __slots__ = {'k': '...', 'j': ''} class Root3(Root2): __slots__ = ['h'] class Root4(Root3): __slots__ = 'aa' @dataclass(slots=True) class Base(Root4): y: int j: str h: str self.assertEqual(Base.__slots__, ('y',)) @dataclass(slots=True) class Derived(Base): aa: float x: str z: int k: str h: str self.assertEqual(Derived.__slots__, ('z',)) @dataclass class AnotherDerived(Base): z: int self.assertNotIn('__slots__', AnotherDerived.__dict__) def test_slots_with_docs(self): class Root: __slots__ = {'x': 'x'} @dataclass(slots=True) class Base(Root): y1: int = field(doc='y1') y2: int self.assertEqual(Base.__slots__, {'y1': 'y1', 'y2': None}) @dataclass(slots=True) class Child(Base): z1: int = field(doc='z1') z2: int self.assertEqual(Child.__slots__, {'z1': 'z1', 'z2': None}) def test_cant_inherit_from_iterator_slots(self): class Root: __slots__ = iter(['a']) class Root2(Root): __slots__ = ('b', ) with self.assertRaisesRegex( TypeError, "^Slots of 'Root' cannot be determined" ): @dataclass(slots=True) class C(Root2): x: int def test_returns_new_class(self): class A: x: int B = dataclass(A, slots=True) self.assertIsNot(A, B) self.assertNotHasAttr(A, "__slots__") self.assertHasAttr(B, "__slots__") # Can't be local to test_frozen_pickle. @dataclass(frozen=True, slots=True) class FrozenSlotsClass: foo: str bar: int @dataclass(frozen=True) class FrozenWithoutSlotsClass: foo: str bar: int def test_frozen_pickle(self): # bpo-43999 self.assertEqual(self.FrozenSlotsClass.__slots__, ("foo", "bar")) for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(proto=proto): obj = self.FrozenSlotsClass("a", 1) p = pickle.loads(pickle.dumps(obj, protocol=proto)) self.assertIsNot(obj, p) self.assertEqual(obj, p) obj = self.FrozenWithoutSlotsClass("a", 1) p = pickle.loads(pickle.dumps(obj, protocol=proto)) self.assertIsNot(obj, p) self.assertEqual(obj, p) @dataclass(frozen=True, slots=True) class FrozenSlotsGetStateClass: foo: str bar: int getstate_called: bool = field(default=False, compare=False) def __getstate__(self): object.__setattr__(self, 'getstate_called', True) return [self.foo, self.bar] @dataclass(frozen=True, slots=True) class FrozenSlotsSetStateClass: foo: str bar: int setstate_called: bool = field(default=False, compare=False) def __setstate__(self, state): object.__setattr__(self, 'setstate_called', True) object.__setattr__(self, 'foo', state[0]) object.__setattr__(self, 'bar', state[1]) @dataclass(frozen=True, slots=True) class FrozenSlotsAllStateClass: foo: str bar: int getstate_called: bool = field(default=False, compare=False) setstate_called: bool = field(default=False, compare=False) def __getstate__(self): object.__setattr__(self, 'getstate_called', True) return [self.foo, self.bar] def __setstate__(self, state): object.__setattr__(self, 'setstate_called', True) object.__setattr__(self, 'foo', state[0]) object.__setattr__(self, 'bar', state[1]) def test_frozen_slots_pickle_custom_state(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(proto=proto): obj = self.FrozenSlotsGetStateClass('a', 1) dumped = pickle.dumps(obj, protocol=proto) self.assertTrue(obj.getstate_called) self.assertEqual(obj, pickle.loads(dumped)) for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(proto=proto): obj = self.FrozenSlotsSetStateClass('a', 1) obj2 = pickle.loads(pickle.dumps(obj, protocol=proto)) self.assertTrue(obj2.setstate_called) self.assertEqual(obj, obj2) for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(proto=proto): obj = self.FrozenSlotsAllStateClass('a', 1) dumped = pickle.dumps(obj, protocol=proto) self.assertTrue(obj.getstate_called) obj2 = pickle.loads(dumped) self.assertTrue(obj2.setstate_called) self.assertEqual(obj, obj2) def test_slots_with_default_no_init(self): # Originally reported in bpo-44649. @dataclass(slots=True) class A: a: str b: str = field(default='b', init=False) obj = A("a") self.assertEqual(obj.a, 'a') self.assertEqual(obj.b, 'b') def test_slots_with_default_factory_no_init(self): # Originally reported in bpo-44649. @dataclass(slots=True) class A: a: str b: str = field(default_factory=lambda:'b', init=False) obj = A("a") self.assertEqual(obj.a, 'a') self.assertEqual(obj.b, 'b') def test_slots_no_weakref(self): @dataclass(slots=True) class A: # No weakref. pass self.assertNotIn("__weakref__", A.__slots__) a = A() with self.assertRaisesRegex(TypeError, "cannot create weak reference"): weakref.ref(a) with self.assertRaises(AttributeError): a.__weakref__ def test_slots_weakref(self): @dataclass(slots=True, weakref_slot=True) class A: a: int self.assertIn("__weakref__", A.__slots__) a = A(1) a_ref = weakref.ref(a) self.assertIs(a.__weakref__, a_ref) def test_slots_weakref_base_str(self): class Base: __slots__ = '__weakref__' @dataclass(slots=True) class A(Base): a: int # __weakref__ is in the base class, not A. But an A is still weakref-able. self.assertIn("__weakref__", Base.__slots__) self.assertNotIn("__weakref__", A.__slots__) a = A(1) weakref.ref(a) def test_slots_weakref_base_tuple(self): # Same as test_slots_weakref_base, but use a tuple instead of a string # in the base class. class Base: __slots__ = ('__weakref__',) @dataclass(slots=True) class A(Base): a: int # __weakref__ is in the base class, not A. But an A is still # weakref-able. self.assertIn("__weakref__", Base.__slots__) self.assertNotIn("__weakref__", A.__slots__) a = A(1) weakref.ref(a) def test_weakref_slot_without_slot(self): with self.assertRaisesRegex(TypeError, "weakref_slot is True but slots is False"): @dataclass(weakref_slot=True) class A: a: int def test_weakref_slot_make_dataclass(self): A = make_dataclass('A', [('a', int),], slots=True, weakref_slot=True) self.assertIn("__weakref__", A.__slots__) a = A(1) weakref.ref(a) # And make sure if raises if slots=True is not given. with self.assertRaisesRegex(TypeError, "weakref_slot is True but slots is False"): B = make_dataclass('B', [('a', int),], weakref_slot=True) def test_weakref_slot_subclass_weakref_slot(self): @dataclass(slots=True, weakref_slot=True) class Base: field: int # A *can* also specify weakref_slot=True if it wants to (gh-93521) @dataclass(slots=True, weakref_slot=True) class A(Base): ... # __weakref__ is in the base class, not A. But an instance of A # is still weakref-able. self.assertIn("__weakref__", Base.__slots__) self.assertNotIn("__weakref__", A.__slots__) a = A(1) a_ref = weakref.ref(a) self.assertIs(a.__weakref__, a_ref) def test_weakref_slot_subclass_no_weakref_slot(self): @dataclass(slots=True, weakref_slot=True) class Base: field: int @dataclass(slots=True) class A(Base): ... # __weakref__ is in the base class, not A. Even though A doesn't # specify weakref_slot, it should still be weakref-able. self.assertIn("__weakref__", Base.__slots__) self.assertNotIn("__weakref__", A.__slots__) a = A(1) a_ref = weakref.ref(a) self.assertIs(a.__weakref__, a_ref) def test_weakref_slot_normal_base_weakref_slot(self): class Base: __slots__ = ('__weakref__',) @dataclass(slots=True, weakref_slot=True) class A(Base): field: int # __weakref__ is in the base class, not A. But an instance of # A is still weakref-able. self.assertIn("__weakref__", Base.__slots__) self.assertNotIn("__weakref__", A.__slots__) a = A(1) a_ref = weakref.ref(a) self.assertIs(a.__weakref__, a_ref) def test_dataclass_derived_weakref_slot(self): class A: pass @dataclass(slots=True, weakref_slot=True) class B(A): pass self.assertEqual(B.__slots__, ()) B() def test_dataclass_derived_generic(self): T = typing.TypeVar('T') @dataclass(slots=True, weakref_slot=True) class A(typing.Generic[T]): pass self.assertEqual(A.__slots__, ('__weakref__',)) self.assertTrue(A.__weakref__) A() @dataclass(slots=True, weakref_slot=True) class B[T2]: pass self.assertEqual(B.__slots__, ('__weakref__',)) self.assertTrue(B.__weakref__) B() def test_dataclass_derived_generic_from_base(self): T = typing.TypeVar('T') class RawBase: ... @dataclass(slots=True, weakref_slot=True) class C1(typing.Generic[T], RawBase): pass self.assertEqual(C1.__slots__, ()) self.assertTrue(C1.__weakref__) C1() @dataclass(slots=True, weakref_slot=True) class C2(RawBase, typing.Generic[T]): pass self.assertEqual(C2.__slots__, ()) self.assertTrue(C2.__weakref__) C2() @dataclass(slots=True, weakref_slot=True) class D[T2](RawBase): pass self.assertEqual(D.__slots__, ()) self.assertTrue(D.__weakref__) D() def test_dataclass_derived_generic_from_slotted_base(self): T = typing.TypeVar('T') class WithSlots: __slots__ = ('a', 'b') @dataclass(slots=True, weakref_slot=True) class E1(WithSlots, Generic[T]): pass self.assertEqual(E1.__slots__, ('__weakref__',)) self.assertTrue(E1.__weakref__) E1() @dataclass(slots=True, weakref_slot=True) class E2(Generic[T], WithSlots): pass self.assertEqual(E2.__slots__, ('__weakref__',)) self.assertTrue(E2.__weakref__) E2() @dataclass(slots=True, weakref_slot=True) class F[T2](WithSlots): pass self.assertEqual(F.__slots__, ('__weakref__',)) self.assertTrue(F.__weakref__) F() def test_dataclass_derived_generic_from_slotted_base_with_weakref(self): T = typing.TypeVar('T') class WithWeakrefSlot: __slots__ = ('__weakref__',) @dataclass(slots=True, weakref_slot=True) class G1(WithWeakrefSlot, Generic[T]): pass self.assertEqual(G1.__slots__, ()) self.assertTrue(G1.__weakref__) G1() @dataclass(slots=True, weakref_slot=True) class G2(Generic[T], WithWeakrefSlot): pass self.assertEqual(G2.__slots__, ()) self.assertTrue(G2.__weakref__) G2() @dataclass(slots=True, weakref_slot=True) class H[T2](WithWeakrefSlot): pass self.assertEqual(H.__slots__, ()) self.assertTrue(H.__weakref__) H() def test_dataclass_slot_dict(self): class WithDictSlot: __slots__ = ('__dict__',) @dataclass(slots=True) class A(WithDictSlot): ... self.assertEqual(A.__slots__, ()) self.assertEqual(A().__dict__, {}) A() @support.cpython_only def test_dataclass_slot_dict_ctype(self): # https://github.com/python/cpython/issues/123935 # Skips test if `_testcapi` is not present: _testcapi = import_helper.import_module('_testcapi') @dataclass(slots=True) class HasDictOffset(_testcapi.HeapCTypeWithDict): __dict__: dict = {} self.assertNotEqual(_testcapi.HeapCTypeWithDict.__dictoffset__, 0) self.assertEqual(HasDictOffset.__slots__, ()) @dataclass(slots=True) class DoesNotHaveDictOffset(_testcapi.HeapCTypeWithWeakref): __dict__: dict = {} self.assertEqual(_testcapi.HeapCTypeWithWeakref.__dictoffset__, 0) self.assertEqual(DoesNotHaveDictOffset.__slots__, ('__dict__',)) @support.cpython_only def test_slots_with_wrong_init_subclass(self): # TODO: This test is for a kinda-buggy behavior. # Ideally, it should be fixed and `__init_subclass__` # should be fully supported in the future versions. # See https://github.com/python/cpython/issues/91126 class WrongSuper: def __init_subclass__(cls, arg): pass with self.assertRaisesRegex( TypeError, "missing 1 required positional argument: 'arg'", ): @dataclass(slots=True) class WithWrongSuper(WrongSuper, arg=1): pass class CorrectSuper: args = [] def __init_subclass__(cls, arg="default"): cls.args.append(arg) @dataclass(slots=True) class WithCorrectSuper(CorrectSuper): pass # __init_subclass__ is called twice: once for `WithCorrectSuper` # and once for `WithCorrectSuper__slots__` new class # that we create internally. self.assertEqual(CorrectSuper.args, ["default", "default"]) def test_original_class_is_gced(self): # gh-135228: Make sure when we replace the class with slots=True, the original class # gets garbage collected. def make_simple(): @dataclass(slots=True) class SlotsTest: pass return SlotsTest def make_with_annotations(): @dataclass(slots=True) class SlotsTest: x: int return SlotsTest def make_with_annotations_and_method(): @dataclass(slots=True) class SlotsTest: x: int def method(self) -> int: return self.x return SlotsTest def make_with_forwardref(): @dataclass(slots=True) class SlotsTest: x: undefined y: list[undefined] return SlotsTest for make in (make_simple, make_with_annotations, make_with_annotations_and_method, make_with_forwardref): with self.subTest(make=make): C = make() support.gc_collect() candidates = [cls for cls in object.__subclasses__() if cls.__name__ == 'SlotsTest' and cls.__firstlineno__ == make.__code__.co_firstlineno + 1] self.assertEqual(candidates, [C]) class TestDescriptors(unittest.TestCase): def test_set_name(self): # See bpo-33141. # Create a descriptor. class D: def __set_name__(self, owner, name): self.name = name + 'x' def __get__(self, instance, owner): if instance is not None: return 1 return self # This is the case of just normal descriptor behavior, no # dataclass code is involved in initializing the descriptor. @dataclass class C: c: int=D() self.assertEqual(C.c.name, 'cx') # Now test with a default value and init=False, which is the # only time this is really meaningful. If not using # init=False, then the descriptor will be overwritten, anyway. @dataclass class C: c: int=field(default=D(), init=False) self.assertEqual(C.c.name, 'cx') self.assertEqual(C().c, 1) def test_non_descriptor(self): # PEP 487 says __set_name__ should work on non-descriptors. # Create a descriptor. class D: def __set_name__(self, owner, name): self.name = name + 'x' @dataclass class C: c: int=field(default=D(), init=False) self.assertEqual(C.c.name, 'cx') def test_lookup_on_instance(self): # See bpo-33175. class D: pass d = D() # Create an attribute on the instance, not type. d.__set_name__ = Mock() # Make sure d.__set_name__ is not called. @dataclass class C: i: int=field(default=d, init=False) self.assertEqual(d.__set_name__.call_count, 0) def test_lookup_on_class(self): # See bpo-33175. class D: pass D.__set_name__ = Mock() # Make sure D.__set_name__ is called. @dataclass class C: i: int=field(default=D(), init=False) self.assertEqual(D.__set_name__.call_count, 1) def test_init_calls_set(self): class D: pass D.__set__ = Mock() @dataclass class C: i: D = D() # Make sure D.__set__ is called. D.__set__.reset_mock() c = C(5) self.assertEqual(D.__set__.call_count, 1) def test_getting_field_calls_get(self): class D: pass D.__set__ = Mock() D.__get__ = Mock() @dataclass class C: i: D = D() c = C(5) # Make sure D.__get__ is called. D.__get__.reset_mock() value = c.i self.assertEqual(D.__get__.call_count, 1) def test_setting_field_calls_set(self): class D: pass D.__set__ = Mock() @dataclass class C: i: D = D() c = C(5) # Make sure D.__set__ is called. D.__set__.reset_mock() c.i = 10 self.assertEqual(D.__set__.call_count, 1) def test_setting_uninitialized_descriptor_field(self): class D: pass D.__set__ = Mock() @dataclass class C: i: D # D.__set__ is not called because there's no D instance to call it on D.__set__.reset_mock() c = C(5) self.assertEqual(D.__set__.call_count, 0) # D.__set__ still isn't called after setting i to an instance of D # because descriptors don't behave like that when stored as instance vars c.i = D() c.i = 5 self.assertEqual(D.__set__.call_count, 0) def test_default_value(self): class D: def __get__(self, instance: Any, owner: object) -> int: if instance is None: return 100 return instance._x def __set__(self, instance: Any, value: int) -> None: instance._x = value @dataclass class C: i: D = D() c = C() self.assertEqual(c.i, 100) c = C(5) self.assertEqual(c.i, 5) def test_no_default_value(self): class D: def __get__(self, instance: Any, owner: object) -> int: if instance is None: raise AttributeError() return instance._x def __set__(self, instance: Any, value: int) -> None: instance._x = value @dataclass class C: i: D = D() with self.assertRaisesRegex(TypeError, 'missing 1 required positional argument'): c = C() class TestStringAnnotations(unittest.TestCase): def test_classvar(self): # Some expressions recognized as ClassVar really aren't. But # if you're using string annotations, it's not an exact # science. # These tests assume that both "import typing" and "from # typing import *" have been run in this file. for typestr in ('ClassVar[int]', 'ClassVar [int]', ' ClassVar [int]', 'ClassVar', ' ClassVar ', 'typing.ClassVar[int]', 'typing.ClassVar[str]', ' typing.ClassVar[str]', 'typing .ClassVar[str]', 'typing. ClassVar[str]', 'typing.ClassVar [str]', 'typing.ClassVar [ str]', # Not syntactically valid, but these will # be treated as ClassVars. 'typing.ClassVar.[int]', 'typing.ClassVar+', ): with self.subTest(typestr=typestr): @dataclass class C: x: typestr # x is a ClassVar, so C() takes no args. C() # And it won't appear in the class's dict because it doesn't # have a default. self.assertNotIn('x', C.__dict__) def test_isnt_classvar(self): for typestr in ('CV', 't.ClassVar', 't.ClassVar[int]', 'typing..ClassVar[int]', 'Classvar', 'Classvar[int]', 'typing.ClassVarx[int]', 'typong.ClassVar[int]', 'dataclasses.ClassVar[int]', 'typingxClassVar[str]', ): with self.subTest(typestr=typestr): @dataclass class C: x: typestr # x is not a ClassVar, so C() takes one arg. self.assertEqual(C(10).x, 10) def test_initvar(self): # These tests assume that both "import dataclasses" and "from # dataclasses import *" have been run in this file. for typestr in ('InitVar[int]', 'InitVar [int]' ' InitVar [int]', 'InitVar', ' InitVar ', 'dataclasses.InitVar[int]', 'dataclasses.InitVar[str]', ' dataclasses.InitVar[str]', 'dataclasses .InitVar[str]', 'dataclasses. InitVar[str]', 'dataclasses.InitVar [str]', 'dataclasses.InitVar [ str]', # Not syntactically valid, but these will # be treated as InitVars. 'dataclasses.InitVar.[int]', 'dataclasses.InitVar+', ): with self.subTest(typestr=typestr): @dataclass class C: x: typestr # x is an InitVar, so doesn't create a member. with self.assertRaisesRegex(AttributeError, "object has no attribute 'x'"): C(1).x def test_isnt_initvar(self): for typestr in ('IV', 'dc.InitVar', 'xdataclasses.xInitVar', 'typing.xInitVar[int]', ): with self.subTest(typestr=typestr): @dataclass class C: x: typestr # x is not an InitVar, so there will be a member x. self.assertEqual(C(10).x, 10) def test_classvar_module_level_import(self): from test.test_dataclasses import dataclass_module_1 from test.test_dataclasses import dataclass_module_1_str from test.test_dataclasses import dataclass_module_2 from test.test_dataclasses import dataclass_module_2_str for m in (dataclass_module_1, dataclass_module_1_str, dataclass_module_2, dataclass_module_2_str, ): with self.subTest(m=m): # There's a difference in how the ClassVars are # interpreted when using string annotations or # not. See the imported modules for details. if m.USING_STRINGS: c = m.CV(10) else: c = m.CV() self.assertEqual(c.cv0, 20) # There's a difference in how the InitVars are # interpreted when using string annotations or # not. See the imported modules for details. c = m.IV(0, 1, 2, 3, 4) for field_name in ('iv0', 'iv1', 'iv2', 'iv3'): with self.subTest(field_name=field_name): with self.assertRaisesRegex(AttributeError, f"object has no attribute '{field_name}'"): # Since field_name is an InitVar, it's # not an instance field. getattr(c, field_name) if m.USING_STRINGS: # iv4 is interpreted as a normal field. self.assertIn('not_iv4', c.__dict__) self.assertEqual(c.not_iv4, 4) else: # iv4 is interpreted as an InitVar, so it # won't exist on the instance. self.assertNotIn('not_iv4', c.__dict__) def test_text_annotations(self): from test.test_dataclasses import dataclass_textanno self.assertEqual( get_type_hints(dataclass_textanno.Bar), {'foo': dataclass_textanno.Foo}) self.assertEqual( get_type_hints(dataclass_textanno.Bar.__init__), {'foo': dataclass_textanno.Foo, 'return': type(None)}) ByMakeDataClass = make_dataclass('ByMakeDataClass', [('x', int)]) ManualModuleMakeDataClass = make_dataclass('ManualModuleMakeDataClass', [('x', int)], module=__name__) WrongNameMakeDataclass = make_dataclass('Wrong', [('x', int)]) WrongModuleMakeDataclass = make_dataclass('WrongModuleMakeDataclass', [('x', int)], module='custom') class TestMakeDataclass(unittest.TestCase): def test_simple(self): C = make_dataclass('C', [('x', int), ('y', int, field(default=5))], namespace={'add_one': lambda self: self.x + 1}) c = C(10) self.assertEqual((c.x, c.y), (10, 5)) self.assertEqual(c.add_one(), 11) def test_no_mutate_namespace(self): # Make sure a provided namespace isn't mutated. ns = {} C = make_dataclass('C', [('x', int), ('y', int, field(default=5))], namespace=ns) self.assertEqual(ns, {}) def test_base(self): class Base1: pass class Base2: pass C = make_dataclass('C', [('x', int)], bases=(Base1, Base2)) c = C(2) self.assertIsInstance(c, C) self.assertIsInstance(c, Base1) self.assertIsInstance(c, Base2) def test_base_dataclass(self): @dataclass class Base1: x: int class Base2: pass C = make_dataclass('C', [('y', int)], bases=(Base1, Base2)) with self.assertRaisesRegex(TypeError, 'required positional'): c = C(2) c = C(1, 2) self.assertIsInstance(c, C) self.assertIsInstance(c, Base1) self.assertIsInstance(c, Base2) self.assertEqual((c.x, c.y), (1, 2)) def test_init_var(self): def post_init(self, y): self.x *= y C = make_dataclass('C', [('x', int), ('y', InitVar[int]), ], namespace={'__post_init__': post_init}, ) c = C(2, 3) self.assertEqual(vars(c), {'x': 6}) self.assertEqual(len(fields(c)), 1) def test_class_var(self): C = make_dataclass('C', [('x', int), ('y', ClassVar[int], 10), ('z', ClassVar[int], field(default=20)), ]) c = C(1) self.assertEqual(vars(c), {'x': 1}) self.assertEqual(len(fields(c)), 1) self.assertEqual(C.y, 10) self.assertEqual(C.z, 20) def test_other_params(self): C = make_dataclass('C', [('x', int), ('y', ClassVar[int], 10), ('z', ClassVar[int], field(default=20)), ], init=False) # Make sure we have a repr, but no init. self.assertNotIn('__init__', vars(C)) self.assertIn('__repr__', vars(C)) # Make sure random other params don't work. with self.assertRaisesRegex(TypeError, 'unexpected keyword argument'): C = make_dataclass('C', [], xxinit=False) def test_no_types(self): C = make_dataclass('Point', ['x', 'y', 'z']) c = C(1, 2, 3) self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3}) self.assertEqual(C.__annotations__, {'x': typing.Any, 'y': typing.Any, 'z': typing.Any}) C = make_dataclass('Point', ['x', ('y', int), 'z']) c = C(1, 2, 3) self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3}) self.assertEqual(C.__annotations__, {'x': typing.Any, 'y': int, 'z': typing.Any}) def test_no_types_get_annotations(self): C = make_dataclass('C', ['x', ('y', int), 'z']) self.assertEqual( annotationlib.get_annotations(C, format=annotationlib.Format.VALUE), {'x': typing.Any, 'y': int, 'z': typing.Any}, ) self.assertEqual( annotationlib.get_annotations( C, format=annotationlib.Format.FORWARDREF), {'x': typing.Any, 'y': int, 'z': typing.Any}, ) self.assertEqual( annotationlib.get_annotations( C, format=annotationlib.Format.STRING), {'x': 'typing.Any', 'y': 'int', 'z': 'typing.Any'}, ) def test_no_types_no_typing_import(self): with import_helper.CleanImport('typing'): self.assertNotIn('typing', sys.modules) C = make_dataclass('C', ['x', ('y', int)]) self.assertNotIn('typing', sys.modules) self.assertEqual( C.__annotate__(annotationlib.Format.FORWARDREF), { 'x': annotationlib.ForwardRef('Any', module='typing'), 'y': int, }, ) self.assertNotIn('typing', sys.modules) for field in fields(C): if field.name == "x": self.assertEqual(field.type, annotationlib.ForwardRef('Any', module='typing')) else: self.assertEqual(field.name, "y") self.assertIs(field.type, int) def test_module_attr(self): self.assertEqual(ByMakeDataClass.__module__, __name__) self.assertEqual(ByMakeDataClass(1).__module__, __name__) self.assertEqual(WrongModuleMakeDataclass.__module__, "custom") Nested = make_dataclass('Nested', []) self.assertEqual(Nested.__module__, __name__) self.assertEqual(Nested().__module__, __name__) def test_pickle_support(self): for klass in [ByMakeDataClass, ManualModuleMakeDataClass]: for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(proto=proto): self.assertEqual( pickle.loads(pickle.dumps(klass, proto)), klass, ) self.assertEqual( pickle.loads(pickle.dumps(klass(1), proto)), klass(1), ) def test_cannot_be_pickled(self): for klass in [WrongNameMakeDataclass, WrongModuleMakeDataclass]: for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(proto=proto): with self.assertRaises(pickle.PickleError): pickle.dumps(klass, proto) with self.assertRaises(pickle.PickleError): pickle.dumps(klass(1), proto) def test_invalid_type_specification(self): for bad_field in [(), (1, 2, 3, 4), ]: with self.subTest(bad_field=bad_field): with self.assertRaisesRegex(TypeError, r'Invalid field: '): make_dataclass('C', ['a', bad_field]) # And test for things with no len(). for bad_field in [float, lambda x:x, ]: with self.subTest(bad_field=bad_field): with self.assertRaisesRegex(TypeError, r'has no len\(\)'): make_dataclass('C', ['a', bad_field]) def test_duplicate_field_names(self): for field in ['a', 'ab']: with self.subTest(field=field): with self.assertRaisesRegex(TypeError, 'Field name duplicated'): make_dataclass('C', [field, 'a', field]) def test_keyword_field_names(self): for field in ['for', 'async', 'await', 'as']: with self.subTest(field=field): with self.assertRaisesRegex(TypeError, 'must not be keywords'): make_dataclass('C', ['a', field]) with self.assertRaisesRegex(TypeError, 'must not be keywords'): make_dataclass('C', [field]) with self.assertRaisesRegex(TypeError, 'must not be keywords'): make_dataclass('C', [field, 'a']) def test_non_identifier_field_names(self): for field in ['()', 'x,y', '*', '2@3', '', 'little johnny tables']: with self.subTest(field=field): with self.assertRaisesRegex(TypeError, 'must be valid identifiers'): make_dataclass('C', ['a', field]) with self.assertRaisesRegex(TypeError, 'must be valid identifiers'): make_dataclass('C', [field]) with self.assertRaisesRegex(TypeError, 'must be valid identifiers'): make_dataclass('C', [field, 'a']) def test_underscore_field_names(self): # Unlike namedtuple, it's okay if dataclass field names have # an underscore. make_dataclass('C', ['_', '_a', 'a_a', 'a_']) def test_funny_class_names_names(self): # No reason to prevent weird class names, since # types.new_class allows them. for classname in ['()', 'x,y', '*', '2@3', '']: with self.subTest(classname=classname): C = make_dataclass(classname, ['a', 'b']) self.assertEqual(C.__name__, classname) def test_dataclass_decorator_default(self): C = make_dataclass('C', [('x', int)], decorator=dataclass) c = C(10) self.assertEqual(c.x, 10) def test_dataclass_custom_decorator(self): def custom_dataclass(cls, *args, **kwargs): dc = dataclass(cls, *args, **kwargs) dc.__custom__ = True return dc C = make_dataclass('C', [('x', int)], decorator=custom_dataclass) c = C(10) self.assertEqual(c.x, 10) self.assertEqual(c.__custom__, True) class TestReplace(unittest.TestCase): def test(self): @dataclass(frozen=True) class C: x: int y: int c = C(1, 2) c1 = replace(c, x=3) self.assertEqual(c1.x, 3) self.assertEqual(c1.y, 2) def test_frozen(self): @dataclass(frozen=True) class C: x: int y: int z: int = field(init=False, default=10) t: int = field(init=False, default=100) c = C(1, 2) c1 = replace(c, x=3) self.assertEqual((c.x, c.y, c.z, c.t), (1, 2, 10, 100)) self.assertEqual((c1.x, c1.y, c1.z, c1.t), (3, 2, 10, 100)) with self.assertRaisesRegex(TypeError, 'init=False'): replace(c, x=3, z=20, t=50) with self.assertRaisesRegex(TypeError, 'init=False'): replace(c, z=20) replace(c, x=3, z=20, t=50) # Make sure the result is still frozen. with self.assertRaisesRegex(FrozenInstanceError, "cannot assign to field 'x'"): c1.x = 3 # Make sure we can't replace an attribute that doesn't exist, # if we're also replacing one that does exist. Test this # here, because setting attributes on frozen instances is # handled slightly differently from non-frozen ones. with self.assertRaisesRegex(TypeError, r"__init__\(\) got an unexpected " "keyword argument 'a'"): c1 = replace(c, x=20, a=5) def test_invalid_field_name(self): @dataclass(frozen=True) class C: x: int y: int c = C(1, 2) with self.assertRaisesRegex(TypeError, r"__init__\(\) got an unexpected " "keyword argument 'z'"): c1 = replace(c, z=3) def test_invalid_object(self): @dataclass(frozen=True) class C: x: int y: int with self.assertRaisesRegex(TypeError, 'dataclass instance'): replace(C, x=3) with self.assertRaisesRegex(TypeError, 'dataclass instance'): replace(0, x=3) def test_no_init(self): @dataclass class C: x: int y: int = field(init=False, default=10) c = C(1) c.y = 20 # Make sure y gets the default value. c1 = replace(c, x=5) self.assertEqual((c1.x, c1.y), (5, 10)) # Trying to replace y is an error. with self.assertRaisesRegex(TypeError, 'init=False'): replace(c, x=2, y=30) with self.assertRaisesRegex(TypeError, 'init=False'): replace(c, y=30) def test_classvar(self): @dataclass class C: x: int y: ClassVar[int] = 1000 c = C(1) d = C(2) self.assertIs(c.y, d.y) self.assertEqual(c.y, 1000) # Trying to replace y is an error: can't replace ClassVars. with self.assertRaisesRegex(TypeError, r"__init__\(\) got an " "unexpected keyword argument 'y'"): replace(c, y=30) replace(c, x=5) def test_initvar_is_specified(self): @dataclass class C: x: int y: InitVar[int] def __post_init__(self, y): self.x *= y c = C(1, 10) self.assertEqual(c.x, 10) with self.assertRaisesRegex(TypeError, r"InitVar 'y' must be " r"specified with replace\(\)"): replace(c, x=3) c = replace(c, x=3, y=5) self.assertEqual(c.x, 15) def test_initvar_with_default_value(self): @dataclass class C: x: int y: InitVar[int] = None z: InitVar[int] = 42 def __post_init__(self, y, z): if y is not None: self.x += y if z is not None: self.x += z c = C(x=1, y=10, z=1) self.assertEqual(replace(c), C(x=12)) self.assertEqual(replace(c, y=4), C(x=12, y=4, z=42)) self.assertEqual(replace(c, y=4, z=1), C(x=12, y=4, z=1)) def test_recursive_repr(self): @dataclass class C: f: "C" c = C(None) c.f = c self.assertEqual(repr(c), "TestReplace.test_recursive_repr.<locals>.C(f=...)") def test_recursive_repr_two_attrs(self): @dataclass class C: f: "C" g: "C" c = C(None, None) c.f = c c.g = c self.assertEqual(repr(c), "TestReplace.test_recursive_repr_two_attrs" ".<locals>.C(f=..., g=...)") def test_recursive_repr_indirection(self): @dataclass class C: f: "D" @dataclass class D: f: "C" c = C(None) d = D(None) c.f = d d.f = c self.assertEqual(repr(c), "TestReplace.test_recursive_repr_indirection" ".<locals>.C(f=TestReplace.test_recursive_repr_indirection" ".<locals>.D(f=...))") def test_recursive_repr_indirection_two(self): @dataclass class C: f: "D" @dataclass class D: f: "E" @dataclass class E: f: "C" c = C(None) d = D(None) e = E(None) c.f = d d.f = e e.f = c self.assertEqual(repr(c), "TestReplace.test_recursive_repr_indirection_two" ".<locals>.C(f=TestReplace.test_recursive_repr_indirection_two" ".<locals>.D(f=TestReplace.test_recursive_repr_indirection_two" ".<locals>.E(f=...)))") def test_recursive_repr_misc_attrs(self): @dataclass class C: f: "C" g: int c = C(None, 1) c.f = c self.assertEqual(repr(c), "TestReplace.test_recursive_repr_misc_attrs" ".<locals>.C(f=..., g=1)") ## def test_initvar(self): ## @dataclass ## class C: ## x: int ## y: InitVar[int] ## c = C(1, 10) ## d = C(2, 20) ## # In our case, replacing an InitVar is a no-op ## self.assertEqual(c, replace(c, y=5)) ## replace(c, x=5) class TestAbstract(unittest.TestCase): def test_abc_implementation(self): class Ordered(abc.ABC): @abc.abstractmethod def __lt__(self, other): pass @abc.abstractmethod def __le__(self, other): pass @dataclass(order=True) class Date(Ordered): year: int month: 'Month' day: 'int' self.assertFalse(inspect.isabstract(Date)) self.assertGreater(Date(2020,12,25), Date(2020,8,31)) def test_maintain_abc(self): class A(abc.ABC): @abc.abstractmethod def foo(self): pass @dataclass class Date(A): year: int month: 'Month' day: 'int' self.assertTrue(inspect.isabstract(Date)) msg = "class Date without an implementation for abstract method 'foo'" self.assertRaisesRegex(TypeError, msg, Date) class TestMatchArgs(unittest.TestCase): def test_match_args(self): @dataclass class C: a: int self.assertEqual(C(42).__match_args__, ('a',)) def test_explicit_match_args(self): ma = () @dataclass class C: a: int __match_args__ = ma self.assertIs(C(42).__match_args__, ma) def test_bpo_43764(self): @dataclass(repr=False, eq=False, init=False) class X: a: int b: int c: int self.assertEqual(X.__match_args__, ("a", "b", "c")) def test_match_args_argument(self): @dataclass(match_args=False) class X: a: int self.assertNotIn('__match_args__', X.__dict__) @dataclass(match_args=False) class Y: a: int __match_args__ = ('b',) self.assertEqual(Y.__match_args__, ('b',)) @dataclass(match_args=False) class Z(Y): z: int self.assertEqual(Z.__match_args__, ('b',)) # Ensure parent dataclass __match_args__ is seen, if child class # specifies match_args=False. @dataclass class A: a: int z: int @dataclass(match_args=False) class B(A): b: int self.assertEqual(B.__match_args__, ('a', 'z')) def test_make_dataclasses(self): C = make_dataclass('C', [('x', int), ('y', int)]) self.assertEqual(C.__match_args__, ('x', 'y')) C = make_dataclass('C', [('x', int), ('y', int)], match_args=True) self.assertEqual(C.__match_args__, ('x', 'y')) C = make_dataclass('C', [('x', int), ('y', int)], match_args=False) self.assertNotIn('__match__args__', C.__dict__) C = make_dataclass('C', [('x', int), ('y', int)], namespace={'__match_args__': ('z',)}) self.assertEqual(C.__match_args__, ('z',)) class TestKeywordArgs(unittest.TestCase): def test_no_classvar_kwarg(self): msg = 'field a is a ClassVar but specifies kw_only' with self.assertRaisesRegex(TypeError, msg): @dataclass class A: a: ClassVar[int] = field(kw_only=True) with self.assertRaisesRegex(TypeError, msg): @dataclass class A: a: ClassVar[int] = field(kw_only=False) with self.assertRaisesRegex(TypeError, msg): @dataclass(kw_only=True) class A: a: ClassVar[int] = field(kw_only=False) def test_field_marked_as_kwonly(self): ####################### # Using dataclass(kw_only=True) @dataclass(kw_only=True) class A: a: int self.assertTrue(fields(A)[0].kw_only) @dataclass(kw_only=True) class A: a: int = field(kw_only=True) self.assertTrue(fields(A)[0].kw_only) @dataclass(kw_only=True) class A: a: int = field(kw_only=False) self.assertFalse(fields(A)[0].kw_only) ####################### # Using dataclass(kw_only=False) @dataclass(kw_only=False) class A: a: int self.assertFalse(fields(A)[0].kw_only) @dataclass(kw_only=False) class A: a: int = field(kw_only=True) self.assertTrue(fields(A)[0].kw_only) @dataclass(kw_only=False) class A: a: int = field(kw_only=False) self.assertFalse(fields(A)[0].kw_only) ####################### # Not specifying dataclass(kw_only) @dataclass class A: a: int self.assertFalse(fields(A)[0].kw_only) @dataclass class A: a: int = field(kw_only=True) self.assertTrue(fields(A)[0].kw_only) @dataclass class A: a: int = field(kw_only=False) self.assertFalse(fields(A)[0].kw_only) def test_match_args(self): # kw fields don't show up in __match_args__. @dataclass(kw_only=True) class C: a: int self.assertEqual(C(a=42).__match_args__, ()) @dataclass class C: a: int b: int = field(kw_only=True) self.assertEqual(C(42, b=10).__match_args__, ('a',)) def test_KW_ONLY(self): @dataclass class A: a: int _: KW_ONLY b: int c: int A(3, c=5, b=4) msg = "takes 2 positional arguments but 4 were given" with self.assertRaisesRegex(TypeError, msg): A(3, 4, 5) @dataclass(kw_only=True) class B: a: int _: KW_ONLY b: int c: int B(a=3, b=4, c=5) msg = "takes 1 positional argument but 4 were given" with self.assertRaisesRegex(TypeError, msg): B(3, 4, 5) # Explicitly make a field that follows KW_ONLY be non-keyword-only. @dataclass class C: a: int _: KW_ONLY b: int c: int = field(kw_only=False) c = C(1, 2, b=3) self.assertEqual(c.a, 1) self.assertEqual(c.b, 3) self.assertEqual(c.c, 2) c = C(1, b=3, c=2) self.assertEqual(c.a, 1) self.assertEqual(c.b, 3) self.assertEqual(c.c, 2) c = C(1, b=3, c=2) self.assertEqual(c.a, 1) self.assertEqual(c.b, 3) self.assertEqual(c.c, 2) c = C(c=2, b=3, a=1) self.assertEqual(c.a, 1) self.assertEqual(c.b, 3) self.assertEqual(c.c, 2) def test_KW_ONLY_as_string(self): @dataclass class A: a: int _: 'dataclasses.KW_ONLY' b: int c: int A(3, c=5, b=4) msg = "takes 2 positional arguments but 4 were given" with self.assertRaisesRegex(TypeError, msg): A(3, 4, 5) def test_KW_ONLY_twice(self): msg = "'Y' is KW_ONLY, but KW_ONLY has already been specified" with self.assertRaisesRegex(TypeError, msg): @dataclass class A: a: int X: KW_ONLY Y: KW_ONLY b: int c: int with self.assertRaisesRegex(TypeError, msg): @dataclass class A: a: int X: KW_ONLY b: int Y: KW_ONLY c: int with self.assertRaisesRegex(TypeError, msg): @dataclass class A: a: int X: KW_ONLY b: int c: int Y: KW_ONLY # But this usage is okay, since it's not using KW_ONLY. @dataclass class NoDuplicateKwOnlyAnnotation: a: int _: KW_ONLY b: int c: int = field(kw_only=True) # And if inheriting, it's okay. @dataclass class BaseUsesKwOnly: a: int _: KW_ONLY b: int c: int @dataclass class SubclassUsesKwOnly(BaseUsesKwOnly): _: KW_ONLY d: int # Make sure the error is raised in a derived class. with self.assertRaisesRegex(TypeError, msg): @dataclass class A: a: int _: KW_ONLY b: int c: int @dataclass class B(A): X: KW_ONLY d: int Y: KW_ONLY def test_post_init(self): @dataclass class A: a: int _: KW_ONLY b: InitVar[int] c: int d: InitVar[int] def __post_init__(self, b, d): raise CustomError(f'{b=} {d=}') with self.assertRaisesRegex(CustomError, 'b=3 d=4'): A(1, c=2, b=3, d=4) @dataclass class B: a: int _: KW_ONLY b: InitVar[int] c: int d: InitVar[int] def __post_init__(self, b, d): self.a = b self.c = d b = B(1, c=2, b=3, d=4) self.assertEqual(asdict(b), {'a': 3, 'c': 4}) def test_defaults(self): # For kwargs, make sure we can have defaults after non-defaults. @dataclass class A: a: int = 0 _: KW_ONLY b: int c: int = 1 d: int a = A(d=4, b=3) self.assertEqual(a.a, 0) self.assertEqual(a.b, 3) self.assertEqual(a.c, 1) self.assertEqual(a.d, 4) # Make sure we still check for non-kwarg non-defaults not following # defaults. err_regex = "non-default argument 'z' follows default argument 'a'" with self.assertRaisesRegex(TypeError, err_regex): @dataclass class A: a: int = 0 z: int _: KW_ONLY b: int c: int = 1 d: int def test_make_dataclass(self): A = make_dataclass("A", ['a'], kw_only=True) self.assertTrue(fields(A)[0].kw_only) B = make_dataclass("B", ['a', ('b', int, field(kw_only=False))], kw_only=True) self.assertTrue(fields(B)[0].kw_only) self.assertFalse(fields(B)[1].kw_only) def test_deferred_annotations(self): @dataclass class A: x: undefined y: ClassVar[undefined] fs = fields(A) self.assertEqual(len(fs), 1) self.assertEqual(fs[0].name, 'x') class TestZeroArgumentSuperWithSlots(unittest.TestCase): def test_zero_argument_super(self): @dataclass(slots=True) class A: def foo(self): super() A().foo() def test_dunder_class_with_old_property(self): @dataclass(slots=True) class A: def _get_foo(slf): self.assertIs(__class__, type(slf)) self.assertIs(__class__, slf.__class__) return __class__ def _set_foo(slf, value): self.assertIs(__class__, type(slf)) self.assertIs(__class__, slf.__class__) def _del_foo(slf): self.assertIs(__class__, type(slf)) self.assertIs(__class__, slf.__class__) foo = property(_get_foo, _set_foo, _del_foo) a = A() self.assertIs(a.foo, A) a.foo = 4 del a.foo def test_dunder_class_with_new_property(self): @dataclass(slots=True) class A: @property def foo(slf): return slf.__class__ @foo.setter def foo(slf, value): self.assertIs(__class__, type(slf)) @foo.deleter def foo(slf): self.assertIs(__class__, type(slf)) a = A() self.assertIs(a.foo, A) a.foo = 4 del a.foo # Test the parts of a property individually. def test_slots_dunder_class_property_getter(self): @dataclass(slots=True) class A: @property def foo(slf): return __class__ a = A() self.assertIs(a.foo, A) def test_slots_dunder_class_property_setter(self): @dataclass(slots=True) class A: foo = property() @foo.setter def foo(slf, val): self.assertIs(__class__, type(slf)) a = A() a.foo = 4 def test_slots_dunder_class_property_deleter(self): @dataclass(slots=True) class A: foo = property() @foo.deleter def foo(slf): self.assertIs(__class__, type(slf)) a = A() del a.foo def test_wrapped(self): def mydecorator(f): @wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) return wrapper @dataclass(slots=True) class A: @mydecorator def foo(self): super() A().foo() def test_remembered_class(self): # Apply the dataclass decorator manually (not when the class # is created), so that we can keep a reference to the # undecorated class. class A: def cls(self): return __class__ self.assertIs(A().cls(), A) B = dataclass(slots=True)(A) self.assertIs(B().cls(), B) # This is undesirable behavior, but is a function of how # modifying __class__ in the closure works. I'm not sure this # should be tested or not: I don't really want to guarantee # this behavior, but I don't want to lose the point that this # is how it works. # The underlying class is "broken" by changing its __class__ # in A.foo() to B. This normally isn't a problem, because no # one will be keeping a reference to the underlying class A. self.assertIs(A().cls(), B) if __name__ == '__main__': unittest.main()
python
github
https://github.com/python/cpython
Lib/test/test_dataclasses/__init__.py