function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
sequence
def grad(w, X, y, L, K): g,_ = getAvgGradient(w, X, y, L, K) return g
jihunhamm/Crowd-ML
[ 16, 10, 16, 5, 1463416723 ]
def setup_method(self, method): self.easy_data = pd.DataFrame({"A": np.random.randn(10), "B": np.random.randn(10), "C": np.random.randn(10), "datetime": pd.date_range('1/1/2019', periods=10)}) self.lookback = random.randint(1, 5)
intel-analytics/analytics-zoo
[ 2553, 722, 2553, 534, 1493951250 ]
def imports( self, interface: str, module_imports: dict[str, str]
flacjacket/pywayland
[ 64, 11, 64, 8, 1427851565 ]
def method_type(self) -> str: pass
flacjacket/pywayland
[ 64, 11, 64, 8, 1427851565 ]
def method_args(self) -> Iterable[str]: pass
flacjacket/pywayland
[ 64, 11, 64, 8, 1427851565 ]
def return_type(self) -> str: pass
flacjacket/pywayland
[ 64, 11, 64, 8, 1427851565 ]
def output_doc_params(self, printer: Printer) -> None: pass
flacjacket/pywayland
[ 64, 11, 64, 8, 1427851565 ]
def output_body(self, printer: Printer, opcode: int) -> None: pass
flacjacket/pywayland
[ 64, 11, 64, 8, 1427851565 ]
def test_i386(): p = angr.Project(os.path.join(test_location, 'i386', 'test_strcasecmp'), auto_load_libs=False) arg1 = claripy.BVS('arg1', 20*8) s = p.factory.entry_state(args=("test_strcasecmp", arg1)) sm = p.factory.simulation_manager(s) sm.explore() sm.move('deadended', 'found', filter_func=lambda s: b"Welcome" in s.posix.dumps(1)) assert len(sm.found) == 1 f = sm.found[0] sol = f.solver.eval(arg1, cast_to=bytes) assert b'\x00' in sol assert sol[:sol.index(b'\x00')].lower() == b'letmein' assert b'wchar works' in f.posix.dumps(1)
angr/angr
[ 6420, 966, 6420, 287, 1438897615 ]
def test_ui_gotopage_security_groups(self): print print "Started Test: GotoPage Security Groups" self.click_element_by_id("euca-logo") print print "Test: Received the Page Title -> " + self.driver.title self.click_element_by_id("dashboard-netsec-sgroup") print print "Test: Clicked the GoToPage Button" self.verify_element_by_id("table-sgroups-new") print print "Finished Test: GotoPage Security Groups" print return 0
eucalyptus/se34euca
[ 12, 13, 12, 18, 1352789276 ]
def test_ui_create_empty_security_group(self): print print "Started Test: Create Security Group" self.click_element_by_link_text("Dashboard") self.verify_element_by_link_text("Launch new instance") print print "Test: Go to the Page Security Group" self.click_element_by_css_selector("#dashboard-netsec-sgroup > span") self.click_element_by_id("table-sgroups-new") print print "Test: Create Security Group" self.set_keys_by_id("sgroup-name", "mywebservice") self.set_keys_by_id("sgroup-description", "test") self.click_element_by_id("sgroup-add-btn") print print "Finished: Create Security Group" print return 0
eucalyptus/se34euca
[ 12, 13, 12, 18, 1352789276 ]
def test_ui_delete_security_group(self): print print "Started Test: Delete Security Group" self.click_element_by_link_text("Dashboard") self.verify_element_by_link_text("Launch new instance") print print "Test: Go to the Page Security Group" self.click_element_by_css_selector("#dashboard-netsec-sgroup > span") self.verify_element_by_id("table-sgroups-new") self.click_element_by_css_selector("td.checkbox-cell.sorting_1 > input[type=\"checkbox\"]") self.click_element_by_id("more-actions-sgroups") print print "Test: Delete Security Group" self.click_element_by_link_text("Delete") self.click_element_by_id("btn-sgroups-delete-delete") print print "Finished: Delete Security Group" print return 0
eucalyptus/se34euca
[ 12, 13, 12, 18, 1352789276 ]
def test_ui_check_security_group_count(self, sg_count): print print "Started Test: Check Security Group Count" self.click_element_by_link_text("Dashboard") self.verify_element_by_link_text("Launch new instance") print "Verifying that Security Group Count on Dashboard is "+sg_count self.verify_text_displayed_by_css("#dashboard-netsec-sgroup > span",sg_count) print print "Finished Test: Check Security Group Count" print return 0
eucalyptus/se34euca
[ 12, 13, 12, 18, 1352789276 ]
def test_cromu_00070_caching(): # Test exploitation of CROMU_00070 given an input which causes a leak. Then test that we can do it again restoring # from the cache. for _ in range(2): payload = bytes.fromhex("06000006020a00000000000000000000000c030c00000100e1f505000000000000eb") cg = colorguard.ColorGuard(os.path.join(bin_location, "tests/cgc/CROMU_00070"), payload) pov = cg.attempt_exploit() nose.tools.assert_not_equal(pov, None) nose.tools.assert_true(pov.test_binary())
mechaphish/colorguard
[ 11, 11, 11, 1, 1471720164 ]
def setUp(self): self.set_filename('image51.xlsx')
jmcnamara/XlsxWriter
[ 3172, 594, 3172, 18, 1357261626 ]
def __init__(self, *args, **kwargs): super(Roles, self).__init__(*args, **kwargs) self.roles = [] self.policies = []
remind101/stacker_blueprints
[ 40, 52, 40, 16, 1449594934 ]
def create_ec2_role(self, name): return self.create_role(name, get_default_assumerole_policy())
remind101/stacker_blueprints
[ 40, 52, 40, 16, 1449594934 ]
def generate_policy_statements(self): """Should be overridden on a subclass to create policy statements. By subclassing this blueprint, and overriding this method to generate a list of :class:`awacs.aws.Statement` types, a :class:`troposphere.iam.PolicyType` will be created and attached to the roles specified here. If not specified, no Policy will be created. """ return []
remind101/stacker_blueprints
[ 40, 52, 40, 16, 1449594934 ]
def list(self, survey_id, **kwargs): kwargs.update({'survey_id': survey_id, }) return super(SurveyPage, self).list(**kwargs)
ITNG/SurveyGizmo
[ 16, 19, 16, 4, 1372462650 ]
def create(self, survey_id, title, **kwargs): kwargs.update({ 'survey_id': survey_id, 'title': title, }) return super(SurveyPage, self).create(**kwargs)
ITNG/SurveyGizmo
[ 16, 19, 16, 4, 1372462650 ]
def copy(self, **kwargs): raise NotImplementedError()
ITNG/SurveyGizmo
[ 16, 19, 16, 4, 1372462650 ]
def get_permission_decorator(): if getattr(settings, 'CENTAUR_PERMISSION_DECORATOR', None): module, decorator = settings.CENTAUR_PERMISSION_DECORATOR.rsplit('.', 1) return getattr(import_module(module), decorator) return user_passes_test(lambda u: u.is_superuser)
potatolondon/centaur
[ 2, 3, 2, 1, 1398151823 ]
def timestamp(datetime): """ Returns UTC timestamp, this is included in python3 but not 2""" return calendar.timegm(datetime.timetuple())
potatolondon/centaur
[ 2, 3, 2, 1, 1398151823 ]
def index(request): errors = Error.objects.all() # Filter by user email if request.GET.get('user', None): errors_pks = [e.error.pk for e in Event.objects.filter(logged_in_user_email=request.GET.get('user'))] errors = errors.filter(pk__in=errors_pks) errors = errors.order_by("-last_event") page = request.GET.get('page', 1) paginator = Paginator(errors, 20) try: errors = paginator.page(page) except PageNotAnInteger: errors = paginator.page(1) except EmptyPage: errors = paginator.page(paginator.num_pages) return render(request, "centaur/index.html", {"errors": errors})
potatolondon/centaur
[ 2, 3, 2, 1, 1398151823 ]
def error(request, error_id, limit=200): error = get_object_or_404(Error, pk=error_id) events = error.events.all().order_by("-created")[:limit] series = [ timestamp(event.created.replace(minute=0, second=0, microsecond=0)) for event in events ] page = request.GET.get('page', 1) paginator = Paginator(events, 1) try: events = paginator.page(page) except PageNotAnInteger: events = paginator.page(1) except EmptyPage: events = paginator.page(paginator.num_pages) return render(request, "centaur/error.html", { "error": error, "events": events, "series": series, })
potatolondon/centaur
[ 2, 3, 2, 1, 1398151823 ]
def clear_old_events(request): defer(_clear_old_events, _queue=CLEANUP_QUEUE) return HttpResponse("OK. Cleaning task deferred.")
potatolondon/centaur
[ 2, 3, 2, 1, 1398151823 ]
def _update_error_count(error_id, events_removed): @db.transactional(xg=True) def txn(): _error = Error.objects.get(pk=error_id) _error.event_count -= events_removed _error.save() txn()
potatolondon/centaur
[ 2, 3, 2, 1, 1398151823 ]
def add_arguments(self, parser): parser.add_argument('domain')
dimagi/commcare-hq
[ 465, 201, 465, 202, 1247158807 ]
def get_duplicate_users(domain): by_username = defaultdict(list) for user_id, username in get_all_user_id_username_pairs_by_domain(domain, include_web_users=False): by_username[username].append(user_id) dupes = {} for username, user_ids in by_username.items(): if len(user_ids) > 1: dupes[username] = user_ids return dupes
dimagi/commcare-hq
[ 465, 201, 465, 202, 1247158807 ]
def sharing_group_tuple(self, g): return ("sg__%s" % g['_id'], '%s [case sharing]' % g['name'])
dimagi/commcare-hq
[ 465, 201, 465, 202, 1247158807 ]
def static_options(self): options = super(CaseListFilterUtils, self).static_options # replace [Active Mobile Workers] and [Deactivated Mobile Workers] with case-list-specific options assert options[0][0] == "t__0" return [ ("all_data", _("[All Data]")), ('project_data', _("[Project Data]")) ] + options[1:]
dimagi/commcare-hq
[ 465, 201, 465, 202, 1247158807 ]
def utils(self): return CaseListFilterUtils(self.domain)
dimagi/commcare-hq
[ 465, 201, 465, 202, 1247158807 ]
def show_all_data(mobile_user_and_group_slugs): return 'all_data' in mobile_user_and_group_slugs
dimagi/commcare-hq
[ 465, 201, 465, 202, 1247158807 ]
def show_project_data(mobile_user_and_group_slugs): return 'project_data' in mobile_user_and_group_slugs
dimagi/commcare-hq
[ 465, 201, 465, 202, 1247158807 ]
def show_deactivated_data(mobile_user_and_group_slugs): from corehq.apps.reports.models import HQUserType return "t__{}".format(HQUserType.DEACTIVATED) in mobile_user_and_group_slugs
dimagi/commcare-hq
[ 465, 201, 465, 202, 1247158807 ]
def selected_sharing_group_ids(mobile_user_and_group_slugs): return [g[4:] for g in mobile_user_and_group_slugs if g.startswith("sg__")]
dimagi/commcare-hq
[ 465, 201, 465, 202, 1247158807 ]
def selected_group_ids(cls, mobile_user_and_group_slugs): return (super(CaseListFilter, cls).selected_group_ids(mobile_user_and_group_slugs) + cls.selected_sharing_group_ids(mobile_user_and_group_slugs))
dimagi/commcare-hq
[ 465, 201, 465, 202, 1247158807 ]
def test_init(self): f = Field("test", b"\x01\x23", slice(10, 12), "std") self.assertEqual(f.name, "test") self.assertEqual(f.size, slice(10, 12, 1)) self.assertEqual(f.default, Value(b"\x01\x23", 10)) self.assertEqual(f.fuzz, "std")
ernw/dizzy
[ 62, 10, 62, 1, 1529939719 ]
def test_add_unaligned(self): pass
ernw/dizzy
[ 62, 10, 62, 1, 1529939719 ]
def test_iter(self): expected = [Value(b'\x01#', 10), Value(b'\x00\x00', 10), Value(b'\x00\x01', 10), Value(b'\x00\x02', 10), Value(b'\x00\x03', 10), Value(b'\x00\x04', 10), Value(b'\x03\xfb', 10), Value(b'\x03\xfc', 10), Value(b'\x03\xfd', 10), Value(b'\x03\xfe', 10), Value(b'\x03\xff', 10), Value(b'\x01\xfc', 10), Value(b'\x01\xfd', 10), Value(b'\x01\xfe', 10), Value(b'\x01\xff', 10), Value(b'\x01\x00', 10), Value(b'\x02\x00', 10), Value(b'\x03\x00', 10), Value(b'\x04\x00', 10)] f = Field("test", b"\x01\x23", 10, "std") self.assertEqual([i for i in f], expected)
ernw/dizzy
[ 62, 10, 62, 1, 1529939719 ]
def test_size(self): f = Field("test", b"\x01\x23", 10, "std") self.assertEqual(f.length(), 19) self.assertEqual(len(list(f)), f.length())
ernw/dizzy
[ 62, 10, 62, 1, 1529939719 ]
def __init__(self, pos, char, name, color, blocks=False, always_visible=False, fighter=None, ai=None, item=None, equipment=None): self.pos = pos self.char = char self.name = name self.color = color self.blocks = blocks self.always_visible = always_visible self.fighter = fighter self._ensure_ownership(fighter) self.ai = ai self._ensure_ownership(ai) self.item = item self._ensure_ownership(item) self.equipment = equipment self._ensure_ownership(equipment)
Naburimannu/libtcodpy-tutorial
[ 11, 3, 11, 2, 1454382865 ]
def x(self): return self.pos.x
Naburimannu/libtcodpy-tutorial
[ 11, 3, 11, 2, 1454382865 ]
def y(self): return self.pos.y
Naburimannu/libtcodpy-tutorial
[ 11, 3, 11, 2, 1454382865 ]
def distance_to(self, other): """ Return the distance to another object. """ dx = other.x - self.x dy = other.y - self.y return math.sqrt(dx ** 2 + dy ** 2)
Naburimannu/libtcodpy-tutorial
[ 11, 3, 11, 2, 1454382865 ]
def distance(self, pos): """ Return the distance to some coordinates. """ return math.sqrt((pos.x - self.x) ** 2 + (pos.y - self.y) ** 2)
Naburimannu/libtcodpy-tutorial
[ 11, 3, 11, 2, 1454382865 ]
def set_owner(self, entity): self.owner = entity
Naburimannu/libtcodpy-tutorial
[ 11, 3, 11, 2, 1454382865 ]
def __init__(self, hp, defense, power, xp, death_function=None): self.base_max_hp = hp self.hp = hp self.base_defense = defense self.base_power = power self.xp = xp self.death_function = death_function
Naburimannu/libtcodpy-tutorial
[ 11, 3, 11, 2, 1454382865 ]
def power(self): bonus = sum(equipment.power_bonus for equipment in _get_all_equipped(self.owner)) return self.base_power + bonus
Naburimannu/libtcodpy-tutorial
[ 11, 3, 11, 2, 1454382865 ]
def defense(self): bonus = sum(equipment.defense_bonus for equipment in _get_all_equipped(self.owner)) return self.base_defense + bonus
Naburimannu/libtcodpy-tutorial
[ 11, 3, 11, 2, 1454382865 ]
def max_hp(self): bonus = sum(equipment.max_hp_bonus for equipment in _get_all_equipped(self.owner)) return self.base_max_hp + bonus
Naburimannu/libtcodpy-tutorial
[ 11, 3, 11, 2, 1454382865 ]
def __init__(self, description=None, count=1, use_function=None): self.description = description self.use_function = use_function self.count = count
Naburimannu/libtcodpy-tutorial
[ 11, 3, 11, 2, 1454382865 ]
def __init__(self, slot, power_bonus=0, defense_bonus=0, max_hp_bonus=0): self.power_bonus = power_bonus self.defense_bonus = defense_bonus self.max_hp_bonus = max_hp_bonus self.slot = slot self.is_equipped = False
Naburimannu/libtcodpy-tutorial
[ 11, 3, 11, 2, 1454382865 ]
def __init__(self, take_turn, metadata=None): self._turn_function = take_turn self._metadata = metadata
Naburimannu/libtcodpy-tutorial
[ 11, 3, 11, 2, 1454382865 ]
def create_jobs(api_type): api = api_select.api(__file__, api_type) api.flow_job() api.job('passwd_args', exec_time=0.5, max_fails=0, expect_invocations=1, expect_order=1, params=(('s1', 'no-secret', 'desc'), ('passwd', 'p2', 'desc'), ('PASS', 'p3', 'desc'))) return api
lhupfeldt/jenkinsflow
[ 13, 5, 13, 3, 1355357553 ]
def __init__(self, temperature=None, duration=None, start=True): self.state = self.STATE_SETUP self.sensor = W1ThermSensor() self.end_time = None self._setup_gpio() self._set_target_temperature(temperature) self._set_duration(duration) self.display_initial_info() if start: self.start()
bennuttall/chef-hat
[ 2, 1, 2, 1, 1424026705 ]
def _setup_gpio(self): """ Setup the GPIO pins used in the Chef HAT (input buttons and status LED) and create an event on the back button to terminate the process. """ GPIO.setup(self.LED, GPIO.OUT) self.turn_led_off() for button in self.BUTTONS: GPIO.setup(button, GPIO.IN, self.PULL) self.remove_button_event(button) self.add_button_event(self.BUTTON_BACK, self.terminate)
bennuttall/chef-hat
[ 2, 1, 2, 1, 1424026705 ]
def write(self, text, line=1): """ Prints `text` TODO: writes to the LCD """ print(text)
bennuttall/chef-hat
[ 2, 1, 2, 1, 1424026705 ]
def turn_led_off(self): """ Turns the status LED off """ GPIO.output(self.LED, False)
bennuttall/chef-hat
[ 2, 1, 2, 1, 1424026705 ]
def turn_cooker_off(self): """ Uses energenie to switch the cooker off. Also turns off the status LED. """ energenie.switch_off() self.turn_led_off()
bennuttall/chef-hat
[ 2, 1, 2, 1, 1424026705 ]
def remove_button_event(self, button): """ Removes a GPIO event for a particular button. """ GPIO.remove_event_detect(button)
bennuttall/chef-hat
[ 2, 1, 2, 1, 1424026705 ]
def _setup_up_down_buttons(self, increase_function, decrease_function): """ Configures the *up* and *down* buttons on the Chef HAT to run particular increase and decrease functions accordingly. When the *enter* button is pressed removes the up/down button events and continues. """ self.add_button_event(self.BUTTON_UP, increase_function) self.add_button_event(self.BUTTON_DOWN, decrease_function) self._wait_for_button_press(self.BUTTON_ENTER) self.remove_button_event(self.BUTTON_UP) self.remove_button_event(self.BUTTON_DOWN)
bennuttall/chef-hat
[ 2, 1, 2, 1, 1424026705 ]
def _set_duration(self, duration): """ Sets the object's `duration` property. If `duration` is passed, sets it to the *int* of that value, otherwise sets it to its configured default value and provides the means to change the value using the up/down buttons and the LCD. """ if duration is not None: self.duration = int(duration) else: self.duration = int(self.DEFAULT_DURATION) self.write("Set") self.write("timer", 2) sleep(1) self.write("Timer:") self.write("%2d mins" % self.duration, 2) self._setup_up_down_buttons( self.increase_duration, self.decrease_duration )
bennuttall/chef-hat
[ 2, 1, 2, 1, 1424026705 ]
def increase_target_temperature(self, pin): """ Increases the target temperature by the temperature increment and displays the new value on the LCD. """ self.target_temperature += self.TEMPERATURE_INCREMENT self.write("Temp:") self.write("%7dC" % self.target_temperature, 2)
bennuttall/chef-hat
[ 2, 1, 2, 1, 1424026705 ]
def increase_duration(self, pin): """ Increases the duration by the duration increment and displays the new value on the LCD. """ self.duration += self.DURATION_INCREMENT self.write("Timer:") self.write("%3d mins" % self.duration, 2)
bennuttall/chef-hat
[ 2, 1, 2, 1, 1424026705 ]
def update_status_to_ready(self): """ Updates the object state to *ready* and adds a button press event for the user to proceed to the *food in* state. """ self.state = self.STATE_READY self.add_button_event(self.BUTTON_ENTER, self.update_status_to_food_in) self.write("Add food and press enter to continue")
bennuttall/chef-hat
[ 2, 1, 2, 1, 1424026705 ]
def update_status_to_cooking(self): """ Updates the object state to *cooking* and sets the timer according to the object's `duration` property, relative to the current time. """ self.state = self.STATE_COOKING self.write("Cooking") current_time = datetime.now() print(current_time) self.end_time = current_time + timedelta(minutes=self.duration) print(self.end_time)
bennuttall/chef-hat
[ 2, 1, 2, 1, 1424026705 ]
def update_status_to_finished(self, pin): """ Updates the object state to *finished*. """ self.state = self.STATE_FINISHED self.write("Finished")
bennuttall/chef-hat
[ 2, 1, 2, 1, 1424026705 ]
def moderate_temperature(self, temperature): """ Moderates the temperature of the cooker. Switches it off if the temperature is too high, and switches it off if it's too low, relative to the object's `target_temperature` property. Also writes out the on or off action and the temperature value. """ if temperature < self.target_temperature: self.turn_cooker_on() self.write("%.2f on" % temperature) else: self.turn_cooker_off() self.write("%.2f off" % temperature)
bennuttall/chef-hat
[ 2, 1, 2, 1, 1424026705 ]
def show_remaining_time(self): """ Prints the amount of cooking time remaining. If under 1 minute, shown in seconds, otherwise shown in minutes. """ current_time = datetime.now() time_left = self.end_time - current_time seconds_left = time_left.seconds minutes_left = seconds_left // 60 if minutes_left > 0: min_or_mins = 'min' if minutes_left == 1 else 'mins' print("%s %s left" % (minutes_left, min_or_mins)) else: sec or secs = 'sec' if seconds_left == 1 else 'secs' print("%s %s left" % (seconds_left, sec or secs))
bennuttall/chef-hat
[ 2, 1, 2, 1, 1424026705 ]
def get_default_country(self): """Get the default country based on geoip data. """ if not geoip or not request.remote_addr: return None Country = Pool().get('country.country') try: current_app.logger.debug( "GeoIP lookup for remote address: %s" % request.remote_addr ) country, = Country.search([ ('code', '=', geoip.country_code_by_addr(request.remote_addr)) ]) except ValueError: return None return country
fulfilio/nereid-webshop
[ 3, 12, 3, 1, 1439289405 ]
def RunGit(self, _git_repo, cmd, _retry=True, **kwargs): return self._results['RunGit'].LookupResult( (cmd,), hook_args=(cmd,), hook_kwargs=kwargs)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def setUp(self): self._branch = 'test_branch' self._target_manifest_branch = 'cros/master'
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testPushChange(self): """Verify pushing changes works.""" self._TestPushChange(bad_cls=False)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def __init__(self, path, new_package=True): self.path = path self.package = '%s_package' % path self.cros_workon_vars = 'cros_workon_vars' self._new_package = new_package
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def RevWorkOnEBuild(self, srcroot, manifest): if self._new_package: return ('%s_new_package' % self.path, '%s_new_ebuild' % self.path, '%s_old_ebuild' % self.path)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def setUp(self): self._manifest = 'manifest' self._parser = cros_mark_as_stable.GetParser() self._package_list = ['pkg1'] self._overlays = [os.path.join(self.tempdir, 'overlay_%s' % i) for i in range(0, 3)] self._overlay_remote_ref = { self._overlays[0]: git.RemoteRef('remote', 'ref', 'project_1'), self._overlays[1]: git.RemoteRef('remote', 'ref', 'project_1'), self._overlays[2]: git.RemoteRef('remote', 'ref', 'project_2'), } self._git_project_overlays = {} self._overlay_tracking_branch = {} for overlay in self._overlays: self._git_project_overlays.setdefault( self._overlay_remote_ref[overlay], []).append(overlay) self._overlay_tracking_branch[overlay] = ( self._overlay_remote_ref[overlay].ref) self.PatchObject(git, 'GetTrackingBranchViaManifest') # TODO: Remove explicit --buildroot after --srcroot remove and a normal # default is set. self._commit_options = self._parser.parse_args( ['commit', '--buildroot', constants.SOURCE_ROOT]) self._push_options = self._parser.parse_args( ['push', '--buildroot', constants.SOURCE_ROOT])
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testPushOverlays(self): """Test _PushOverlays.""" self.PatchObject(os.path, 'isdir', return_value=True) mock_push_change = self.PatchObject(cros_mark_as_stable, 'PushChange') cros_mark_as_stable._PushOverlays( self._push_options, self._overlays, self._overlay_tracking_branch) self.assertEqual(mock_push_change.call_count, 3)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testGetOverlayToEbuildsMap(self): """Test _GetOverlayToEbuildsMap.""" self.PatchObject(portage_util, 'GetOverlayEBuilds', return_value=['ebuild']) expected_overlay_dicts = { overlay : ['ebuild'] for overlay in self._overlays} overlay_ebuilds = cros_mark_as_stable._GetOverlayToEbuildsMap( self._commit_options, self._overlays, self._package_list) self.assertCountEqual(expected_overlay_dicts, overlay_ebuilds)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testWorkOnEbuildWithNewPackage(self): """Test _WorkOnEbuild with new packages.""" overlay = self._overlays[0] ebuild = EbuildMock('ebuild') with parallel.Manager() as manager: revved_packages = manager.list() new_package_atoms = manager.list() messages = manager.list() ebuild_paths_to_add = manager.list() ebuild_paths_to_remove = manager.list() cros_mark_as_stable._WorkOnEbuild( overlay, ebuild, self._manifest, self._commit_options, ebuild_paths_to_add, ebuild_paths_to_remove, messages, revved_packages, new_package_atoms) self.assertCountEqual(ebuild_paths_to_add, ['ebuild_new_ebuild']) self.assertCountEqual(ebuild_paths_to_remove, ['ebuild_old_ebuild']) self.assertCountEqual(messages, [cros_mark_as_stable._GIT_COMMIT_MESSAGE % 'ebuild_package']) self.assertCountEqual(revved_packages, ['ebuild_package']) self.assertCountEqual(new_package_atoms, ['=ebuild_new_package'])
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def setUp(self): self.PatchObject(git.ManifestCheckout, 'Cached', return_value='manifest') self.mock_work_on_push = self.PatchObject( cros_mark_as_stable, '_WorkOnPush') self.mock_work_on_commit = self.PatchObject( cros_mark_as_stable, '_WorkOnCommit') self._overlays = [] remote_refs = [] self._overlay_tracking_branch = {} self._git_project_overlays = {} for i in range(0, 3): overlay = os.path.join(self.tempdir, 'overlay_%s' % i) osutils.SafeMakedirs(overlay) self._overlays.append(overlay) remote_ref = git.RemoteRef('remote', 'ref', 'project_%s' % i) remote_refs.append(remote_ref) self._overlay_tracking_branch[overlay] = remote_ref.ref self._git_project_overlays[remote_ref.project_name] = [overlay] self.PatchObject(portage_util, 'FindOverlays', return_value=self._overlays) self.PatchObject(git, 'GetTrackingBranchViaManifest', side_effect=remote_refs)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testMainWithPush(self): """Test Main with Push options.""" cros_mark_as_stable.main( ['push', '--all', '--overlays', ':'.join(self._overlays)]) self.mock_work_on_push.assert_called_once_with( mock.ANY, self._overlay_tracking_branch, self._git_project_overlays) options = self.mock_work_on_push.call_args[0][0] self.assertEqual(options.buildroot, constants.SOURCE_ROOT) self.assertIsNone(options.srcroot)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testMainWithBuildroot(self): """Test Main with Commit options.""" self.PatchObject(os.path, 'isdir', side_effect=lambda p: p == '/buildroot') cros_mark_as_stable.main( ['commit', '--all', '--overlay-type', 'both', '--buildroot', '/buildroot']) options = self.mock_work_on_commit.call_args[0][0] self.assertEqual(options.buildroot, '/buildroot') self.assertIsNone(options.srcroot)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def setUp(self): self.PatchObject(osutils, 'FindMissingBinaries', return_value=[])
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testNothingToUnmerge(self): """Clean up packages that don't exist (portage will exit 1)""" self.rc.AddCmdResult(partial_mock.In('emerge'), returncode=1) cros_mark_as_stable.CleanStalePackages('.', (), ['no/pkg'])
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def setUp(self): # Always stub RunCommmand out as we use it in every method. self.git_mock = self.PatchObject(git, 'RunGit') self.start_mock = self.PatchObject(repo_util.Repository, 'StartBranch') self._branch_name = 'test_branch' self._target_manifest_branch = 'cros/test' self._branch = cros_mark_as_stable.GitBranch( branch_name=self._branch_name, tracking_branch=self._target_manifest_branch, cwd='.')
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testCheckoutNoCreate(self): """Test init with previous branch existing.""" self.PatchObject(self._branch, 'Exists', return_value=True) cros_mark_as_stable.GitBranch.Checkout(self._branch) self.git_mock.assert_called_with('.', ['checkout', '-f', self._branch_name], quiet=True)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def list_models(kind=None): # type: (str) -> List[str] """ Return the list of available models on the model path. *kind* can be one of the following: * all: all models * py: python models only * c: c models only * single: c models which support single precision * double: c models which require double precision * opencl: c models which run in opencl * dll: c models which do not run in opencl * 1d: models without orientation * 2d: models with orientation * magnetic: models supporting magnetic sld * nommagnetic: models without magnetic parameter For multiple conditions, combine with plus. For example, *c+single+2d* would return all oriented models implemented in C which can be computed accurately with single precision arithmetic. """ if kind and any(k not in KINDS for k in kind.split('+')): raise ValueError("kind not in " + ", ".join(KINDS)) files = sorted(glob(joinpath(generate.MODEL_PATH, "[a-zA-Z]*.py"))) available_models = [basename(f)[:-3] for f in files] if kind and '+' in kind: all_kinds = kind.split('+') condition = lambda name: all(_matches(name, k) for k in all_kinds) else: condition = lambda name: _matches(name, kind) selected = [name for name in available_models if condition(name)] return selected
SasView/sasmodels
[ 13, 25, 13, 185, 1423839860 ]
def load_model(model_name, dtype=None, platform='ocl'): # type: (str, str, str) -> KernelModel """ Load model info and build model. *model_name* is the name of the model, or perhaps a model expression such as sphere*hardsphere or sphere+cylinder. *dtype* and *platform* are given by :func:`build_model`. """ return build_model(load_model_info(model_name), dtype=dtype, platform=platform)
SasView/sasmodels
[ 13, 25, 13, 185, 1423839860 ]
def reparameterize( base, parameters, translation, filename=None, title=None, insert_after=None, docs=None, name=None, source=None, ): """ Reparameterize an existing model. *base* is the original modelinfo. This cannot be a reparameterized model; only one level of reparameterization is supported. *parameters* are the new parameter definitions that will be included in the model info. *translation* is a string each line containing *var = expr*. The variable *var* can be a new intermediate value, or it can be a parameter from the base model that will be replace by the expression. The expression *expr* can be any C99 expression, including C-style if-expressions *condition ? value1 : value2*. Expressions can use any new or existing parameter that is not being replaced including intermediate values that are previously defined. Parameters can only be assigned once, never updated. C99 math functions are available, as well as any functions defined in the base model or included in *source* (see below). *filename* is the filename for the replacement model. This is usually *__file__*, giving the path to the model file, but it could also be a nominal filename for translations defined on-the-fly. *title* is the model title, which defaults to *base.title* plus " (reparameterized)". *insert_after* controls parameter placement. By default, the new parameters replace the old parameters in their original position. Instead, you can provide a dictionary *{'par': 'newpar1,newpar2'}* indicating that new parameters named *newpar1* and *newpar2* should be included in the table after the existing parameter *par*, or at the beginning if *par* is the empty string. *docs* constains the doc string for the translated model, which by default references the base model and gives the *translation* text. *name* is the model name (default = :code:`"constrained_" + base.name`). *source* is a list any additional C source files that should be included to define functions and constants used in the translation expressions. This will be included after all sources for the base model. Sources will only be included once, even if they are listed in both places, so feel free to list all dependencies for the helper function, such as "lib/polevl.c". """ if not isinstance(base, modelinfo.ModelInfo): base = load_model_info(base) if name is None: name = filename if filename is not None else "constrained_" + base.name name = os.path.basename(name).split('.')[0] if title is None: title = base.title + " (reparameterized)" if docs is None: lines = "\n ".join(s.lstrip() for s in translation.split('\n')) docs = _REPARAMETERIZE_DOCS%{'base': base.id, 'translation': lines} #source = merge_deps(base.source, source) source = (base.source + [f for f in source if f not in base.source] if source else base.source) # TODO: don't repeat code from generate._build_translation base_pars = [par.id for par in base.parameters.kernel_parameters] old_pars = [match.group(1) for match in _LHS_RE.finditer(translation) if match.group(1) in base_pars] new_pars = [modelinfo.parse_parameter(*p) for p in parameters] table = modelinfo.derive_table(base.parameters, remove=old_pars, insert=new_pars, insert_after=insert_after) caller = copy.copy(base) caller.translation = translation caller.name = caller.id = name caller.docs = docs caller.filename = filename caller.parameters = table caller.source = source return caller
SasView/sasmodels
[ 13, 25, 13, 185, 1423839860 ]
def merge_deps(old, new): """ Merge two dependency lists. The lists are partially ordered, with all dependents coming after the items they depend on, but otherwise order doesn't matter. The merged list preserves the partial ordering. So if old and new both include the item "c", then all items that come before "c" in old and new will come before "c" in the result, and all items that come after "c" in old and new will come after "c" in the result. """ if new is None: return old result = [] for item in new: try: index = old.index(item) #print(item,"found in",old,"at",index,"giving",old[:index]) result.extend(old[:index]) old = old[index+1:] except ValueError: #print(item, "not found in", old) pass result.append(item) #print("after", item, "old", old, "result", result) result.extend(old) return result
SasView/sasmodels
[ 13, 25, 13, 185, 1423839860 ]
def precompile_dlls(path, dtype="double"): # type: (str, str) -> List[str] """ Precompile the dlls for all builtin models, returning a list of dll paths. *path* is the directory in which to save the dlls. It will be created if it does not already exist. This can be used when build the windows distribution of sasmodels which may be missing the OpenCL driver and the dll compiler. """ from . import kerneldll numpy_dtype = np.dtype(dtype) if not os.path.exists(path): os.makedirs(path) compiled_dlls = [] for model_name in list_models(): model_info = load_model_info(model_name) if not callable(model_info.Iq): source = generate.make_source(model_info)['dll'] old_path = kerneldll.SAS_DLL_PATH try: kerneldll.SAS_DLL_PATH = path dll = kerneldll.make_dll(source, model_info, dtype=numpy_dtype) finally: kerneldll.SAS_DLL_PATH = old_path compiled_dlls.append(dll) return compiled_dlls
SasView/sasmodels
[ 13, 25, 13, 185, 1423839860 ]
def test_composite_order(): """ Check that mixture models produce the same result independent of ordder. """ def test_models(fst, snd): """Confirm that two models produce the same parameters""" fst = load_model(fst) snd = load_model(snd) # Un-disambiguate parameter names so that we can check if the same # parameters are in a pair of composite models. Since each parameter in # the mixture model is tagged as e.g., A_sld, we ought to use a # regex subsitution s/^[A-Z]+_/_/, but removing all uppercase letters # is good enough. # TODO: check that the models produce the same results # Note that compare.py will give a misleading answer. For # "cylinder+sphere" the A_radius parameter will use the default # cylinder radius, but for "sphere+cylinder" it will use the default # sphere radius so a simple comparison of the two will appear to be # different unless you explicitly set radius, solvent, and solvent_sld # for the A and B models. fst = [[x for x in p.name if x == x.lower()] for p in fst.info.parameters.kernel_parameters] snd = [[x for x in p.name if x == x.lower()] for p in snd.info.parameters.kernel_parameters] assert sorted(fst) == sorted(snd), "{} != {}".format(fst, snd) test_models( "cylinder+sphere", "sphere+cylinder") test_models( "cylinder*sphere", "sphere*cylinder") test_models( "cylinder@hardsphere*sphere", "sphere*cylinder@hardsphere") test_models( "barbell+sphere*cylinder@hardsphere", "sphere*cylinder@hardsphere+barbell") test_models( "barbell+cylinder@hardsphere*sphere", "cylinder@hardsphere*sphere+barbell") test_models( "barbell+sphere*cylinder@hardsphere", "barbell+cylinder@hardsphere*sphere") test_models( "sphere*cylinder@hardsphere+barbell", "cylinder@hardsphere*sphere+barbell") test_models( "barbell+sphere*cylinder@hardsphere", "cylinder@hardsphere*sphere+barbell") test_models( "barbell+cylinder@hardsphere*sphere", "sphere*cylinder@hardsphere+barbell")
SasView/sasmodels
[ 13, 25, 13, 185, 1423839860 ]
def list_models_main(): # type: () -> int """ Run list_models as a main program. See :func:`list_models` for the kinds of models that can be requested on the command line. """ import sys kind = sys.argv[1] if len(sys.argv) > 1 else "all" try: models = list_models(kind) print("\n".join(models)) except Exception: print(list_models.__doc__) return 1 return 0
SasView/sasmodels
[ 13, 25, 13, 185, 1423839860 ]
def setUp(self): self.username = 'theskumar' self.email = '[email protected]'
theskumar/django-unsubscribe
[ 24, 11, 24, 4, 1392272801 ]
def setUp(self): pass
UCSBarchlab/PyRTL
[ 184, 70, 184, 23, 1393210686 ]
def test_output_list_type(self): outputs = pyrtl.helperfuncs.output_list('one, two, three') self.assertTrue(all(isinstance(outp, pyrtl.Output) for outp in outputs))
UCSBarchlab/PyRTL
[ 184, 70, 184, 23, 1393210686 ]
def test_wirevector_list_type(self): # Single string of names wirevectors = pyrtl.helperfuncs.wirevector_list('one, two, three') self.assertTrue(all(isinstance(wire, pyrtl.WireVector) for wire in wirevectors)) self.assertListEqual([wire.bitwidth for wire in wirevectors], [1, 1, 1]) # List of names wirevectors = pyrtl.helperfuncs.wirevector_list('one, two, three') self.assertTrue(all(isinstance(wire, pyrtl.WireVector) for wire in wirevectors)) self.assertListEqual([wire.bitwidth for wire in wirevectors], [1, 1, 1])
UCSBarchlab/PyRTL
[ 184, 70, 184, 23, 1393210686 ]
def test_wirevector_list_per_wire_width(self): wirevectors = pyrtl.helperfuncs.wirevector_list('one/2, two/4, three/8') self.assertListEqual([wire.bitwidth for wire in wirevectors], [2, 4, 8]) wirevectors = pyrtl.helperfuncs.wirevector_list(['one', 'two', 'three'], [2, 4, 8]) self.assertListEqual([wire.bitwidth for wire in wirevectors], [2, 4, 8])
UCSBarchlab/PyRTL
[ 184, 70, 184, 23, 1393210686 ]
def setUp(self): pass
UCSBarchlab/PyRTL
[ 184, 70, 184, 23, 1393210686 ]