code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class Analysis_class_test(AnalysisTestCase): <NEW_LINE> <INDENT> def test_regional_boxplot(self): <NEW_LINE> <INDENT> self.assertTrue('boxplot_' + str(self.test_analysis.year) in self.files) <NEW_LINE> self.assertEqual(len(self.boxplotresults['boxes']), 6) <NEW_LINE> <DEDENT> def test_regional_distributions(self): <NEW_LINE> <INDENT> self.assertTrue('regional_distributions_' + str(self.test_analysis.year) in self.files) | Verifies that create_regional_boxplot and create_regional_distributions successfully create files | 625990883617ad0b5ee07d0e |
class ExpressRouteServiceProvider(Resource): <NEW_LINE> <INDENT> _validation = { 'name': {'readonly': True}, 'type': {'readonly': True}, 'provisioning_state': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'peering_locations': {'key': 'properties.peeringLocations', 'type': '[str]'}, 'bandwidths_offered': {'key': 'properties.bandwidthsOffered', 'type': '[ExpressRouteServiceProviderBandwidthsOffered]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, id: Optional[str] = None, location: Optional[str] = None, tags: Optional[Dict[str, str]] = None, peering_locations: Optional[List[str]] = None, bandwidths_offered: Optional[List["ExpressRouteServiceProviderBandwidthsOffered"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(ExpressRouteServiceProvider, self).__init__(id=id, location=location, tags=tags, **kwargs) <NEW_LINE> self.peering_locations = peering_locations <NEW_LINE> self.bandwidths_offered = bandwidths_offered <NEW_LINE> self.provisioning_state = None | A ExpressRouteResourceProvider object.
Variables are only populated by the server, and will be ignored when sending a request.
:param id: Resource ID.
:type id: str
:ivar name: Resource name.
:vartype name: str
:ivar type: Resource type.
:vartype type: str
:param location: Resource location.
:type location: str
:param tags: A set of tags. Resource tags.
:type tags: dict[str, str]
:param peering_locations: A list of peering locations.
:type peering_locations: list[str]
:param bandwidths_offered: A list of bandwidths offered.
:type bandwidths_offered:
list[~azure.mgmt.network.v2019_11_01.models.ExpressRouteServiceProviderBandwidthsOffered]
:ivar provisioning_state: The provisioning state of the express route service provider
resource. Possible values include: "Succeeded", "Updating", "Deleting", "Failed".
:vartype provisioning_state: str or ~azure.mgmt.network.v2019_11_01.models.ProvisioningState | 6259908871ff763f4b5e936a |
class CreateServiceAccountKeyRequest(_messages.Message): <NEW_LINE> <INDENT> class PrivateKeyTypeValueValuesEnum(_messages.Enum): <NEW_LINE> <INDENT> TYPE_UNSPECIFIED = 0 <NEW_LINE> TYPE_PKCS12_FILE = 1 <NEW_LINE> TYPE_GOOGLE_CREDENTIALS_FILE = 2 <NEW_LINE> <DEDENT> privateKeyType = _messages.EnumField('PrivateKeyTypeValueValuesEnum', 1) | The service account key create request.
Enums:
PrivateKeyTypeValueValuesEnum: The type of the private key requested.
GOOGLE_CREDENTIALS is the default key type.
Fields:
privateKeyType: The type of the private key requested. GOOGLE_CREDENTIALS
is the default key type. | 625990885fcc89381b266f3c |
class light_speed(temporary_env): <NEW_LINE> <INDENT> def __init__(self, c): <NEW_LINE> <INDENT> temporary_env.__init__(self, param, LIGHT_SPEED=c) <NEW_LINE> self.c = c <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> temporary_env.__enter__(self) <NEW_LINE> return self.c | Within the context of this macro, the environment varialbe LIGHT_SPEED
can be customized.
Examples:
>>> with light_speed(15.):
... print(lib.param.LIGHT_SPEED)
15.
>>> print(lib.param.LIGHT_SPEED)
137.03599967994 | 62599088e1aae11d1e7cf5f2 |
class ELSTD: <NEW_LINE> <INDENT> def __init__(self, num_features=None, epsilon=0): <NEW_LINE> <INDENT> self.n = n <NEW_LINE> self.reset(epsilon) <NEW_LINE> <DEDENT> def reset(self, epsilon=0): <NEW_LINE> <INDENT> self.z = np.zeros(self.n) <NEW_LINE> self.A = np.eye(self.n) * epsilon <NEW_LINE> self.b = np.zeros(self.n) <NEW_LINE> self.F = 0 <NEW_LINE> self.M = 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def theta(self): <NEW_LINE> <INDENT> _theta = np.dot(np.linalg.pinv(self.A), self.b) <NEW_LINE> return _theta <NEW_LINE> <DEDENT> def update(self, x, reward, xp, gm, gm_p, lm, interest): <NEW_LINE> <INDENT> self.F = gm * self.F + interest <NEW_LINE> self.M = (lm * I) + ((1 - lm) * self.F) <NEW_LINE> self.z = (gm * lm * self.z + self.M * x) <NEW_LINE> self.A += np.outer(self.z, (x - gm_p*xp)) <NEW_LINE> self.b += self.z * reward | Emphatic least-squares temporal difference learning.
Attributes
----------
n : int
The number of features (and therefore the length of the weight vector).
z : Vector[float]
The eligibility trace vector.
A : Matrix[float]
A matrix with shape `(n, n)` that acts like a potential matrix.
b : Vector[float]
A vector of length `n` that accumulates the trace multiplied by the
reward over a trajectory.
F : float
The followon trace scalar.
M : float
The emphasis scalar. | 62599088bf627c535bcb3091 |
class IntentData(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._examples = [] <NEW_LINE> <DEDENT> def addExample(self, example): <NEW_LINE> <INDENT> self._examples.append(example) <NEW_LINE> <DEDENT> def getExamples(self): <NEW_LINE> <INDENT> return self._examples | Represents a single intent. | 625990887047854f46340f73 |
class Code(Terminal): <NEW_LINE> <INDENT> def __init__(self, *codes): <NEW_LINE> <INDENT> self.codes = set(map(assetcode.normalise, codes)) <NEW_LINE> <DEDENT> def match_single(self, inv_node): <NEW_LINE> <INDENT> return inv_node.code in self.codes <NEW_LINE> <DEDENT> def sexpr(self): <NEW_LINE> <INDENT> return f"(Code {list(self.codes)})" | An AST node representing a 'code' check.
:param codes: A list of valid codes.
:type codes: list of str | 6259908826068e7796d4e500 |
class CardArgumentError(Exception): <NEW_LINE> <INDENT> pass | Exception raised when arguments to the Card class
initializer are mismatched or missing. | 625990884a966d76dd5f0aa4 |
class MAVLink_serial_udb_extra_f5_message(MAVLink_message): <NEW_LINE> <INDENT> def __init__(self, sue_YAWKP_AILERON, sue_YAWKD_AILERON, sue_ROLLKP, sue_ROLLKD, sue_YAW_STABILIZATION_AILERON, sue_AILERON_BOOST): <NEW_LINE> <INDENT> MAVLink_message.__init__(self, MAVLINK_MSG_ID_SERIAL_UDB_EXTRA_F5, 'SERIAL_UDB_EXTRA_F5') <NEW_LINE> self._fieldnames = ['sue_YAWKP_AILERON', 'sue_YAWKD_AILERON', 'sue_ROLLKP', 'sue_ROLLKD', 'sue_YAW_STABILIZATION_AILERON', 'sue_AILERON_BOOST'] <NEW_LINE> self.sue_YAWKP_AILERON = sue_YAWKP_AILERON <NEW_LINE> self.sue_YAWKD_AILERON = sue_YAWKD_AILERON <NEW_LINE> self.sue_ROLLKP = sue_ROLLKP <NEW_LINE> self.sue_ROLLKD = sue_ROLLKD <NEW_LINE> self.sue_YAW_STABILIZATION_AILERON = sue_YAW_STABILIZATION_AILERON <NEW_LINE> self.sue_AILERON_BOOST = sue_AILERON_BOOST <NEW_LINE> <DEDENT> def pack(self, mav): <NEW_LINE> <INDENT> return MAVLink_message.pack(self, mav, 121, struct.pack('<ffffff', self.sue_YAWKP_AILERON, self.sue_YAWKD_AILERON, self.sue_ROLLKP, self.sue_ROLLKD, self.sue_YAW_STABILIZATION_AILERON, self.sue_AILERON_BOOST)) | Backwards compatible version of SERIAL_UDB_EXTRA F5: format | 625990885fc7496912d4904a |
class RA_coord(object): <NEW_LINE> <INDENT> ra_expr = re.compile(r'(\d{1,2})[: ](\d{1,2})[: ](\d{1,2}(\.\d+)?)') <NEW_LINE> def __init__(self,h,m,s): <NEW_LINE> <INDENT> if isinstance(s,float): <NEW_LINE> <INDENT> s = "{0:.2}".format(s) <NEW_LINE> <DEDENT> self.h = abs(int(h)) <NEW_LINE> self.m = abs(int(m)) <NEW_LINE> self.s = abs(Decimal(s)) <NEW_LINE> <DEDENT> def toHours(self): <NEW_LINE> <INDENT> return self.h+Decimal(self.m)/60 +Decimal(self.s)/3600 <NEW_LINE> <DEDENT> def toDegrees(self): <NEW_LINE> <INDENT> return self.toHours()*15 <NEW_LINE> <DEDENT> def toASeconds(self): <NEW_LINE> <INDENT> return 15*(self.h*3600 + self.m*60 + self.s) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "{0:02}:{1:02}:{2:05.2f}".format(self.h,self.m,self.s) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "RA_coord({0},{1},{2})".format(self.h,self.m,self.s) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def fromStr(cls,s): <NEW_LINE> <INDENT> match = RA_coord.ra_expr.match(s) <NEW_LINE> if match: <NEW_LINE> <INDENT> h,m,s = match.group(1,2,3) <NEW_LINE> return cls(h,m,s) <NEW_LINE> <DEDENT> elif decimal_re.match(s): <NEW_LINE> <INDENT> return cls.fromDegrees(Decimal(s)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def fromHours(cls,hrs): <NEW_LINE> <INDENT> tmp = hrs <NEW_LINE> h = int(tmp) <NEW_LINE> tmp *= 60 <NEW_LINE> m = int(tmp % 60) <NEW_LINE> tmp *= 60 <NEW_LINE> s = tmp % 60 <NEW_LINE> return cls(h,m,s) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def fromDegrees(cls, deg): <NEW_LINE> <INDENT> if isinstance(deg,float): <NEW_LINE> <INDENT> deg = "{0:.2}".format(deg) <NEW_LINE> <DEDENT> return cls.fromHours(Decimal(deg)/15) <NEW_LINE> <DEDENT> def __sub__(self, other): <NEW_LINE> <INDENT> return self.toASeconds() - other.toASeconds() <NEW_LINE> <DEDENT> @property <NEW_LINE> def hours(self): <NEW_LINE> <INDENT> return self.h <NEW_LINE> <DEDENT> @property <NEW_LINE> def minutes(self): <NEW_LINE> <INDENT> return self.m <NEW_LINE> <DEDENT> @property <NEW_LINE> def seconds(self): <NEW_LINE> <INDENT> return self.s | A coordinate in RA | 625990887b180e01f3e49e44 |
class GeloPluginManager(PluginManager.PluginManager): <NEW_LINE> <INDENT> def __init__(self, plugin_locator=None): <NEW_LINE> <INDENT> if plugin_locator is None: <NEW_LINE> <INDENT> plugin_locator = PluginFileLocator.PluginFileAnalyzerWithInfoFile( "GeloPluginAnalyzer", extensions="gelo-plugin" ) <NEW_LINE> <DEDENT> super().__init__( categories_filter=None, directories_list=None, plugin_locator=plugin_locator ) <NEW_LINE> self.config = None <NEW_LINE> self.mediator = None <NEW_LINE> self.show = None <NEW_LINE> <DEDENT> def set_cms(self, config, mediator: arch.IMediator, show: str) -> None: <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.mediator = mediator <NEW_LINE> self.show = show <NEW_LINE> <DEDENT> def instanciateElementWithImportInfo( self, element, element_name, plugin_module_name, candidate_filepath ): <NEW_LINE> <INDENT> c = self.config.configparser["plugin:" + element_name] <NEW_LINE> return element(c, self.mediator, self.show) <NEW_LINE> <DEDENT> def instanciateElement(self, element): <NEW_LINE> <INDENT> return element(self.config.configparser, self.mediator, self.show) <NEW_LINE> <DEDENT> def enablePluginByName(self, name, category="Default"): <NEW_LINE> <INDENT> to_enable = self.getPluginByName(name, category) <NEW_LINE> if to_enable is not None: <NEW_LINE> <INDENT> eo = to_enable.plugin_object <NEW_LINE> if eo is not None: <NEW_LINE> <INDENT> eo.enable() <NEW_LINE> return eo <NEW_LINE> <DEDENT> <DEDENT> return None <NEW_LINE> <DEDENT> def disablePluginByName(self, name, category="Default"): <NEW_LINE> <INDENT> to_disable = self.getPluginByName(name, category) <NEW_LINE> if to_disable is not None: <NEW_LINE> <INDENT> do = to_disable.plugin_object <NEW_LINE> if do is not None: <NEW_LINE> <INDENT> do.disable() <NEW_LINE> return do <NEW_LINE> <DEDENT> <DEDENT> return None | Load Gelo plugins (just override the method that instantiates plugins).
| 6259908899fddb7c1ca63bbb |
class RLimsolve(RPackage): <NEW_LINE> <INDENT> homepage = "https://cloud.r-project.org/package=limSolve" <NEW_LINE> url = "https://cloud.r-project.org/src/contrib/limSolve_1.5.6.tar.gz" <NEW_LINE> list_url = "https://cloud.r-project.org/src/contrib/Archive/limSolve" <NEW_LINE> version('1.5.6', sha256='b97ea9930383634c8112cdbc42f71c4e93fe0e7bfaa8f401921835cb44cb49a0') <NEW_LINE> depends_on('[email protected]:', type=('build', 'run')) <NEW_LINE> depends_on('r-quadprog', type=('build', 'run')) <NEW_LINE> depends_on('r-lpsolve', type=('build', 'run')) <NEW_LINE> depends_on('r-mass', type=('build', 'run')) | Solving Linear Inverse Models
Functions that (1) find the minimum/maximum of a linear or quadratic
function: min or max (f(x)), where f(x) = ||Ax-b||^2 or f(x) = sum(a_i*x_i)
subject to equality constraints Ex=f and/or inequality constraints Gx>=h,
(2) sample an underdetermined- or overdetermined system Ex=f subject to
Gx>=h, and if applicable Ax~=b, (3) solve a linear system Ax=B for the
unknown x. It includes banded and tridiagonal linear systems. | 62599088adb09d7d5dc0c119 |
class Meta: <NEW_LINE> <INDENT> unique_together = ( ('name', 'slave'), ( 'source_path', 'destination_path', 'slave', 'source_type', 'destination_type', ), ) | Meta class | 62599088e1aae11d1e7cf5f3 |
class AddInstance(base.Command): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def Args(parser): <NEW_LINE> <INDENT> parser.add_argument( 'resource', nargs='+', help='Resources to add to the resource view.') <NEW_LINE> <DEDENT> def Run(self, args): <NEW_LINE> <INDENT> zone_views_client = self.context['zoneViewsClient'] <NEW_LINE> project = properties.VALUES.core.project.Get(required=True) <NEW_LINE> if args.region: <NEW_LINE> <INDENT> raise exceptions.ToolException(ValueError( 'addinstance must be used against a zonal resourceview')) <NEW_LINE> <DEDENT> instance_urls = [] <NEW_LINE> for instance in args.resource: <NEW_LINE> <INDENT> instance_urls.append( 'https://www.googleapis.com/compute/v1/projects/' + project + '/zones/' + args.zone + '/instances/' + instance) <NEW_LINE> <DEDENT> request_body = {'resources': instance_urls} <NEW_LINE> if 'v1beta1' in self.context['api_version']: <NEW_LINE> <INDENT> request = zone_views_client.addresources( projectName=project, zone=args.zone, resourceViewName=args.resourceview, body=request_body) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> request = zone_views_client.addResources( project=project, zone=args.zone, resourceView=args.resourceview, body=request_body) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> request.execute() <NEW_LINE> log.Print('Instances added to resource view {0}.'.format( args.resourceview)) <NEW_LINE> <DEDENT> except errors.HttpError as error: <NEW_LINE> <INDENT> raise exceptions.HttpException(util.GetError(error)) <NEW_LINE> <DEDENT> except errors.Error as error: <NEW_LINE> <INDENT> raise exceptions.ToolException(error) | Adds resources to a resource view by resource name. | 62599088656771135c48ae10 |
class RectangularController(BaseController): <NEW_LINE> <INDENT> def __init__(self, width, height=1, reverse_x=False, reverse_y=False, a=10): <NEW_LINE> <INDENT> self.WIDTH = width <NEW_LINE> self.HEIGHT = height <NEW_LINE> self.REVERSE_X = reverse_x <NEW_LINE> self.REVERSE_Y = reverse_y <NEW_LINE> config = { 'a': a, 'height': height, 'reverse_x': reverse_x, 'reverse_y': reverse_y, 'type': 'rectangle', 'width': width, } <NEW_LINE> BaseController.__init__(self, config, width * height, a) <NEW_LINE> <DEDENT> def _get_index(self, x, y): <NEW_LINE> <INDENT> if self.REVERSE_X: <NEW_LINE> <INDENT> x = self.WIDTH - x - 1 <NEW_LINE> <DEDENT> if self.REVERSE_Y: <NEW_LINE> <INDENT> y = self.HEIGHT - y - 1 <NEW_LINE> <DEDENT> return (y * self.WIDTH) + (x if y % 2 == 0 else self.WIDTH - x - 1) <NEW_LINE> <DEDENT> def add_led(self, x, y, colour): <NEW_LINE> <INDENT> index = self._get_index(x, y) <NEW_LINE> BaseController.add_led(self, index, colour) <NEW_LINE> <DEDENT> def set_led(self, x, y, colour): <NEW_LINE> <INDENT> index = self._get_index(x, y) <NEW_LINE> BaseController.set_led(self, index, colour) | An interface to control a strip of RGB LEDs arranged in a rectangle.
| 625990884c3428357761be7b |
class CiscoAsaSSH(CiscoSSHConnection): <NEW_LINE> <INDENT> def session_preparation(self): <NEW_LINE> <INDENT> self._test_channel_read() <NEW_LINE> self.set_base_prompt() <NEW_LINE> if self.secret: <NEW_LINE> <INDENT> self.enable() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.asa_login() <NEW_LINE> <DEDENT> self.disable_paging(command="terminal pager 0") <NEW_LINE> self.set_terminal_width(command="terminal width 511") <NEW_LINE> time.sleep(.3 * self.global_delay_factor) <NEW_LINE> self.clear_buffer() <NEW_LINE> <DEDENT> def send_command_timing(self, *args, **kwargs): <NEW_LINE> <INDENT> output = super(CiscoAsaSSH, self).send_command_timing(*args, **kwargs) <NEW_LINE> if len(args) >= 1: <NEW_LINE> <INDENT> command_string = args[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> command_string = kwargs['command_string'] <NEW_LINE> <DEDENT> if "changeto" in command_string: <NEW_LINE> <INDENT> self.set_base_prompt() <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> def send_command(self, *args, **kwargs): <NEW_LINE> <INDENT> if len(args) >= 1: <NEW_LINE> <INDENT> command_string = args[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> command_string = kwargs['command_string'] <NEW_LINE> <DEDENT> if "changeto" in command_string: <NEW_LINE> <INDENT> if len(args) <= 1: <NEW_LINE> <INDENT> expect_string = kwargs.get('expect_string', '#') <NEW_LINE> kwargs['expect_string'] = expect_string <NEW_LINE> <DEDENT> <DEDENT> output = super(CiscoAsaSSH, self).send_command(*args, **kwargs) <NEW_LINE> if "changeto" in command_string: <NEW_LINE> <INDENT> self.set_base_prompt() <NEW_LINE> <DEDENT> return output <NEW_LINE> <DEDENT> def send_command_expect(self, *args, **kwargs): <NEW_LINE> <INDENT> return self.send_command(*args, **kwargs) <NEW_LINE> <DEDENT> def set_base_prompt(self, *args, **kwargs): <NEW_LINE> <INDENT> cur_base_prompt = super(CiscoAsaSSH, self).set_base_prompt(*args, **kwargs) <NEW_LINE> match = re.search(r'(.*)\(conf.*', cur_base_prompt) <NEW_LINE> if match: <NEW_LINE> <INDENT> self.base_prompt = match.group(1) <NEW_LINE> return self.base_prompt <NEW_LINE> <DEDENT> <DEDENT> def asa_login(self): <NEW_LINE> <INDENT> delay_factor = self.select_delay_factor(0) <NEW_LINE> i = 1 <NEW_LINE> max_attempts = 50 <NEW_LINE> self.write_channel("login" + self.RETURN) <NEW_LINE> while i <= max_attempts: <NEW_LINE> <INDENT> time.sleep(.5 * delay_factor) <NEW_LINE> output = self.read_channel() <NEW_LINE> if 'sername' in output: <NEW_LINE> <INDENT> self.write_channel(self.username + self.RETURN) <NEW_LINE> <DEDENT> elif 'ssword' in output: <NEW_LINE> <INDENT> self.write_channel(self.password + self.RETURN) <NEW_LINE> <DEDENT> elif '#' in output: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.write_channel("login" + self.RETURN) <NEW_LINE> <DEDENT> i += 1 | Subclass specific to Cisco ASA. | 62599088aad79263cf43037b |
class TrailEditForm(forms.ModelForm): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Trail <NEW_LINE> fields = [ 'title', 'region', 'country', 'description', 'trackfile', 'distance', 'ascent', 'calories', 'duration', 'geocaches', 'public', 'trail_type', 'activity_type', 'difficulty', 'season', 'directions', ] | User edits one of their trails. | 62599088be7bc26dc9252c36 |
class EmailBackend(object): <NEW_LINE> <INDENT> def authenticate(self, username=None, password=None, **kwargs): <NEW_LINE> <INDENT> UserModel = get_user_model() <NEW_LINE> if username is None: <NEW_LINE> <INDENT> username = kwargs.get('email') <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> user = UserModel._default_manager.get(email=username) <NEW_LINE> if user.check_password(password): <NEW_LINE> <INDENT> return user <NEW_LINE> <DEDENT> <DEDENT> except UserModel.DoesNotExist: <NEW_LINE> <INDENT> UserModel().set_password(password) <NEW_LINE> <DEDENT> <DEDENT> def get_user(self, user_id): <NEW_LINE> <INDENT> UserModel = get_user_model() <NEW_LINE> try: <NEW_LINE> <INDENT> return UserModel._default_manager.get(pk=user_id) <NEW_LINE> <DEDENT> except UserModel.DoesNotExist: <NEW_LINE> <INDENT> return None | Authenticates against settings.AUTH_USER_MODEL. | 62599088d8ef3951e32c8c3e |
class PacketLoggerOpts(TypedDict, total=False): <NEW_LINE> <INDENT> enabled: Optional[bool] <NEW_LINE> fileNumberLimit: Optional[int] <NEW_LINE> logFileSizeInHours: Optional[float] <NEW_LINE> compressSpecifications: Optional[bool] <NEW_LINE> compressPrices: Optional[bool] | Packet logger options. | 62599088dc8b845886d5517a |
class Calculator(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.choices_cmd = ['add', 'sub', 'mul', 'div', 'pow', 'mod', 'floor'] <NEW_LINE> <DEDENT> def add(self, op1, op2): <NEW_LINE> <INDENT> return op1 + op2 <NEW_LINE> <DEDENT> def sub(self, op1, op2): <NEW_LINE> <INDENT> return op1 - op2 <NEW_LINE> <DEDENT> def mul(self, op1, op2): <NEW_LINE> <INDENT> return op1 * op2 <NEW_LINE> <DEDENT> def div(self, op1, op2): <NEW_LINE> <INDENT> return op1 / op2 <NEW_LINE> <DEDENT> def pow(self, op1, op2): <NEW_LINE> <INDENT> return op1 ** op2 <NEW_LINE> <DEDENT> def mod(self, op1, op2): <NEW_LINE> <INDENT> return op1 % op2 <NEW_LINE> <DEDENT> def floor(self, op1, op2): <NEW_LINE> <INDENT> return op1 // op2 <NEW_LINE> <DEDENT> def wall(self, op1, op2): <NEW_LINE> <INDENT> print("WALL!") <NEW_LINE> <DEDENT> def magic(self, op1, op2): <NEW_LINE> <INDENT> return ((( op1 / op2 ) + ( op2 / op1 ))* op1 ) / op2 <NEW_LINE> <DEDENT> def floor2(self, op1, op2): <NEW_LINE> <INDENT> return op1 // op2 <NEW_LINE> <DEDENT> def bhendrickx(self, op1, op2): <NEW_LINE> <INDENT> return op1 / 100 + op2 / 100 <NEW_LINE> <DEDENT> def rand(self): <NEW_LINE> <INDENT> return 42 <NEW_LINE> <DEDENT> def powpow(self, op1, op2): <NEW_LINE> <INDENT> return (op1 ** op2) ** op2 <NEW_LINE> <DEDENT> def addanddividebytwo(self, op1, op2): <NEW_LINE> <INDENT> return (op1 + op2) / 2 | A basic calculator, little more than a wrapper for some basic arithmetic operators. | 6259908871ff763f4b5e936e |
class Command(BaseCommand): <NEW_LINE> <INDENT> help = "Notifies job alert subscribers of new matches" <NEW_LINE> def handle(self, *args, **options): <NEW_LINE> <INDENT> task = JobAlertNotificationTask.objects.create() <NEW_LINE> try: <NEW_LINE> <INDENT> start_time = ( JobAlertNotificationTask.objects.filter(is_successful=True) .latest("started") .started ) <NEW_LINE> <DEDENT> except JobAlertNotificationTask.DoesNotExist: <NEW_LINE> <INDENT> start_time = None <NEW_LINE> <DEDENT> for homepage in RecruitmentHomePage.objects.live().all(): <NEW_LINE> <INDENT> messages = [] <NEW_LINE> alerts = JobAlertSubscription.objects.filter( confirmed=True, homepage=homepage ) <NEW_LINE> for alert in alerts: <NEW_LINE> <INDENT> search_params = json.loads(alert.search) <NEW_LINE> querydict = QueryDict(mutable=True) <NEW_LINE> querydict.update(search_params) <NEW_LINE> results = get_job_search_results( querydict=querydict, homepage=homepage, queryset=self.get_queryset( start_time=max(filter(None, [start_time, alert.created])), end_time=task.started, ), ) <NEW_LINE> if results: <NEW_LINE> <INDENT> subject = "New job search results" <NEW_LINE> body = render_to_string( "patterns/email/job_search_results_alert.txt", context={**alert.get_email_context(), "results": results}, ) <NEW_LINE> messages.append( NotifyEmailMessage(subject=subject, body=body, to=[alert.email]) ) <NEW_LINE> <DEDENT> <DEDENT> num_sent = 0 <NEW_LINE> for message in messages: <NEW_LINE> <INDENT> message.send() <NEW_LINE> num_sent += 1 <NEW_LINE> <DEDENT> task.is_successful = True <NEW_LINE> task.ended = now() <NEW_LINE> task.save() <NEW_LINE> self.stdout.write( f"{len(alerts)} subscriptions for job site (id={homepage.id}) evaluated" ) <NEW_LINE> self.stdout.write(f"{num_sent} emails sent") <NEW_LINE> <DEDENT> <DEDENT> def get_queryset(self, start_time, end_time): <NEW_LINE> <INDENT> params = {"created__lt": end_time} <NEW_LINE> if start_time: <NEW_LINE> <INDENT> params["created__gte"] = start_time <NEW_LINE> <DEDENT> return TalentLinkJob.objects.filter(**params) | This checks job alert subscriptions, and sends messages about new matches.
Any further documentation for this feature is at docs/recruitment-site.md | 62599088a05bb46b3848bf07 |
class PQ(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Q = [] <NEW_LINE> self.length = 0 <NEW_LINE> <DEDENT> def push(self, item, priority = 0): <NEW_LINE> <INDENT> heapq.heappush(self.Q, (priority, item)) <NEW_LINE> self.length += 1 <NEW_LINE> <DEDENT> def isEmpty(self): <NEW_LINE> <INDENT> return self.length == 0 <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return str(self.Q) <NEW_LINE> <DEDENT> def pop(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return heapq.heappop(self.Q)[1] <NEW_LINE> self.length -= 1 <NEW_LINE> <DEDENT> except IndexError as e: <NEW_LINE> <INDENT> print("The PQ is empty. There is no solution") <NEW_LINE> raise | Priority queue. | 62599088e1aae11d1e7cf5f4 |
class Bowtie2_MapError(Exception): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> self.message = message | Exception raised when bowtie2-map fails | 62599088283ffb24f3cf5462 |
class H5TelstateSensorData(RecordSensorData): <NEW_LINE> <INDENT> def __init__(self, data, name=None): <NEW_LINE> <INDENT> super(H5TelstateSensorData, self).__init__(data, name) <NEW_LINE> self.dtype = None <NEW_LINE> <DEDENT> def __getitem__(self, key): <NEW_LINE> <INDENT> if key == 'timestamp': <NEW_LINE> <INDENT> return np.asarray(self._data[key]) <NEW_LINE> <DEDENT> elif key == 'value': <NEW_LINE> <INDENT> values = [_h5_telstate_unpack(s) for s in self._data[key]] <NEW_LINE> self.dtype = infer_dtype(values) <NEW_LINE> if self.dtype == np.object: <NEW_LINE> <INDENT> values = [ComparableArrayWrapper(value) for value in values] <NEW_LINE> <DEDENT> return values <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("Sensor %r data has no key '%s'" % (self.name, key)) | Raw (uninterpolated) sensor data in HDF5 TelescopeState recarray form.
This wraps the telstate sensors stored in recent HDF5 files. It differs
in two ways from the normal HDF5 sensors: no 'status' field and values
encoded by katsdptelstate.
TODO: This is a temporary fix to get at missing sensors in telstate and
should be replaced by a proper wrapping of any telstate object.
Object-valued sensors (including sensors with ndarrays as values) will have
its values wrapped by :class:`ComparableArrayWrapper`.
Parameters
----------
data : recarray-like, with fields ('timestamp', 'value')
Uninterpolated sensor data as structured array or equivalent (such as
an :class:`h5py.Dataset`)
name : string or None, optional
Sensor name (assumed to be data.name by default, if it exists) | 625990882c8b7c6e89bd53a8 |
class WhatIsVocabQuestion(QuestionTemplate): <NEW_LINE> <INDENT> regex1 = Lemma("who") + Lemma("be") + Vocabulary() <NEW_LINE> regex2 = Lemma("what") + Lemma("be") + Vocabulary() <NEW_LINE> regex = (regex1 | regex2) + Question(Pos(".")) <NEW_LINE> def interpret(self, match): <NEW_LINE> <INDENT> desc = dsl.DefinitionOf(match.vocabulary) <NEW_LINE> return desc, "define" | Regex for questions like "What is foaf"
Ex: "What is dcterms" | 625990885fc7496912d4904c |
class PwmanCli(cmd.Cmd, BaseCommands): <NEW_LINE> <INDENT> undoc_header = "Aliases:" <NEW_LINE> def __init__(self, db, hasxsel, callback, config_parser, **kwargs): <NEW_LINE> <INDENT> super(PwmanCli, self).__init__(**kwargs) <NEW_LINE> self.intro = "%s %s (c) visit: %s" % (appname, version, website) <NEW_LINE> self._historyfile = config_parser.get_value("Readline", "history") <NEW_LINE> self.hasxsel = hasxsel <NEW_LINE> self.config = config_parser <NEW_LINE> try: <NEW_LINE> <INDENT> enc = CryptoEngine.get() <NEW_LINE> enc.callback = callback() <NEW_LINE> self._db = db <NEW_LINE> self._db.open() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.error(e) <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> readline.read_history_file(self._historyfile) <NEW_LINE> <DEDENT> except IOError as e: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> self.prompt = "pwman> " | Inherit from the BaseCommands and Aliases | 6259908871ff763f4b5e9370 |
class Page(models.Model): <NEW_LINE> <INDENT> content_type = models.ForeignKey(ContentType) <NEW_LINE> object_id = models.PositiveIntegerField() <NEW_LINE> content_object = generic.GenericForeignKey('content_type', 'object_id') <NEW_LINE> @property <NEW_LINE> def title(self): <NEW_LINE> <INDENT> return self.content_object.title | Page is a catch-all model that encompasses plain text pages,
exercises, etc.
For each content type, remember to connect it to Page via
post_save and create_page (see example below) | 62599088e1aae11d1e7cf5f5 |
class Logo(LogoType_): <NEW_LINE> <INDENT> c_tag = 'Logo' <NEW_LINE> c_namespace = NAMESPACE <NEW_LINE> c_children = LogoType_.c_children.copy() <NEW_LINE> c_attributes = LogoType_.c_attributes.copy() <NEW_LINE> c_child_order = LogoType_.c_child_order[:] <NEW_LINE> c_cardinality = LogoType_.c_cardinality.copy() | The urn:oasis:names:tc:SAML:metadata:ui:Logo element | 625990885fdd1c0f98e5fb3d |
class TemporalAttachmentMetamorphosisGeomGradientGradZetaPenalized(Operator): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__(functional.domain, functional.domain, linear=False) <NEW_LINE> <DEDENT> def _call(self, X): <NEW_LINE> <INDENT> zeta_list=X[1] <NEW_LINE> grad = functional.gradient(X) <NEW_LINE> laplacian_op = odl.discr.diff_ops.Laplacian(functional.image_domain) <NEW_LINE> for k in range(functional.N): <NEW_LINE> <INDENT> grad[1][k] -= 2*laplacian_op(zeta_list[k]).copy() <NEW_LINE> <DEDENT> return grad | The gradient operator of the TemporalAttachmentMetmorphosisGeom
functional when zeta is also penalized by the norm of
its gradient. | 625990887047854f46340f79 |
class JudgeConfig(AppConfig): <NEW_LINE> <INDENT> name = 'judge' <NEW_LINE> verbose_name = _("Judge") | Config class used for app name and its translation. | 62599088aad79263cf43037e |
class ObjectBase(ObjectGen): <NEW_LINE> <INDENT> def __init__(self, name='', createFunction = None, model = None, models= [], anims = [], animNames = [], animDict = {}, properties={}, movable = True, actor = False, named=False, updateModelFunction = None, orderedProperties=[], propertiesMask={}): <NEW_LINE> <INDENT> ObjectGen.__init__(self, name) <NEW_LINE> self.createFunction = createFunction <NEW_LINE> self.model = model <NEW_LINE> self.models = models[:] <NEW_LINE> self.anims = anims[:] <NEW_LINE> self.animNames = animNames[:] <NEW_LINE> self.animDict = copy.deepcopy(animDict) <NEW_LINE> self.properties = copy.deepcopy(properties) <NEW_LINE> self.movable = movable <NEW_LINE> self.actor = actor <NEW_LINE> self.named = named <NEW_LINE> self.updateModelFunction = updateModelFunction <NEW_LINE> self.orderedProperties = orderedProperties[:] <NEW_LINE> self.propertiesMask = copy.deepcopy(propertiesMask) | Base class for obj definitions | 6259908850812a4eaa6219a7 |
class RLaplacesdemon(RPackage): <NEW_LINE> <INDENT> homepage = "https://github.com/LaplacesDemonR/LaplacesDemon" <NEW_LINE> url = "https://cloud.r-project.org/src/contrib/LaplacesDemon_16.0.1.tar.gz" <NEW_LINE> list_url = "https://cloud.r-project.org/src/contrib/Archive/LaplacesDemon" <NEW_LINE> version('16.1.4', sha256='4152a1c3c652979e97870e5c50c45a243d0ad8d4ff968091160e3d66509f61db') <NEW_LINE> version('16.1.1', sha256='779ed1dbfed523a15701b4d5d891d4f1f11ab27518826a8a7725807d4c42bd77') <NEW_LINE> version('16.1.0', sha256='41d99261e8fc33c977b43ecf66ebed8ef1c84d9bd46b271609e9aadddc2ca8bb') <NEW_LINE> version('16.0.1', sha256='be21eff3c821b4fe0b4724f03c9221c2456257f93d91f864de11e95dc35e8679') <NEW_LINE> depends_on('[email protected]:', type=('build', 'run')) | Complete Environment for Bayesian Inference
Provides a complete environment for Bayesian inference using a variety of
different samplers (see ?LaplacesDemon for an overview). The README
describes the history of the package development process. | 62599088aad79263cf43037f |
class IndexedSlices(_TensorLike): <NEW_LINE> <INDENT> def __init__(self, values, indices, dense_shape=None): <NEW_LINE> <INDENT> _get_graph_from_inputs([values, indices, dense_shape]) <NEW_LINE> self._values = values <NEW_LINE> self._indices = indices <NEW_LINE> self._dense_shape = dense_shape <NEW_LINE> <DEDENT> @property <NEW_LINE> def values(self): <NEW_LINE> <INDENT> return self._values <NEW_LINE> <DEDENT> @property <NEW_LINE> def indices(self): <NEW_LINE> <INDENT> return self._indices <NEW_LINE> <DEDENT> @property <NEW_LINE> def dense_shape(self): <NEW_LINE> <INDENT> return self._dense_shape <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.values.name <NEW_LINE> <DEDENT> @property <NEW_LINE> def device(self): <NEW_LINE> <INDENT> return self.values.device <NEW_LINE> <DEDENT> @property <NEW_LINE> def op(self): <NEW_LINE> <INDENT> return self.values.op <NEW_LINE> <DEDENT> @property <NEW_LINE> def dtype(self): <NEW_LINE> <INDENT> return self.values.dtype <NEW_LINE> <DEDENT> @property <NEW_LINE> def graph(self): <NEW_LINE> <INDENT> return self._values.graph <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "IndexedSlices(indices=%s, values=%s%s)" % ( self._indices, self._values, (", dense_shape=%s" % self._dense_shape) if self._dense_shape is not None else "") <NEW_LINE> <DEDENT> def __neg__(self): <NEW_LINE> <INDENT> return IndexedSlices(-self.values, self.indices, self.dense_shape) | A sparse representation of a set of tensor slices at given indices.
This class is a simple wrapper for a pair of `Tensor` objects:
* `values`: A `Tensor` of any dtype with shape `[D0, D1, ..., Dn]`.
* `indices`: A 1-D integer `Tensor` with shape `[D0]`.
An `IndexedSlices` is typically used to represent a subset of a larger
tensor `dense` of shape `[LARGE0, D1, .. , DN]` where `LARGE0 >> D0`.
The values in `indices` are the indices in the first dimension of
the slices that have been extracted from the larger tensor.
The dense tensor `dense` represented by an `IndexedSlices` `slices` has
```python
dense[slices.indices[i], :, :, :, ...] = slices.values[i, :, :, :, ...]
```
The `IndexedSlices` class is used principally in the definition of
gradients for operations that have sparse gradients
(e.g. [`tf.gather`](../../api_docs/python/array_ops.md#gather)).
Contrast this representation with
[`SparseTensor`](../../api_docs/python/sparse_ops.md#SparseTensor),
which uses multi-dimensional indices and scalar values. | 62599088dc8b845886d5517e |
class Signup(FlexibleSchema): <NEW_LINE> <INDENT> username = UniqueUsername(not_empty=True) <NEW_LINE> email = UniqueEmail(resolve_domain=True, not_empty=True) <NEW_LINE> password = Password(not_empty=True) <NEW_LINE> confirm = Password(not_empty=True) <NEW_LINE> chained_validators = [ validators.FieldsMatch( 'password', 'confirm' ) ] | Form fields to render and validate for signup. | 62599088ad47b63b2c5a9417 |
@debtcollector.removals.removed_class("OpportunisticTestCase") <NEW_LINE> class OpportunisticTestCase(DbTestCase): <NEW_LINE> <INDENT> pass | Placeholder for backwards compatibility. | 62599088adb09d7d5dc0c11f |
class Cfc: <NEW_LINE> <INDENT> def __init__(self, grafo): <NEW_LINE> <INDENT> self.grafo = grafo <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> dfs = BuscaProfundidade(self.grafo) <NEW_LINE> dfs.busca() <NEW_LINE> tt = TempoTermino(self.grafo.n_vertices) <NEW_LINE> for u in range(self.grafo.n_vertices): <NEW_LINE> <INDENT> tt.t[u] = dfs.t[u] <NEW_LINE> tt.restantes[u] = True <NEW_LINE> <DEDENT> grafoT = self.grafo.transposto() <NEW_LINE> while tt.n_restantes: <NEW_LINE> <INDENT> vRaiz = tt.maxTT() <NEW_LINE> print("Raiz da pŕoxima árvore:", vRaiz) <NEW_LINE> self.visitaDfs(grafoT,vRaiz,tt) <NEW_LINE> <DEDENT> <DEDENT> def visitaDfs(self, grafo, u, tt): <NEW_LINE> <INDENT> tt.restantes[u] = False <NEW_LINE> tt.n_restantes -= 1 <NEW_LINE> print("Vertice:", u) <NEW_LINE> adjs = grafo.adjs(u) <NEW_LINE> if adjs: <NEW_LINE> <INDENT> for v in adjs: <NEW_LINE> <INDENT> if tt.restantes[v]: self.visitaDfs(grafo, v, tt) | Busca por componentes fortemente conectados | 62599088a05bb46b3848bf09 |
class Scheme: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass | A Scheme class
The scheme class is responsible for the following:
Gen: A generator that produces a list of candidate tag sequences that is defined over the entire sentence structure.
Dec: A search algorithm that finds the highest scoring tag sequence from the list provided by the generator.
Enc: An encoder which is responsible for converting a tag sequence into a series of histories/contexts under a
user-defined stipulation of whether or not the problem is tractable.
Note: A scheme of size 1 is still a bit buggy, we want to avoid that for the time being | 62599088283ffb24f3cf5466 |
class RequestFailed(IOError): <NEW_LINE> <INDENT> pass | The metadata endpoint returned an unexpected status code. | 62599088aad79263cf430380 |
class TestLongestCommonPrefix(unittest.TestCase): <NEW_LINE> <INDENT> def test_longest_common_prefix(self): <NEW_LINE> <INDENT> s = SolutionF() <NEW_LINE> self.assertEqual('fl', s.longestCommonPrefix(["flower", "flow", "flight"])) <NEW_LINE> self.assertEqual('', s.longestCommonPrefix(["flower", "flow", ""])) <NEW_LINE> self.assertEqual('f', s.longestCommonPrefix(["flower", "flow", "f"])) <NEW_LINE> self.assertEqual('', s.longestCommonPrefix(["dog", "racecar", "car"])) <NEW_LINE> self.assertEqual('', s.longestCommonPrefix([])) | Test q014_longest_common_prefix.py | 625990888a349b6b43687e24 |
class DataTarget(_LocalPathTarget): <NEW_LINE> <INDENT> def load(self, fun, cached=False, **kwargs): <NEW_LINE> <INDENT> if self.exists(): <NEW_LINE> <INDENT> if not cached or not settings.cached or self.path not in cache: <NEW_LINE> <INDENT> opts = {**{},**kwargs} <NEW_LINE> df = fun(self.path, **opts) <NEW_LINE> if cached or settings.cached: <NEW_LINE> <INDENT> cache[self.path] = df <NEW_LINE> <DEDENT> return df <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return cache.get(self.path) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise RuntimeError('Target does not exist, make sure task is complete') <NEW_LINE> <DEDENT> <DEDENT> def save(self, df, fun, **kwargs): <NEW_LINE> <INDENT> fun = getattr(df, fun) <NEW_LINE> (self.path).parent.mkdir(parents=True, exist_ok=True) <NEW_LINE> fun(self.path, **kwargs) <NEW_LINE> return self.path | Local target which saves in-memory data (eg dataframes) to persistent storage (eg files) and loads from storage to memory
This is an abstract class that you should extend. | 6259908826068e7796d4e508 |
class KeyboardInterface(USBInterface): <NEW_LINE> <INDENT> name : str = "USB keyboard interface" <NEW_LINE> class_number : int = 3 <NEW_LINE> class KeyEventEndpoint(USBEndpoint): <NEW_LINE> <INDENT> number : int = 3 <NEW_LINE> direction : USBDirection = USBDirection.IN <NEW_LINE> transfer_type : USBTransferType = USBTransferType.INTERRUPT <NEW_LINE> interval : int = 10 <NEW_LINE> <DEDENT> class USBClassDescriptor(USBClassDescriptor): <NEW_LINE> <INDENT> number : int = USBDescriptorTypeNumber.HID <NEW_LINE> raw : bytes = b'\x09\x21\x10\x01\x00\x01\x22\x2b\x00' <NEW_LINE> <DEDENT> class ReportDescriptor(HIDReportDescriptor): <NEW_LINE> <INDENT> fields : tuple = ( USAGE_PAGE (HIDUsagePage.GENERIC_DESKTOP), USAGE (HIDGenericDesktopUsage.KEYBOARD), COLLECTION (HIDCollection.APPLICATION), USAGE_PAGE (HIDUsagePage.KEYBOARD), USAGE_MINIMUM (KeyboardKeys.LEFTCTRL), USAGE_MAXIMUM (KeyboardKeys.RIGHTMETA), LOGICAL_MINIMUM (0), LOGICAL_MAXIMUM (1), REPORT_SIZE (1), REPORT_COUNT (KeyboardKeys.RIGHTMETA - KeyboardKeys.LEFTCTRL + 1), INPUT (variable=True), REPORT_SIZE (8), REPORT_COUNT (1), INPUT (constant=True), USAGE_MINIMUM (KeyboardKeys.NONE), USAGE_MAXIMUM (KeyboardKeys.COMPOSE), LOGICAL_MINIMUM (KeyboardKeys.NONE), LOGICAL_MAXIMUM (KeyboardKeys.COMPOSE), REPORT_SIZE (8), REPORT_COUNT (KEY_ROLLOVER), INPUT (), END_COLLECTION (), ) <NEW_LINE> <DEDENT> @class_request_handler(number=USBStandardRequests.GET_INTERFACE) <NEW_LINE> @to_this_interface <NEW_LINE> def handle_get_interface_request(self, request): <NEW_LINE> <INDENT> request.stall() | Core HID interface for our keyboard. | 62599088a8370b77170f1f93 |
class Action(models.IntegerChoices): <NEW_LINE> <INDENT> CONTINUE = 0 <NEW_LINE> RECHECK = 1 <NEW_LINE> PAUSE = 2 <NEW_LINE> CHANGE = 3 <NEW_LINE> EMERGENCY = 4 <NEW_LINE> INACTIVATE = 5 | Class to describe Lab.action field choices and action taken on abnormal Lab.
Will be set by process_high() or process_low() method. | 62599088656771135c48ae14 |
class Customer(Person): <NEW_LINE> <INDENT> def __init__(self, company_name="", **kwargs): <NEW_LINE> <INDENT> super(Customer, self).__init__(**kwargs) <NEW_LINE> self.company_name = company_name | A subclass of Person that represents a customer. | 62599088ec188e330fdfa475 |
class TwoLayerNet(object): <NEW_LINE> <INDENT> def __init__(self, input_dim=3*32*32, hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0): <NEW_LINE> <INDENT> self.params = {} <NEW_LINE> self.reg = reg <NEW_LINE> self.params['W1'] = np.random.normal(scale=weight_scale, size=(input_dim, hidden_dim)) <NEW_LINE> self.params['b1'] = np.zeros(hidden_dim) <NEW_LINE> self.params['W2'] = np.random.normal(scale=weight_scale, size=(hidden_dim, num_classes)) <NEW_LINE> self.params['b2'] = np.zeros(num_classes) <NEW_LINE> <DEDENT> def loss(self, X, y=None): <NEW_LINE> <INDENT> scores = None <NEW_LINE> l1_out, l1_cache = affine_relu_forward(X, self.params['W1'], self.params['b1']) <NEW_LINE> l2_out, l2_cache = affine_forward(l1_out, self.params['W2'], self.params['b2']) <NEW_LINE> scores = l2_out <NEW_LINE> if y is None: <NEW_LINE> <INDENT> return scores <NEW_LINE> <DEDENT> loss, grads = 0, {} <NEW_LINE> data_loss, data_dx = softmax_loss(scores, y) <NEW_LINE> reg_loss = 0.0 <NEW_LINE> reg_loss += np.sum(self.params['W1'] * self.params['W1']) <NEW_LINE> reg_loss += np.sum(self.params['W2'] * self.params['W2']) <NEW_LINE> loss = data_loss + (0.5 * self.reg * reg_loss) <NEW_LINE> dH, dW2, db2 = affine_backward(data_dx, l2_cache) <NEW_LINE> grads['W2'] = dW2 + (self.reg * self.params['W2']) <NEW_LINE> grads['b2'] = db2 <NEW_LINE> dX, dW1, db1 = affine_relu_backward(dH, l1_cache) <NEW_LINE> grads['W1'] = dW1 + (self.reg * self.params['W1']) <NEW_LINE> grads['b1'] = db1 <NEW_LINE> return loss, grads | A two-layer fully-connected neural network with ReLU nonlinearity and
softmax loss that uses a modular layer design. We assume an input dimension
of D, a hidden dimension of H, and perform classification over C classes.
The architecure should be affine - relu - affine - softmax.
Note that this class does not implement gradient descent; instead, it
will interact with a separate Solver object that is responsible for running
optimization.
The learnable parameters of the model are stored in the dictionary
self.params that maps parameter names to numpy arrays. | 6259908826068e7796d4e50a |
class Clinic(models.Model): <NEW_LINE> <INDENT> TYPE_CHIOCES = ( ('primary', 'Primary Healthcare Facility'), ('general', 'General Hospital'), ) <NEW_LINE> name = models.CharField(max_length=100, unique=True) <NEW_LINE> slug = models.SlugField(unique=True) <NEW_LINE> type = models.CharField(max_length=16, null=True, choices=TYPE_CHIOCES, default='primary') <NEW_LINE> town = models.CharField(max_length=100) <NEW_LINE> ward = models.CharField(max_length=100) <NEW_LINE> lga = models.ForeignKey(LGA, null=True) <NEW_LINE> location = gis.PointField(null=True, blank=True) <NEW_LINE> lga_rank = models.IntegerField( blank=True, null=True, verbose_name='LGA rank', editable=False) <NEW_LINE> pbf_rank = models.IntegerField( blank=True, null=True, verbose_name='PBF rank', editable=False) <NEW_LINE> code = models.PositiveIntegerField( verbose_name='SMS Code', unique=True, help_text="Code of Clinic to be used in SMS registration.") <NEW_LINE> created = models.DateTimeField(auto_now_add=True) <NEW_LINE> updated = models.DateTimeField(auto_now=True) <NEW_LINE> objects = gis.GeoManager() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ['name'] <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def managers(self): <NEW_LINE> <INDENT> return self.clinicstaff_set.filter(is_manager=True) | A health clinic. | 6259908863b5f9789fe86d31 |
class BF3TestCase(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> from b3.parsers.frostbite2.abstractParser import AbstractParser <NEW_LINE> from b3.fake import FakeConsole <NEW_LINE> AbstractParser.__bases__ = (FakeConsole,) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> if hasattr(self, "parser"): <NEW_LINE> <INDENT> del self.parser.clients <NEW_LINE> self.parser.working = False | Test case that is suitable for testing BF3 parser specific features | 62599088d486a94d0ba2db7e |
class RecordsSource(ReadOnlySource): <NEW_LINE> <INDENT> fields = [params.RECORDS] <NEW_LINE> targets = (params.INPUT,) <NEW_LINE> actions = (params.READ_ACTION,) <NEW_LINE> def __init__(self, records): <NEW_LINE> <INDENT> self.records = records <NEW_LINE> <DEDENT> def get_data(self): <NEW_LINE> <INDENT> from pyexcel.utils import yield_from_records <NEW_LINE> return {DEFAULT_SHEET_NAME: yield_from_records(self.records)} <NEW_LINE> <DEDENT> def get_source_info(self): <NEW_LINE> <INDENT> return params.RECORDS, None | A list of dictionaries as data source
The dictionaries should have identical fields. | 6259908855399d3f056280dd |
class ListDisplayVideo360AdvertiserLinksAsyncPager: <NEW_LINE> <INDENT> def __init__( self, method: Callable[ ..., Awaitable[analytics_admin.ListDisplayVideo360AdvertiserLinksResponse] ], request: analytics_admin.ListDisplayVideo360AdvertiserLinksRequest, response: analytics_admin.ListDisplayVideo360AdvertiserLinksResponse, *, metadata: Sequence[Tuple[str, str]] = () ): <NEW_LINE> <INDENT> self._method = method <NEW_LINE> self._request = analytics_admin.ListDisplayVideo360AdvertiserLinksRequest( request ) <NEW_LINE> self._response = response <NEW_LINE> self._metadata = metadata <NEW_LINE> <DEDENT> def __getattr__(self, name: str) -> Any: <NEW_LINE> <INDENT> return getattr(self._response, name) <NEW_LINE> <DEDENT> @property <NEW_LINE> async def pages( self, ) -> AsyncIterator[analytics_admin.ListDisplayVideo360AdvertiserLinksResponse]: <NEW_LINE> <INDENT> yield self._response <NEW_LINE> while self._response.next_page_token: <NEW_LINE> <INDENT> self._request.page_token = self._response.next_page_token <NEW_LINE> self._response = await self._method(self._request, metadata=self._metadata) <NEW_LINE> yield self._response <NEW_LINE> <DEDENT> <DEDENT> def __aiter__(self) -> AsyncIterator[resources.DisplayVideo360AdvertiserLink]: <NEW_LINE> <INDENT> async def async_generator(): <NEW_LINE> <INDENT> async for page in self.pages: <NEW_LINE> <INDENT> for response in page.display_video_360_advertiser_links: <NEW_LINE> <INDENT> yield response <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return async_generator() <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> return "{0}<{1!r}>".format(self.__class__.__name__, self._response) | A pager for iterating through ``list_display_video360_advertiser_links`` requests.
This class thinly wraps an initial
:class:`google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinksResponse` object, and
provides an ``__aiter__`` method to iterate through its
``display_video_360_advertiser_links`` field.
If there are more pages, the ``__aiter__`` method will make additional
``ListDisplayVideo360AdvertiserLinks`` requests and continue to iterate
through the ``display_video_360_advertiser_links`` field on the
corresponding responses.
All the usual :class:`google.analytics.admin_v1alpha.types.ListDisplayVideo360AdvertiserLinksResponse`
attributes are available on the pager. If multiple requests are made, only
the most recent response is retained, and thus used for attribute lookup. | 62599088dc8b845886d55182 |
class ChannelNet(Chain): <NEW_LINE> <INDENT> def __init__(self, channels, block_names, merge_types, dropout_rate=0.0001, multi_blocks=2, groups=2, in_channels=3, in_size=(224, 224), classes=1000): <NEW_LINE> <INDENT> super(ChannelNet, self).__init__() <NEW_LINE> self.in_size = in_size <NEW_LINE> self.classes = classes <NEW_LINE> with self.init_scope(): <NEW_LINE> <INDENT> self.features = SimpleSequential() <NEW_LINE> with self.features.init_scope(): <NEW_LINE> <INDENT> for i, channels_per_stage in enumerate(channels): <NEW_LINE> <INDENT> stage = SimpleSequential() <NEW_LINE> with stage.init_scope(): <NEW_LINE> <INDENT> for j, out_channels in enumerate(channels_per_stage): <NEW_LINE> <INDENT> strides = 2 if (j == 0) else 1 <NEW_LINE> setattr(stage, "unit{}".format(j + 1), ChannetUnit( in_channels=in_channels, out_channels_list=out_channels, strides=strides, multi_blocks=multi_blocks, groups=groups, dropout_rate=dropout_rate, block_names=block_names[i][j], merge_type=merge_types[i][j])) <NEW_LINE> if merge_types[i][j] == "cat": <NEW_LINE> <INDENT> in_channels = sum(out_channels) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> in_channels = out_channels[-1] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> setattr(self.features, "stage{}".format(i + 1), stage) <NEW_LINE> <DEDENT> setattr(self.features, "final_pool", partial( F.average_pooling_2d, ksize=7, stride=1)) <NEW_LINE> <DEDENT> self.output = SimpleSequential() <NEW_LINE> with self.output.init_scope(): <NEW_LINE> <INDENT> setattr(self.output, "flatten", partial( F.reshape, shape=(-1, in_channels))) <NEW_LINE> setattr(self.output, "fc", L.Linear( in_size=in_channels, out_size=classes)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> x = self.features(x) <NEW_LINE> x = self.output(x) <NEW_LINE> return x | ChannelNet model from 'ChannelNets: Compact and Efficient Convolutional Neural Networks via Channel-Wise
Convolutions,' https://arxiv.org/abs/1809.01330.
Parameters:
----------
channels : list of list of list of int
Number of output channels for each unit.
block_names : list of list of list of str
Names of blocks for each unit.
block_names : list of list of str
Merge types for each unit.
dropout_rate : float, default 0.0001
Dropout rate.
multi_blocks : int, default 2
Block count architectural parameter.
groups : int, default 2
Group count architectural parameter.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes. | 62599088fff4ab517ebcf3e0 |
class Notebook: <NEW_LINE> <INDENT> def __init__(self, master=None): <NEW_LINE> <INDENT> self.root = master <NEW_LINE> self.notebook = ttk.Notebook(self.root) <NEW_LINE> s = ttk.Style() <NEW_LINE> s.configure('Red.TLabelframe.Label', background='blue') <NEW_LINE> <DEDENT> def addTab(self, title): <NEW_LINE> <INDENT> self.new_frame = ttk.Frame(self.notebook) <NEW_LINE> self.notebook.add(self.new_frame, text=title) <NEW_LINE> self.notebook.pack(expand=True, fill="both", padx=2, pady=2) <NEW_LINE> <DEDENT> def addLabelFrame(self, title): <NEW_LINE> <INDENT> self.new_label_frame = ttk.LabelFrame(self.new_frame, text=title) <NEW_LINE> self.new_label_frame.grid(column=0, row=0, padx=100, pady=20) <NEW_LINE> <DEDENT> def addLabel(self, text): <NEW_LINE> <INDENT> self.new_label = ttk.Label(self.new_label_frame, text=text+":").grid(column=0, row=0) <NEW_LINE> name = tk.StringVar() <NEW_LINE> self.nameEntered = ttk.Entry(self.new_label_frame, width=12, textvariable=name) <NEW_LINE> self.nameEntered.grid(column=1, row=0) | Create a notebook | 625990883346ee7daa338447 |
class TowerChainsaw(Tower): <NEW_LINE> <INDENT> def find_target(self, creeps): <NEW_LINE> <INDENT> self.target = [] <NEW_LINE> for creep in creeps: <NEW_LINE> <INDENT> if (abs(creep.row - self.row) <= self.range and abs(creep.col - self.col) <= self.range): <NEW_LINE> <INDENT> self.target.append(creep) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def attack(self, creeps): <NEW_LINE> <INDENT> self.find_target(creeps) <NEW_LINE> if self.target: <NEW_LINE> <INDENT> while self.speed_points >= ATTACK_SPEED_POINTS: <NEW_LINE> <INDENT> for target in self.target: <NEW_LINE> <INDENT> target.get_damage(self.damage) <NEW_LINE> <DEDENT> self.speed_points -= ATTACK_SPEED_POINTS <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.speed_points += self.speed <NEW_LINE> <DEDENT> self._next_image() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.image = 0 <NEW_LINE> <DEDENT> <DEDENT> def get_special(self): <NEW_LINE> <INDENT> return 'damage all in range' | Chainsaw tower damage multiple creeps at once. | 625990885fdd1c0f98e5fb43 |
class ManualGrowDialog(QDialog): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.water_spinbox = QSpinBox() <NEW_LINE> self.light_spinbox = QSpinBox() <NEW_LINE> self.water_spinbox.setRange(0,10) <NEW_LINE> self.light_spinbox.setRange(0,10) <NEW_LINE> self.water_spinbox.setSuffix(" Water") <NEW_LINE> self.light_spinbox.setSuffix(" Light") <NEW_LINE> self.water_spinbox.setValue(1) <NEW_LINE> self.light_spinbox.setValue(1) <NEW_LINE> self.submit_button = QPushButton("Enter values") <NEW_LINE> self.dialog_layout = QVBoxLayout() <NEW_LINE> self.dialog_layout.addWidget(self.light_spinbox) <NEW_LINE> self.dialog_layout.addWidget(self.water_spinbox) <NEW_LINE> self.dialog_layout.addWidget(self.submit_button) <NEW_LINE> self.setLayout(self.dialog_layout) <NEW_LINE> self.submit_button.clicked.connect(self.close) <NEW_LINE> <DEDENT> def values(self): <NEW_LINE> <INDENT> return int(self.light_spinbox.value()), int(self.water_spinbox.value()) | This class provides a dialog window to ask for light and water | 625990885fcc89381b266f43 |
class Meta: <NEW_LINE> <INDENT> handler_class = HANDLER_CLASS <NEW_LINE> message_type = DELETE_ROUTES <NEW_LINE> schema_class = "DeleteRoutesSchema" | DeleteRoutes metadata. | 62599088dc8b845886d55184 |
class NumericField(forms.CharField): <NEW_LINE> <INDENT> def to_python(self, raw_value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> raw_value = re.sub('\D', '', raw_value) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return super(NumericField, self).to_python(raw_value) | field to ignore everything except digits - dashes, spaces etc | 62599088283ffb24f3cf546b |
class ProviderUserInfo(UserInfo): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> super(ProviderUserInfo, self).__init__() <NEW_LINE> if not isinstance(data, dict): <NEW_LINE> <INDENT> raise ValueError('Invalid data argument: {0}. Must be a dictionary.'.format(data)) <NEW_LINE> <DEDENT> if not data.get('rawId'): <NEW_LINE> <INDENT> raise ValueError('User ID must not be None or empty.') <NEW_LINE> <DEDENT> self._data = data <NEW_LINE> <DEDENT> @property <NEW_LINE> def uid(self): <NEW_LINE> <INDENT> return self._data.get('rawId') <NEW_LINE> <DEDENT> @property <NEW_LINE> def display_name(self): <NEW_LINE> <INDENT> return self._data.get('displayName') <NEW_LINE> <DEDENT> @property <NEW_LINE> def email(self): <NEW_LINE> <INDENT> return self._data.get('email') <NEW_LINE> <DEDENT> @property <NEW_LINE> def phone_number(self): <NEW_LINE> <INDENT> return self._data.get('phoneNumber') <NEW_LINE> <DEDENT> @property <NEW_LINE> def photo_url(self): <NEW_LINE> <INDENT> return self._data.get('photoUrl') <NEW_LINE> <DEDENT> @property <NEW_LINE> def provider_id(self): <NEW_LINE> <INDENT> return self._data.get('providerId') | Contains metadata regarding how a user is known by a particular identity provider. | 625990887b180e01f3e49e4a |
class CategoryFunctionalMode(GenericCategory): <NEW_LINE> <INDENT> def parse(self, string): <NEW_LINE> <INDENT> self.set_value(string) | This category contains the name of the functional mode
0. name
1. wakeup time from this mode in seconds | 62599088adb09d7d5dc0c125 |
class Meta: <NEW_LINE> <INDENT> model = NPC | Bind model to factory. | 62599088f9cc0f698b1c60b1 |
class ImprovedDisplay(Plugin): <NEW_LINE> <INDENT> enabled = True <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(ImprovedDisplay, self).__init__(*args, **kwargs) <NEW_LINE> self.color_verbose = self.enabled <NEW_LINE> self.easy_copy = self.enabled <NEW_LINE> self.replace_input = self.enabled <NEW_LINE> <DEDENT> def options(self, parser, env): <NEW_LINE> <INDENT> super(ImprovedDisplay, self).options(parser, env) <NEW_LINE> parser.add_option( "--no-color", action="store_false", default=True, dest="color_verbose", help="Disable color in regression tests." ) <NEW_LINE> parser.add_option( "--no-easy-copy", action="store_false", default=True, dest="easy_copy", help="Disable easy copy paste of regression tests." ) <NEW_LINE> parser.add_option( "--np-replace-input", action="store_false", default=True, dest="replace_input", help=("Do not replace input files by their absolute path " "in regression test descriptions.") ) <NEW_LINE> <DEDENT> def configure(self, options, conf): <NEW_LINE> <INDENT> super(ImprovedDisplay, self).configure(options, conf) <NEW_LINE> self.color_verbose = options.color_verbose <NEW_LINE> self.easy_copy = options.easy_copy <NEW_LINE> self.replace_input = options.replace_input <NEW_LINE> try: <NEW_LINE> <INDENT> self.enabled = options.color_verbose or options.easy_copy <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> self.enabled = False <NEW_LINE> <DEDENT> <DEDENT> def describeTest(self, test): <NEW_LINE> <INDENT> args = test.id() <NEW_LINE> if self.easy_copy: <NEW_LINE> <INDENT> args = replace_function(args, self.replace_input) <NEW_LINE> <DEDENT> if self.color_verbose: <NEW_LINE> <INDENT> args = color_arguments(args) <NEW_LINE> <DEDENT> return args <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def report(stream): <NEW_LINE> <INDENT> stream.write('Color is beautiful\n') | Make regression test descriptions easier to read and use. | 625990882c8b7c6e89bd53b2 |
class VirtualMachineScaleSetNetworkConfiguration(SubResource): <NEW_LINE> <INDENT> _validation = { 'name': {'required': True}, 'ip_configurations': {'required': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'primary': {'key': 'properties.primary', 'type': 'bool'}, 'ip_configurations': {'key': 'properties.ipConfigurations', 'type': '[VirtualMachineScaleSetIPConfiguration]'}, } <NEW_LINE> def __init__(self, name, ip_configurations, id=None, primary=None): <NEW_LINE> <INDENT> super(VirtualMachineScaleSetNetworkConfiguration, self).__init__(id=id) <NEW_LINE> self.name = name <NEW_LINE> self.primary = primary <NEW_LINE> self.ip_configurations = ip_configurations | Describes a virtual machine scale set network profile's network
configurations.
:param id: Resource Id
:type id: str
:param name: The network configuration name.
:type name: str
:param primary: Whether this is a primary NIC on a virtual machine.
:type primary: bool
:param ip_configurations: The virtual machine scale set IP Configuration.
:type ip_configurations: list of
:class:`VirtualMachineScaleSetIPConfiguration
<azure.mgmt.compute.v2015_06_15.models.VirtualMachineScaleSetIPConfiguration>` | 62599088656771135c48ae16 |
class Formatter(FormatterBase): <NEW_LINE> <INDENT> DEFAULT_REPLACE = [ (r'\s+' , r' ' ), (r'\s*([^\w\s]+)\s*' , r'\1' ), (r'([,.?!])(\w)' , r'\1 \2' ), (r'([\w,.?!])([[({<])', r'\1 \2' ), (r'([])}>])(\w)' , r'\1 \2' ), (r'(\w)([-+*]+)(\w)' , r'\1 \2 \3'), ] <NEW_LINE> def __init__(self, case=CharCase.TITLE, replace=None, end_chars='.?!', default_end='.'): <NEW_LINE> <INDENT> if replace is None: <NEW_LINE> <INDENT> replace = self.DEFAULT_REPLACE <NEW_LINE> <DEDENT> self.case = int_enum(CharCase, case) <NEW_LINE> self.end_chars = end_chars <NEW_LINE> self.default_end = default_end <NEW_LINE> self.replace = [] <NEW_LINE> for rule in replace: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> expr, repl, flags = rule <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> expr, repl = rule <NEW_LINE> flags = 'u' <NEW_LINE> <DEDENT> flags, custom_flags = re_flags(flags) <NEW_LINE> self.replace.append((re.compile(expr, flags), repl, custom_flags)) <NEW_LINE> <DEDENT> <DEDENT> def save(self): <NEW_LINE> <INDENT> data = super().save() <NEW_LINE> data['case'] = self.case.name <NEW_LINE> data['replace'] = [ (expr.pattern, repl, re_flags_str(expr.flags, flags)) for expr, repl, flags in self.replace ] <NEW_LINE> data['end_chars'] = self.end_chars <NEW_LINE> data['default_end'] = self.default_end <NEW_LINE> return data <NEW_LINE> <DEDENT> def __eq__(self, fmt): <NEW_LINE> <INDENT> return ( self.__class__ is fmt.__class__ and self.case == fmt.case and self.replace == fmt.replace and self.end_chars == fmt.end_chars and self.default_end == fmt.default_end ) <NEW_LINE> <DEDENT> def __call__(self, string): <NEW_LINE> <INDENT> string = lstrip_ws_and_chars(string.rstrip(), self.end_chars) <NEW_LINE> if not string: <NEW_LINE> <INDENT> return string <NEW_LINE> <DEDENT> if self.default_end is not None and string[-1] not in self.end_chars: <NEW_LINE> <INDENT> string += self.default_end <NEW_LINE> <DEDENT> string = self.case.convert(string) <NEW_LINE> for expr, repl, flags in self.replace: <NEW_LINE> <INDENT> string = re_sub(expr, repl, string, custom_flags=flags) <NEW_LINE> <DEDENT> return string | Default formatter.
Attributes
----------
case : `markovchain.text.util.CharCase`
Character case.
replace : `list` of (_sre.SRE_Pattern, `str`, `int`)
List of regular expressions to replace.
end_chars : `str`
Sentence ending characters.
default_end : `None` or `str`
Default sentence ending character. | 625990884c3428357761be86 |
class NopClaim(object): <NEW_LINE> <INDENT> def __init__(self, migration=None): <NEW_LINE> <INDENT> self.migration = migration <NEW_LINE> <DEDENT> @property <NEW_LINE> def disk_gb(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def memory_mb(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def vcpus(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_val, exc_tb): <NEW_LINE> <INDENT> if exc_type is not None: <NEW_LINE> <INDENT> self.abort() <NEW_LINE> <DEDENT> <DEDENT> def abort(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "[Claim: %d MB memory, %d GB disk, %d VCPUS]" % (self.memory_mb, self.disk_gb, self.vcpus) | For use with compute drivers that do not support resource tracking | 625990888a349b6b43687e2a |
class EB_CBLAS(ConfigureMake): <NEW_LINE> <INDENT> def configure_step(self): <NEW_LINE> <INDENT> copy_file('Makefile.LINUX', 'Makefile.in') <NEW_LINE> if not self.cfg['buildopts']: <NEW_LINE> <INDENT> self.cfg.update('buildopts', 'all') <NEW_LINE> <DEDENT> self.cfg.update('buildopts', 'CC="%s"' % os.getenv('CC')) <NEW_LINE> self.cfg.update('buildopts', 'FC="%s"' % os.getenv('F77')) <NEW_LINE> self.cfg.update('buildopts', 'CFLAGS="%s -DADD_"' % os.getenv('CFLAGS')) <NEW_LINE> self.cfg.update('buildopts', 'FFLAGS="%s -DADD_"' % os.getenv('FFLAGS')) <NEW_LINE> blas_lib_dir = os.getenv('BLAS_LIB_DIR') <NEW_LINE> blas_libs = [] <NEW_LINE> for blas_lib in os.getenv('BLAS_STATIC_LIBS').split(','): <NEW_LINE> <INDENT> blas_lib = os.path.join(blas_lib_dir, blas_lib) <NEW_LINE> if os.path.exists(blas_lib): <NEW_LINE> <INDENT> blas_libs.append(blas_lib) <NEW_LINE> <DEDENT> <DEDENT> if get_software_root("imkl"): <NEW_LINE> <INDENT> extra_blas_libs = ['-lmkl_intel_thread', '-lmkl_lapack95_lp64', '-lmkl_intel_lp64', '-lmkl_core'] <NEW_LINE> blas_libs += extra_blas_libs <NEW_LINE> <DEDENT> self.cfg.update('buildopts', 'BLLIB="%s %s"' % (' '.join(blas_libs), os.getenv('LIBS', ''))) <NEW_LINE> <DEDENT> def install_step(self): <NEW_LINE> <INDENT> srcdir = os.path.join(self.cfg['start_dir'], 'lib') <NEW_LINE> targetdir = os.path.join(self.installdir, 'lib') <NEW_LINE> copy_file(os.path.join(srcdir, 'cblas_LINUX.a'), os.path.join(targetdir, 'libcblas.a')) <NEW_LINE> srclib = os.path.join(srcdir, 'libcblas.so') <NEW_LINE> if os.path.exists(srclib): <NEW_LINE> <INDENT> for solib in glob.glob(os.path.join(srcdir, 'libcblas.so*')): <NEW_LINE> <INDENT> copy_file(solib, os.path.join(targetdir, os.path.basename(solib))) <NEW_LINE> <DEDENT> <DEDENT> copy_dir(os.path.join(self.cfg['start_dir'], 'include'), os.path.join(self.installdir, 'include')) <NEW_LINE> <DEDENT> def sanity_check_step(self): <NEW_LINE> <INDENT> custom_paths = { 'files': ['lib/libcblas.a', 'lib/libcblas.%s' % get_shared_lib_ext()], 'dirs': ['include'], } <NEW_LINE> super(EB_CBLAS, self).sanity_check_step(custom_paths=custom_paths) | Support for building CBLAS (BLAS C interface),
inspired by instructions to build CBLAS for ACML, see https://wiki.fysik.dtu.dk/gpaw/install/Linux/vsc.univie.html | 625990884a966d76dd5f0ab2 |
class CourseAccessRole(models.Model): <NEW_LINE> <INDENT> user = models.ForeignKey(User, on_delete=models.CASCADE) <NEW_LINE> org = models.CharField(max_length=64, db_index=True, blank=True) <NEW_LINE> course_id = CourseKeyField(max_length=255, db_index=True, blank=True) <NEW_LINE> role = models.CharField(max_length=64, db_index=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> unique_together = ('user', 'org', 'course_id', 'role') | Maps users to org, courses, and roles. Used by student.roles.CourseRole and OrgRole.
To establish a user as having a specific role over all courses in the org, create an entry
without a course_id. | 62599088a8370b77170f1f99 |
class Member(models.Model): <NEW_LINE> <INDENT> COLLEGES = ( 'McMurtry', 'Martel', 'Brown', 'Duncan', 'Jones', 'Lovett', 'Will Rice', 'Hanzen', 'Sid Rich', 'Baker', 'Wiess' ) <NEW_LINE> first_name = models.CharField(max_length=30) <NEW_LINE> last_name = models.CharField(max_length=30) <NEW_LINE> email = models.EmailField(max_length=100) <NEW_LINE> phone_number = models.IntegerField(blank=True) <NEW_LINE> college = models.CharField(max_length=10) <NEW_LINE> grad_year = models.IntegerField() <NEW_LINE> organization = models.ForeignKey(Organization, on_delete=models.CASCADE) <NEW_LINE> def to_json(self): <NEW_LINE> <INDENT> model_json = {'first_name': self.first_name, 'last_name': self.last_name, 'email': self.email, 'phone_number': self.phone_number, 'college': self.college, 'grad_year': self.grad_year, 'organization': self.organization.name} <NEW_LINE> return model_json <NEW_LINE> <DEDENT> def to_list(self): <NEW_LINE> <INDENT> return [self.first_name, self.last_name, self.email, self.phone_number, self.college, self.grad_year] | This is a model that represent a member in the club. | 625990895fc7496912d49051 |
class TSCrawler(object): <NEW_LINE> <INDENT> def __init__(self, proxy_host=None): <NEW_LINE> <INDENT> self.browser = mechanize.Browser() <NEW_LINE> if proxy_host is not None: <NEW_LINE> <INDENT> self.browser.set_proxies({"http": proxy_host}) <NEW_LINE> <DEDENT> self.cookie = cookielib.LWPCookieJar() <NEW_LINE> self.browser.set_cookiejar(self.cookie) <NEW_LINE> self.browser.set_handle_equiv(True) <NEW_LINE> self.browser.set_handle_redirect(True) <NEW_LINE> self.browser.set_handle_referer(True) <NEW_LINE> self.browser.set_handle_robots(False) <NEW_LINE> self.browser.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) <NEW_LINE> self.browser.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')] <NEW_LINE> <DEDENT> def submit_form_by_dept(self, department_code): <NEW_LINE> <INDENT> self.browser.open('https://www.transparence.sante.gouv.fr') <NEW_LINE> self.browser.follow_link(text="Recherche avancée") <NEW_LINE> self.browser.select_form(nr=0) <NEW_LINE> self.browser.form['form:departementBeneficiaire'] = [department_code] <NEW_LINE> html = self.browser.submit().read() <NEW_LINE> match = re.search('Quelle est la (.*?)è[r|m]e lettre du mot « (.*?) » ?', html, re.S) <NEW_LINE> n, word = match.group(1), match.group(2) <NEW_LINE> word = word.decode('utf-8') <NEW_LINE> answer = word[int(n)-1] <NEW_LINE> self.browser.select_form(nr=0) <NEW_LINE> self.browser.form['j_idt187:captcha'] = answer.encode('utf-8') <NEW_LINE> return self.browser.submit() <NEW_LINE> <DEDENT> def get_detail(self, id): <NEW_LINE> <INDENT> self.browser.select_form(nr=0) <NEW_LINE> if self.browser.form.find_control('j_idt17:dataTable:%s:j_idt80' % id): <NEW_LINE> <INDENT> response = self.browser.submit(name='j_idt17:dataTable:%s:j_idt80' % id) <NEW_LINE> self.browser.select_form(nr=0) <NEW_LINE> self.browser.submit(name='j_idt17:j_idt24') <NEW_LINE> time.sleep(random.random() * 2) <NEW_LINE> return response <NEW_LINE> <DEDENT> <DEDENT> def get_listing_page(self, i): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.browser.select_form(nr=0) <NEW_LINE> self.browser.form.set_all_readonly(False) <NEW_LINE> self.browser.form['j_idt17:j_idt90:%s:j_idt91' % 5] = str( i) <NEW_LINE> self.browser.form['j_idt17'] = 'j_idt17' <NEW_LINE> self.browser.form['javax.faces.ViewState'] = 'e2s2' <NEW_LINE> return self.browser.submit() <NEW_LINE> <DEDENT> except mechanize._form.ControlNotFoundError: <NEW_LINE> <INDENT> info("mechanize error, should be last page") <NEW_LINE> pass | Transparence sante crawler | 6259908992d797404e389943 |
class UnifyModifiersSizeOperator(bpy.types.Operator): <NEW_LINE> <INDENT> bl_idname = "object.unify_modifiers_operator" <NEW_LINE> bl_label = "Unify modifiers" <NEW_LINE> bl_options = {'REGISTER', 'UNDO'} <NEW_LINE> use_names: bpy.props.BoolProperty(name="Use names", default=False) <NEW_LINE> copy_all: bpy.props.BoolProperty(name="Copy all attributes", default=False) <NEW_LINE> @classmethod <NEW_LINE> def poll(cls, context): <NEW_LINE> <INDENT> return (context.space_data.type == 'VIEW_3D' and len(context.selected_objects) > 0 and context.view_layer.objects.active and context.object.mode == 'OBJECT') <NEW_LINE> <DEDENT> def execute(self, context): <NEW_LINE> <INDENT> source = context.view_layer.objects.active <NEW_LINE> targets = list(context.selected_objects) <NEW_LINE> targets.remove(source) <NEW_LINE> source_scale = abs(get_scale(source)) <NEW_LINE> indices = {} <NEW_LINE> for mod in reversed(source.modifiers): <NEW_LINE> <INDENT> if not mod.type in MODS: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> size = getModifierSize(mod, source_scale) <NEW_LINE> indices[mod.type] = indices[mod.type] + 1 if mod.type in indices else 0 <NEW_LINE> if not mod.show_viewport: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> source_index = indices[mod.type] <NEW_LINE> for t in targets: <NEW_LINE> <INDENT> target_scale = abs(get_scale(t)) <NEW_LINE> target_index = 0 <NEW_LINE> for m in reversed(t.modifiers): <NEW_LINE> <INDENT> if m.type == mod.type: <NEW_LINE> <INDENT> do_set_size = self.use_names and m.name == mod.name <NEW_LINE> if not do_set_size and not self.use_names: <NEW_LINE> <INDENT> do_set_size = target_index == source_index <NEW_LINE> <DEDENT> if do_set_size and target_scale != 0: <NEW_LINE> <INDENT> if self.copy_all: <NEW_LINE> <INDENT> copy_modifier(m, mod) <NEW_LINE> <DEDENT> setModifierSize(m, size / target_scale) <NEW_LINE> <DEDENT> target_index += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return {'FINISHED'} | Unify modifiers | 62599089d486a94d0ba2db84 |
class TemporaryWebserver(object): <NEW_LINE> <INDENT> def start(self, repopath): <NEW_LINE> <INDENT> self.httpd = SocketServer.ThreadingTCPServer(("", 0), RequestHandler) <NEW_LINE> self.httpd._cwd = repopath <NEW_LINE> server_thread = threading.Thread(target=self.httpd.serve_forever) <NEW_LINE> server_thread.daemon = True <NEW_LINE> server_thread.start() <NEW_LINE> return self.httpd.server_address[1] <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> del self.httpd | This class is used to control a temporary webserver which is used
by the installer and imagefactory rpm-ostree-toolbox subcommands to get
content from the from the host to the builds | 62599089167d2b6e312b837e |
class RepetitionUnit(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> ordering = [ "name", ] <NEW_LINE> <DEDENT> name = models.CharField(max_length=100, verbose_name=_('Name')) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_owner_object(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_repetition(self): <NEW_LINE> <INDENT> return self.id == 1 | Setting unit, used in combination with an amount such as '10 reps', '5 km' | 625990895fc7496912d49052 |
class AGMetricsTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test_risk(self): <NEW_LINE> <INDENT> ag = testAGs() <NEW_LINE> self.assertTrue(ag[0].risk == 20) <NEW_LINE> self.assertTrue(ag[1].risk == 25) <NEW_LINE> self.assertTrue(ag[2].risk == 25) <NEW_LINE> <DEDENT> def test_cost(self): <NEW_LINE> <INDENT> ag = testAGs() <NEW_LINE> self.assertTrue(ag[0].cost == 20) <NEW_LINE> self.assertTrue(ag[1].cost == 20) <NEW_LINE> self.assertTrue(ag[2].cost == 5) <NEW_LINE> <DEDENT> def test_shortest_path_length(self): <NEW_LINE> <INDENT> ag = testAGs() <NEW_LINE> self.assertTrue(ag[0].shortest_path_length() == 4) <NEW_LINE> self.assertTrue(ag[1].shortest_path_length() == 4) <NEW_LINE> self.assertTrue(ag[2].shortest_path_length() == 1) <NEW_LINE> <DEDENT> def test_mode_path_length(self): <NEW_LINE> <INDENT> ag = testAGs() <NEW_LINE> self.assertTrue(ag[0].mode_path_length() == 4) <NEW_LINE> self.assertTrue(ag[1].mode_path_length() == 5) <NEW_LINE> self.assertTrue(ag[2].mode_path_length() == 5) <NEW_LINE> <DEDENT> def test_mean_path_length(self): <NEW_LINE> <INDENT> ag = testAGs() <NEW_LINE> self.assertTrue(ag[0].mean_path_length() == 4) <NEW_LINE> self.assertTrue(ag[1].mean_path_length() == 4.5) <NEW_LINE> self.assertTrue(ag[2].mean_path_length() == 10.0 / 3.0) | Tests for metrics implemented in attackgraph.py | 62599089ad47b63b2c5a9421 |
class Nonce(models.Model): <NEW_LINE> <INDENT> nonce = models.CharField("NONCE", max_length=16, null=True, blank=True) <NEW_LINE> timestamp = models.DateTimeField("Timestamp", default=current_utc_time) <NEW_LINE> credentials = models.ForeignKey(Credentials) <NEW_LINE> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> self.timestamp = self.timestamp.replace(microsecond=0) <NEW_LINE> super(Nonce, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> timestamp = self.timestamp - datetime.datetime(1970,1,1) <NEW_LINE> timestamp = timestamp.days * 24 * 3600 + timestamp.seconds <NEW_LINE> return u"[{0}/{1}/{2}]".format(self.nonce, timestamp, self.credentials.identifier) | Keeps track of any NONCE combinations that we have used | 62599089e1aae11d1e7cf5fb |
class UserCancelled(TUIException): <NEW_LINE> <INDENT> pass | This class is raised when the user presses ^D in the TUI | 62599089fff4ab517ebcf3e6 |
class VisAttDataset(Dataset): <NEW_LINE> <INDENT> def __init__(self, folder='~/proj/visatt/data/out/'): <NEW_LINE> <INDENT> super(MyDataset, self).__init__() <NEW_LINE> self.folder = folder <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.b - self.a + 1 <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> assert self.a <= index <= self.b <NEW_LINE> return index, index**2 | This dataset contains a list of numbers in the range [a,b] inclusive | 62599089099cdd3c636761e2 |
class TensorBoardLogger(object): <NEW_LINE> <INDENT> def __init__(self, model_dir=None, initial_iter=0, tensorboard_every_n=0, **_unused): <NEW_LINE> <INDENT> self.tensorboard_every_n = tensorboard_every_n <NEW_LINE> self.summary_dir = get_latest_subfolder( os.path.join(model_dir, 'logs'), create_new=initial_iter == 0) <NEW_LINE> self.writer_train = None <NEW_LINE> self.writer_valid = None <NEW_LINE> GRAPH_CREATED.connect(self.init_writer) <NEW_LINE> ITER_STARTED.connect(self.read_tensorboard_op) <NEW_LINE> ITER_FINISHED.connect(self.write_tensorboard) <NEW_LINE> <DEDENT> def init_writer(self, _sender, **_unused_msg): <NEW_LINE> <INDENT> if not self.summary_dir or self.tensorboard_every_n <= 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.writer_train = tf.summary.FileWriter( os.path.join(self.summary_dir, TRAIN), tf.get_default_graph()) <NEW_LINE> self.writer_valid = tf.summary.FileWriter( os.path.join(self.summary_dir, VALID), tf.get_default_graph()) <NEW_LINE> <DEDENT> def read_tensorboard_op(self, sender, **msg): <NEW_LINE> <INDENT> _iter_msg = msg['iter_msg'] <NEW_LINE> if _iter_msg.is_inference: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if not self._is_writing(_iter_msg.current_iter): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> tf_summary_ops = sender.outputs_collector.variables(TF_SUMMARIES) <NEW_LINE> _iter_msg.ops_to_run[TF_SUMMARIES] = tf_summary_ops <NEW_LINE> <DEDENT> def write_tensorboard(self, _sender, **msg): <NEW_LINE> <INDENT> _iter_msg = msg['iter_msg'] <NEW_LINE> if not self._is_writing(_iter_msg.current_iter): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if _iter_msg.is_training: <NEW_LINE> <INDENT> _iter_msg.to_tf_summary(self.writer_train) <NEW_LINE> <DEDENT> elif _iter_msg.is_validation: <NEW_LINE> <INDENT> _iter_msg.to_tf_summary(self.writer_valid) <NEW_LINE> <DEDENT> <DEDENT> def _is_writing(self, c_iter): <NEW_LINE> <INDENT> if self.writer_valid is None or self.writer_train is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not self.summary_dir: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return c_iter % self.tensorboard_every_n == 0 | This class handles iteration events to log summaries to
the TensorBoard log. | 62599089656771135c48ae18 |
class Square(Shape): <NEW_LINE> <INDENT> all_squares =[] <NEW_LINE> def __init__(self, x =0, y =0, side =2): <NEW_LINE> <INDENT> super().__init__(x,y) <NEW_LINE> self.side = side <NEW_LINE> self.__class__.all_squares.append(self) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def total_area(cls): <NEW_LINE> <INDENT> cummulative_area =0 <NEW_LINE> for c in cls.all_squares: <NEW_LINE> <INDENT> cummulative_area+=cls.area(c.side) <NEW_LINE> <DEDENT> return cummulative_area <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def total_perimeter(cls): <NEW_LINE> <INDENT> cummulative_perimeter = 0 <NEW_LINE> for c in cls.all_squares: <NEW_LINE> <INDENT> cummulative_perimeter+=cls.perimeter(c.side) <NEW_LINE> <DEDENT> return cummulative_perimeter <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def area(side1): <NEW_LINE> <INDENT> return math.pow(side1,2) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def perimeter(side1): <NEW_LINE> <INDENT> return 4*side1 | This class describes about the Shape which forms the is a relationship with Shape | 62599089aad79263cf43038a |
class HtmlPrinter(PrettyPrinter): <NEW_LINE> <INDENT> def __init__(self, file_handle, go_to_url = "#", style = _DEFAULT_STYLE): <NEW_LINE> <INDENT> self.handle = file_handle <NEW_LINE> self.go_to_url = go_to_url <NEW_LINE> self.style = style <NEW_LINE> <DEDENT> def write_tag(self, tag, text, attrs = None): <NEW_LINE> <INDENT> self.open_tag(tag, attrs) <NEW_LINE> self.handle.write(text) <NEW_LINE> self.close_tag(tag) <NEW_LINE> <DEDENT> def open_tag(self, tag, attrs = None): <NEW_LINE> <INDENT> ot = "<" + tag <NEW_LINE> if attrs != None: <NEW_LINE> <INDENT> for k, v in attrs.items(): <NEW_LINE> <INDENT> ot += ' {0}="{1}"'.format(k,v) <NEW_LINE> <DEDENT> <DEDENT> ot += ">\n" <NEW_LINE> self.handle.write(ot) <NEW_LINE> <DEDENT> def close_tag(self, tag): <NEW_LINE> <INDENT> self.handle.write("</" + tag + ">\n") <NEW_LINE> <DEDENT> def pretty_print(self, enrichment, graph): <NEW_LINE> <INDENT> self.handle.write("<!DOCTYPE html>") <NEW_LINE> self.open_tag("html") <NEW_LINE> self.open_tag("head") <NEW_LINE> self.handle.write(self.style) <NEW_LINE> self.close_tag("head") <NEW_LINE> self.open_tag("body") <NEW_LINE> self.write_tag("h1", "Enrichments found using {0} method." .format(enrichment.method)) <NEW_LINE> sorted_entries = sorted(enrichment.entries, key = lambda x: x.p_value) <NEW_LINE> self.open_tag("table") <NEW_LINE> self.open_tag("tr") <NEW_LINE> headers = ["ID", "name", "p-value"] <NEW_LINE> for x in enrichment.corrections: <NEW_LINE> <INDENT> if x in corrections_labels: <NEW_LINE> <INDENT> headers.append(corrections_labels[x]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> headers.append(x) <NEW_LINE> <DEDENT> <DEDENT> for header in headers: <NEW_LINE> <INDENT> self.write_tag("th", header) <NEW_LINE> <DEDENT> self.close_tag("tr") <NEW_LINE> for x in sorted_entries: <NEW_LINE> <INDENT> self.open_tag("tr") <NEW_LINE> self.open_tag("td") <NEW_LINE> self.write_tag("a", str(x.id), {"href" : self.go_to_url + str(x.id)}) <NEW_LINE> self.close_tag("td") <NEW_LINE> self.write_tag("td", str(x.name)) <NEW_LINE> self.write_tag("td", str(x.p_value)) <NEW_LINE> for cr in enrichment.corrections: <NEW_LINE> <INDENT> self.write_tag("td", str(x.corrections[cr])) <NEW_LINE> <DEDENT> self.close_tag("tr") <NEW_LINE> <DEDENT> self.close_tag("table") <NEW_LINE> if (len(enrichment.warnings) > 0): <NEW_LINE> <INDENT> self.write_tag("h1", "Warnings:", {"class" : "warning"}) <NEW_LINE> self.open_tag("ul", {"class" : "warning"}) <NEW_LINE> for x in enrichment.warnings: <NEW_LINE> <INDENT> self.write_tag("li", str(x)) <NEW_LINE> <DEDENT> self.close_tag("ul") <NEW_LINE> <DEDENT> self.close_tag("body") <NEW_LINE> self.close_tag("html") | Prints found enrichments to html file. | 625990893617ad0b5ee07d22 |
class Array(Node): <NEW_LINE> <INDENT> icons = {16: images.array_16, 64: images.array_64} <NEW_LINE> @property <NEW_LINE> def shape(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> @property <NEW_LINE> def dtype(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def __getitem__(self, args): <NEW_LINE> <INDENT> raise NotImplementedError | Represents a NumPy-style regular, rectangular array.
Subclasses will be displayed in a spreadsheet-style viewer. | 62599089091ae35668706813 |
class ZeroExpectedError(ValueError): <NEW_LINE> <INDENT> pass | Class for handling tests where an expected value was zero. | 6259908955399d3f056280e5 |
class ILSLocalizerDeviation1500To1000FtMax(KeyPointValueNode): <NEW_LINE> <INDENT> name = 'ILS Localizer Deviation 1500 To 1000 Ft Max' <NEW_LINE> units = ut.DOTS <NEW_LINE> def derive(self, ils_localizer=P('ILS Localizer'), alt_aal=P('Altitude AAL For Flight Phases'), ils_ests=S('ILS Localizer Established')): <NEW_LINE> <INDENT> alt_bands = alt_aal.slices_from_to(1500, 1000) <NEW_LINE> ils_bands = slices_and(alt_bands, ils_ests.get_slices()) <NEW_LINE> self.create_kpvs_within_slices( ils_localizer.array, ils_bands, max_abs_value, ) | Determine maximum deviation from the localizer between 1500 and 1000 ft.
Find where the maximum (absolute) deviation occured and store the actual
value. We can do abs on the statistics to normalise this, but retaining the
sign will make it possible to look for direction of errors at specific
airports. | 6259908923849d37ff852c8b |
class Helper(web.Helper): <NEW_LINE> <INDENT> def is_task(self, task_id, tasks): <NEW_LINE> <INDENT> for t in tasks: <NEW_LINE> <INDENT> if t.id == task_id: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def is_unique(self, id, items): <NEW_LINE> <INDENT> copies = 0 <NEW_LINE> for i in items: <NEW_LINE> <INDENT> if type(i) is dict: <NEW_LINE> <INDENT> if i['id'] == id: <NEW_LINE> <INDENT> copies = copies + 1 <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if i.id == id: <NEW_LINE> <INDENT> copies = copies + 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if copies >= 2: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def del_task_runs(self, app_id=1): <NEW_LINE> <INDENT> db.session.query(model.task_run.TaskRun).filter_by(app_id=app_id).delete() <NEW_LINE> db.session.commit() <NEW_LINE> db.session.query(model.task.Task).filter_by(app_id=app_id) .update({"state": "ongoing"}) <NEW_LINE> db.session.commit() <NEW_LINE> db.session.remove() | Class to help testing the scheduler | 62599089fff4ab517ebcf3e8 |
class MessageHandler(BaseHandler): <NEW_LINE> <INDENT> @CheckPermission(5) <NEW_LINE> async def get(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> limit = self.get_argument('limit', 5) <NEW_LINE> page = self.get_argument('page', 1) <NEW_LINE> total = self.get_argument('total', 0) <NEW_LINE> <DEDENT> except MissingArgumentError as err: <NEW_LINE> <INDENT> return self.write(status=1, msg="参数错误") <NEW_LINE> <DEDENT> res = await Objects.execute(Message.select()) <NEW_LINE> if res: <NEW_LINE> <INDENT> result = [] <NEW_LINE> for resu in res: <NEW_LINE> <INDENT> resul = dict((i, getattr(resu, i)) for i in ["id", "content", "status", "create_time"]) <NEW_LINE> result.append(resul) <NEW_LINE> <DEDENT> self.write(data=result) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.write(status=1, msg="没有消息", data=result) <NEW_LINE> <DEDENT> <DEDENT> @CheckPermission(6) <NEW_LINE> async def post(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> msgid = self.get_argument('msgid') <NEW_LINE> status = self.get_argument('status') <NEW_LINE> <DEDENT> except MissingArgumentError as err: <NEW_LINE> <INDENT> return self.write(status=1, msg="参数错误") <NEW_LINE> <DEDENT> res = await Objects.execute(Message.update(status=status).where(Message.id==msgid)) <NEW_LINE> if res: <NEW_LINE> <INDENT> res = await Objects.execute(Message.select()) <NEW_LINE> result = [] <NEW_LINE> for resu in res: <NEW_LINE> <INDENT> resul = dict((i, getattr(resu, i)) for i in ["id", "content", "status", "create_time"]) <NEW_LINE> result.append(resul) <NEW_LINE> <DEDENT> self.write(msg="操作成功",data=result) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.write(status=1, msg="操作失败") | 系统通知 | 6259908950812a4eaa6219ae |
class IBountyProgramSubmission(Interface): <NEW_LINE> <INDENT> mission = schema.Text( title=_(u"Bounty mission"), required=True, description=_(u"Bounty mission trac ticket #"), ) <NEW_LINE> email = schema.TextLine( title=_(u"Email address"), required=False, ) <NEW_LINE> organization = schema.TextLine( title=_(u"Organization name"), required=False, ) <NEW_LINE> lastName = schema.TextLine( title=_(u"Last name"), required=False, ) <NEW_LINE> firstName = schema.TextLine( title=_(u"First name"), required=False, ) <NEW_LINE> description = schema.TextLine( title=_(u"alt text"), required=False, ) <NEW_LINE> remoteUrl = schema.TextLine( title=_(u"URL"), required=True, ) <NEW_LINE> image = schema.Bytes( title=_(u"Image"), required=True, description=_(u"Image or Logo"), ) | Information for Bounty Program Submission | 62599089aad79263cf43038c |
class TransportProtocolFactory(object): <NEW_LINE> <INDENT> def __init__(self, portal): <NEW_LINE> <INDENT> self.portal = portal <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> return TelnetTransport(AuthenticatingTelnetProtocol, self.portal) | Glues together a portal along with the :class:`TelnetTransport` and
:class:`AuthenticatingTelnetProtocol` objects. This class is instanced
onto the ``protocol`` attribute of the :class:`ServerFactory` class
in :func:`build_manhole`. | 6259908963b5f9789fe86d3b |
class value_set: <NEW_LINE> <INDENT> def available_as_dot_raw_value(self): <NEW_LINE> <INDENT> a = Argument('a') <NEW_LINE> a.value = 'foo' <NEW_LINE> eq_(a.raw_value, 'foo') <NEW_LINE> <DEDENT> def untransformed_appears_as_dot_value(self): <NEW_LINE> <INDENT> a = Argument('a', kind=str) <NEW_LINE> a.value = 'foo' <NEW_LINE> eq_(a.value, 'foo') <NEW_LINE> <DEDENT> def transformed_appears_as_dot_value_with_original_as_raw_value(self): <NEW_LINE> <INDENT> a = Argument('a', kind=int) <NEW_LINE> a.value = '5' <NEW_LINE> eq_(a.value, 5) <NEW_LINE> eq_(a.raw_value, '5') | value= | 62599089d486a94d0ba2db88 |
class KafkaConsumer: <NEW_LINE> <INDENT> def __init__( self, topic_name_pattern, message_handler, is_avro=True, offset_earliest=False, sleep_secs=1.0, consume_timeout=0.1, ): <NEW_LINE> <INDENT> self.topic_name_pattern = topic_name_pattern <NEW_LINE> self.message_handler = message_handler <NEW_LINE> self.sleep_secs = sleep_secs <NEW_LINE> self.consume_timeout = consume_timeout <NEW_LINE> self.offset_earliest = offset_earliest <NEW_LINE> self.broker_properties = { 'BROKER_URL':'PLAINTEXT://localhost:9092', 'SCHEMA_REGISTRY': 'http://localhost:8081', 'KAFKA_REST_PROXY': 'http://localhost:8082' } <NEW_LINE> if is_avro is True: <NEW_LINE> <INDENT> self.broker_properties['SCHEMA_REGISTRY'] = "http://localhost:8081" <NEW_LINE> if offset_earliest is True: <NEW_LINE> <INDENT> self.consumer = AvroConsumer({ 'bootstrap.servers': self.broker_properties['BROKER_URL'], 'group.id': self.topic_name_pattern, 'schema.registry.url': self.broker_properties['SCHEMA_REGISTRY'], 'auto.offset.reset': 'earliest' }) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.consumer = AvroConsumer({ 'bootstrap.servers': self.broker_properties['BROKER_URL'], 'group.id': self.topic_name_pattern, 'schema.registry.url': self.broker_properties['SCHEMA_REGISTRY'] }) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if offset_earliest is True: <NEW_LINE> <INDENT> self.consumer = Consumer({ 'bootstrap.servers': self.broker_properties['BROKER_URL'], 'group.id': self.topic_name_pattern, 'auto.offset.reset': 'earliest' }) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.consumer = Consumer({ 'bootstrap.servers': self.broker_properties['BROKER_URL'], 'group.id': self.topic_name_pattern }) <NEW_LINE> <DEDENT> <DEDENT> self.consumer.subscribe([self.topic_name_pattern], on_assign=self.on_assign) <NEW_LINE> <DEDENT> def on_assign(self, consumer, partitions): <NEW_LINE> <INDENT> for partition in partitions: <NEW_LINE> <INDENT> partition.offset = OFFSET_BEGINNING <NEW_LINE> logger.info("partition offset for topic %s has been set to beginning.", self.topic_name_pattern) <NEW_LINE> <DEDENT> logger.info("partitions assigned for %s", self.topic_name_pattern) <NEW_LINE> consumer.assign(partitions) <NEW_LINE> <DEDENT> async def consume(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> num_results = 1 <NEW_LINE> while num_results > 0: <NEW_LINE> <INDENT> num_results = self._consume() <NEW_LINE> <DEDENT> await gen.sleep(self.sleep_secs) <NEW_LINE> <DEDENT> <DEDENT> def _consume(self): <NEW_LINE> <INDENT> message = self.consumer.poll(self.consume_timeout) <NEW_LINE> if message is None: <NEW_LINE> <INDENT> logger.info("no message received from topic by consumer") <NEW_LINE> return 0 <NEW_LINE> <DEDENT> elif message.error() is not None: <NEW_LINE> <INDENT> logger.error(f"Error from consumer {message.error()}") <NEW_LINE> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.message_handler(message) <NEW_LINE> logger.info(f"consumer recieved message with key {message.key()} value {message.value()}") <NEW_LINE> return 1 <NEW_LINE> <DEDENT> <DEDENT> def close(self): <NEW_LINE> <INDENT> logger.info("closing consumers {}".format(self.topic_name_pattern)) <NEW_LINE> self.consumer.close() | Defines the base kafka consumer class | 62599089fff4ab517ebcf3ea |
class UserProfile(AbstractBaseUser, PermissionsMixin): <NEW_LINE> <INDENT> email = models.EmailField(max_length=255, unique=True) <NEW_LINE> name = models.CharField(max_length=255) <NEW_LINE> is_active = models.BooleanField(default=True) <NEW_LINE> is_staff = models.BooleanField(default=False) <NEW_LINE> objects = UserProfileManager() <NEW_LINE> USERNAME_FIELD = 'email' <NEW_LINE> REQUIRED_FIELDS = ['name'] <NEW_LINE> def get_full_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_short_name(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.email | Request a userfile | 625990892c8b7c6e89bd53ba |
class TestV1AttachedVolume(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testV1AttachedVolume(self): <NEW_LINE> <INDENT> pass | V1AttachedVolume unit test stubs | 6259908999fddb7c1ca63bc6 |
class CT_TextField(BaseOxmlElement): <NEW_LINE> <INDENT> rPr = ZeroOrOne('a:rPr', successors=('a:pPr', 'a:t')) <NEW_LINE> t = ZeroOrOne('a:t', successors=()) <NEW_LINE> @property <NEW_LINE> def text(self): <NEW_LINE> <INDENT> t = self.t <NEW_LINE> if t is None: <NEW_LINE> <INDENT> return u'' <NEW_LINE> <DEDENT> text = t.text <NEW_LINE> return to_unicode(text) if text is not None else u'' | <a:fld> field element, for either a slide number or date field | 62599089d8ef3951e32c8c48 |
class ActiveSensing(Message): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.byte_1 = 0xfe <NEW_LINE> self.byte_2 = 0 <NEW_LINE> self.byte_3 = 0 | This message is intended to be sent repeatedly to tell the receiver that
a connection is alive. Use of this message is optional. When initially
received, the receiver will expect to receive another Active Sensing
message each 300ms (max), and if it does not then it will assume that the
connection has been terminated. At termination, the receiver will turn off
all voices and return to normal (non- active sensing) operation. | 62599089dc8b845886d5518e |
class NotMatch(BaseFn): <NEW_LINE> <INDENT> METHOD_SIG = re.compile(r'notmatch\((.+),\s+(.+)\)') <NEW_LINE> def __init__(self, method=None): <NEW_LINE> <INDENT> args = self.get_args(method) <NEW_LINE> self.term = args[0] <NEW_LINE> self.null = args[1] <NEW_LINE> self.method = method <NEW_LINE> <DEDENT> def _do(self, obj): <NEW_LINE> <INDENT> if str(obj) == str(self.null): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return (str(obj) != self.term) | usage: `notmatch({match_term}, {null_value})`
! White space after commas is required!
result is : True, False or None | 625990894527f215b58eb78a |
class GameManagerTerminal(GameManager): <NEW_LINE> <INDENT> def play(self): <NEW_LINE> <INDENT> print("\n") <NEW_LINE> user_input = "" <NEW_LINE> while user_input.lower() != "q": <NEW_LINE> <INDENT> if self.is_playing: <NEW_LINE> <INDENT> print("\n") <NEW_LINE> if user_input.lower() == "left": <NEW_LINE> <INDENT> self.movement((-1, 0)) <NEW_LINE> <DEDENT> elif user_input.lower() == "right": <NEW_LINE> <INDENT> self.movement((1, 0)) <NEW_LINE> <DEDENT> if user_input.lower() == "up": <NEW_LINE> <INDENT> self.movement((0, -1)) <NEW_LINE> <DEDENT> if user_input.lower() == "down": <NEW_LINE> <INDENT> self.movement((0, 1)) <NEW_LINE> <DEDENT> if user_input.lower() == "r": <NEW_LINE> <INDENT> self.restart() <NEW_LINE> <DEDENT> self.maze.print_level() <NEW_LINE> print("\nYour current position is " + str(self.mcgyver.position)) <NEW_LINE> print("You have " + str(len(self.mcgyver.inventory)) + " item, " + str(len(self.maze.item_list)) + " item remaining\n") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.has_won(): <NEW_LINE> <INDENT> print("You won! That's amazing!\n") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("You lose! You forgot to pick up something, try again.\n") <NEW_LINE> <DEDENT> <DEDENT> user_input = input("Enter a direction to move (up/down/left/right), Q to quit, R to restart\n") | Launches only if the game is played in
terminal mode. | 62599089091ae35668706819 |
class Normalize(object): <NEW_LINE> <INDENT> def __init__(self, normalize_file): <NEW_LINE> <INDENT> self.spoken_normal = {} <NEW_LINE> data_file = open(normalize_file, mode='r', encoding='utf8') <NEW_LINE> reader = csv.reader(data_file) <NEW_LINE> for line in reader: <NEW_LINE> <INDENT> line = line[0].split('\t') <NEW_LINE> self.spoken_normal[line[0]] = line[1] <NEW_LINE> <DEDENT> data_file.close() <NEW_LINE> <DEDENT> def load(self, goal_file): <NEW_LINE> <INDENT> data_file = open(goal_file, 'r', encoding='utf8') <NEW_LINE> new_file = open(goal_file.split('.json')[0] + '_normal.json', 'w', encoding='utf8') <NEW_LINE> for line in data_file: <NEW_LINE> <INDENT> line = json.loads(line) <NEW_LINE> temp_line = copy.deepcopy(line) <NEW_LINE> for symptom, value in temp_line['goal']['implicit_inform_slots'].items(): <NEW_LINE> <INDENT> if symptom in self.spoken_normal.keys(): <NEW_LINE> <INDENT> line['goal']['implicit_inform_slots'][self.spoken_normal[symptom]] = value <NEW_LINE> line['goal']['implicit_inform_slots'].pop(symptom) <NEW_LINE> <DEDENT> <DEDENT> for symptom, value in temp_line['goal']['explicit_inform_slots'].items(): <NEW_LINE> <INDENT> if symptom in self.spoken_normal.keys(): <NEW_LINE> <INDENT> line['goal']['explicit_inform_slots'][self.spoken_normal[symptom]] = value <NEW_LINE> line['goal']['explicit_inform_slots'].pop(symptom) <NEW_LINE> <DEDENT> <DEDENT> new_file.write(json.dumps(line) + '\n') <NEW_LINE> <DEDENT> data_file.close() <NEW_LINE> new_file.close() | 人工对标注得到的症状进行了部分归一。 | 6259908955399d3f056280eb |
class PiecewiseLinearPDFNode(Node): <NEW_LINE> <INDENT> def __init__(self, var, x_range, y_range, norm=1): <NEW_LINE> <INDENT> Node.__init__(self, frozenset({var})) <NEW_LINE> self.var = var <NEW_LINE> self._x_pieces = x_range <NEW_LINE> self._y_pieces = y_range <NEW_LINE> if norm is None: <NEW_LINE> <INDENT> self._Z = numpy.trapz(self._y_pieces, self._x_pieces) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._Z = norm <NEW_LINE> <DEDENT> <DEDENT> def eval(self, input): <NEW_LINE> <INDENT> if input < self._x_pieces[0] or input > self._x_pieces[-1]: <NEW_LINE> <INDENT> self.log_val = LOG_ZERO <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> norm_prob = numpy.interp(x=input, xp=self._x_pieces, yp=self._y_pieces) / self._Z <NEW_LINE> self.log_val = numpy.log(norm_prob) | WRITEME | 62599089dc8b845886d55190 |
class ThrowerAnt(Ant): <NEW_LINE> <INDENT> name = 'Thrower' <NEW_LINE> implemented = True <NEW_LINE> damage = 1 <NEW_LINE> food_cost = 3 <NEW_LINE> min_range = 0 <NEW_LINE> max_range = float('inf') <NEW_LINE> def nearest_bee(self, hive): <NEW_LINE> <INDENT> place = self.place <NEW_LINE> transit = 0 <NEW_LINE> while place != hive and place.entrance != None: <NEW_LINE> <INDENT> if len(place.bees) != 0 and self.min_range <= transit <= self.max_range: <NEW_LINE> <INDENT> return random_or_none(place.bees) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> place = place.entrance <NEW_LINE> transit += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def throw_at(self, target): <NEW_LINE> <INDENT> if target is not None: <NEW_LINE> <INDENT> target.reduce_armor(self.damage) <NEW_LINE> <DEDENT> <DEDENT> def action(self, colony): <NEW_LINE> <INDENT> self.throw_at(self.nearest_bee(colony.hive)) | ThrowerAnt throws a leaf each turn at the nearest Bee in its range. | 625990893346ee7daa33844e |
class _HitObject(_Object, _DetIdStrAdaptor): <NEW_LINE> <INDENT> def __init__(self, tree, index, prefix): <NEW_LINE> <INDENT> super(_HitObject, self).__init__(tree, index, prefix) <NEW_LINE> <DEDENT> def ntracks(self): <NEW_LINE> <INDENT> self._checkIsValid() <NEW_LINE> return getattr(self._tree, self._prefix+"_trkIdx")[self._index].size() <NEW_LINE> <DEDENT> def tracks(self): <NEW_LINE> <INDENT> self._checkIsValid() <NEW_LINE> for itrack in getattr(self._tree, self._prefix+"_trkIdx")[self._index]: <NEW_LINE> <INDENT> yield Track(self._tree, itrack) <NEW_LINE> <DEDENT> <DEDENT> def nseeds(self): <NEW_LINE> <INDENT> self._checkIsValid() <NEW_LINE> return getattr(self._tree, self._prefix+"_seeIdx")[self._index].size() <NEW_LINE> <DEDENT> def seeds(self): <NEW_LINE> <INDENT> self._checkIsValid() <NEW_LINE> for iseed in getattr(self._tree, self._prefix+"_seeIdx")[self._index]: <NEW_LINE> <INDENT> yield Seed(self._tree, iseed) <NEW_LINE> <DEDENT> <DEDENT> def r(self): <NEW_LINE> <INDENT> return math.sqrt(self.x()**2 + self.y()**2) <NEW_LINE> <DEDENT> def r3D(self): <NEW_LINE> <INDENT> return math.sqrt(self.x()**2 + self.y()**2 + self.z()**2) | Adaptor class for pixel/strip hit objects. | 625990895fdd1c0f98e5fb51 |
class IP(TypeDecorator): <NEW_LINE> <INDENT> impl = TypeEngine <NEW_LINE> def load_dialect_impl(self, dialect): <NEW_LINE> <INDENT> if dialect.name == 'postgresql': <NEW_LINE> <INDENT> return dialect.type_descriptor(INET()) <NEW_LINE> <DEDENT> elif dialect.name == 'oracle': <NEW_LINE> <INDENT> return dialect.type_descriptor(OracleRAWLiteral(16)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return dialect.type_descriptor(SQLiteBLOBLiteral()) <NEW_LINE> <DEDENT> <DEDENT> def process_bind_param(self, value, dialect): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if isinstance(value, (IPv4Address, IPv6Address)): <NEW_LINE> <INDENT> if dialect.name == 'postgresql': <NEW_LINE> <INDENT> return text_type(value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(value, IPv6Address): <NEW_LINE> <INDENT> return value.packed <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return struct.pack('!QII', 0, 0xffff, int(value)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> raise TypeError("Unknown input type for IPv4 column: %s" % repr(value)) <NEW_LINE> <DEDENT> def process_result_value(self, value, dialect): <NEW_LINE> <INDENT> if value is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if dialect.name == 'postgresql': <NEW_LINE> <INDENT> return ip_address(text_type(value)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> hi, med, lo = struct.unpack('!QII', value) <NEW_LINE> if hi == 0 and med == 0xffff: <NEW_LINE> <INDENT> return IPv4Address(lo) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return IPv6Address((hi << 64) | (med << 32) | lo) | A type to wrap IP addresses to and from the DB | 6259908992d797404e389948 |
class StubPercentileGetter(object): <NEW_LINE> <INDENT> def __init__(self, performer_percentiles, baseline_percentiles): <NEW_LINE> <INDENT> self._pp = performer_percentiles <NEW_LINE> self._bp = baseline_percentiles <NEW_LINE> <DEDENT> def get_performer_percentiles(self): <NEW_LINE> <INDENT> return self._pp <NEW_LINE> <DEDENT> def get_baseline_percentiles(self): <NEW_LINE> <INDENT> return self._bp | This is a stub percentile getter class intended only for use with these
unit tests. | 6259908963b5f9789fe86d41 |
class PCAProjectionSolver(object): <NEW_LINE> <INDENT> def __init__(self, e, K_inst_cacher, K_th, regul=.1): <NEW_LINE> <INDENT> self.e = e <NEW_LINE> self.q, self.nl = e.shape <NEW_LINE> self.K_inst_cacher = K_inst_cacher <NEW_LINE> self.K_th = K_th <NEW_LINE> self.eTe = e.T @ e <NEW_LINE> self.inv_eTe = spla_chol_invert( self.eTe + regul * np.diag(np.diag(self.eTe)), np.eye(self.nl)) <NEW_LINE> self.H = self.inv_eTe @ e.T <NEW_LINE> self.K_PC_th = self.H.T @ self.K_th @ self.H <NEW_LINE> self.regul = regul * np.ones(self.nl) <NEW_LINE> <DEDENT> def solve_single(self, f, var, mask, a, lam_i0, nodata): <NEW_LINE> <INDENT> if nodata or (mask.mean() > .3): <NEW_LINE> <INDENT> success = False <NEW_LINE> return np.zeros(self.q), .0001 * np.eye(self.q), success <NEW_LINE> <DEDENT> K_PC_inst = self.K_inst_cacher.covwindows.all_K_PCs[lam_i0] <NEW_LINE> fr = 0.5 <NEW_LINE> offdiag = (fr * var[1:] + (1. - fr) * var[:-1]) <NEW_LINE> K_meas = diags([offdiag, var + self.regul, offdiag], [-1, 0, 1]) <NEW_LINE> K_PC_meas = self.H.T @ K_meas @ self.H <NEW_LINE> K_PC = K_PC_inst + K_PC_meas + self.K_PC_th <NEW_LINE> try: <NEW_LINE> <INDENT> A = f @ self.H <NEW_LINE> P_PC = spla_chol_invert(K_PC, np.eye(self.q)) <NEW_LINE> <DEDENT> except (spla.LinAlgError, ValueError): <NEW_LINE> <INDENT> success = False <NEW_LINE> A, P_PC = np.zeros(self.q), 1.0e-4 * np.eye(self.q) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> success = True <NEW_LINE> <DEDENT> return A, P_PC, success | projects data down onto PCs | 62599089d486a94d0ba2db8e |
class BahdanauDecoder(Decoder): <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> super(BahdanauDecoder, self).__init__(config) <NEW_LINE> self.output_size = config.get("n_classes", 32) <NEW_LINE> self.character_distribution = nn.Linear(self.hidden_size, self.output_size) <NEW_LINE> <DEDENT> def forward(self, **kwargs): <NEW_LINE> <INDENT> input = kwargs["input"] <NEW_LINE> prev_hidden = kwargs["prev_hidden"] <NEW_LINE> encoder_outputs = kwargs["encoder_outputs"] <NEW_LINE> seq_len = kwargs.get("seq_len", None) <NEW_LINE> weights = self.attention.forward(prev_hidden, encoder_outputs, seq_len) <NEW_LINE> context = weights.unsqueeze(1).bmm(encoder_outputs).squeeze(1) <NEW_LINE> embedded = self.embedding(input).unsqueeze(0) <NEW_LINE> rnn_input = torch.cat((embedded, context.unsqueeze(0)), 2) <NEW_LINE> outputs, hidden = self.rnn(rnn_input.transpose(1, 0), prev_hidden.unsqueeze(0)) <NEW_LINE> output = self.character_distribution(outputs.squeeze(0)) <NEW_LINE> if self.decoder_output_fn: <NEW_LINE> <INDENT> output = self.decoder_output_fn(output, -1) <NEW_LINE> <DEDENT> if len(output.size()) == 3: <NEW_LINE> <INDENT> output = output.squeeze(1) <NEW_LINE> <DEDENT> return output, hidden.squeeze(0), weights | Corresponds to BahdanauAttnDecoderRNN in Pytorch tutorial | 62599089aad79263cf430393 |
class _callable_dict(dict): <NEW_LINE> <INDENT> def __call__(self): <NEW_LINE> <INDENT> return self.get('T') | Class used with Timer - for returning elapsed time | 62599089dc8b845886d55192 |
class ParameterSearch: <NEW_LINE> <INDENT> def __init__(self, search_config, trainer_config): <NEW_LINE> <INDENT> self.search_config = None <NEW_LINE> self.trainer_config = None <NEW_LINE> self.behavior_name = '' <NEW_LINE> self.hyperparameters = [] <NEW_LINE> self.hyperparameter_sets = [] <NEW_LINE> self.set_search_config(search_config) <NEW_LINE> self.set_trainer_config(trainer_config) <NEW_LINE> <DEDENT> def set_search_config(self, search_config): <NEW_LINE> <INDENT> self.search_config = search_config.copy() <NEW_LINE> self.behavior_name = self.search_config[const.GS_BEHAVIOR_NAME] <NEW_LINE> self.hyperparameters = self.get_search_hyperparameter_names(self.search_config) <NEW_LINE> self.hyperparameter_sets = self.get_hyperparameter_sets(self.search_config) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_search_hyperparameter_names(search_config): <NEW_LINE> <INDENT> return [name for name in search_config[const.GS_SEARCH_PARAMETERS]] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_hyperparameter_sets(search_config): <NEW_LINE> <INDENT> search_sets = [] <NEW_LINE> for _, values in search_config[const.GS_SEARCH_PARAMETERS].items(): <NEW_LINE> <INDENT> search_sets.append(values) <NEW_LINE> <DEDENT> return search_sets <NEW_LINE> <DEDENT> def set_trainer_config(self, trainer_config): <NEW_LINE> <INDENT> self.trainer_config = trainer_config.copy() <NEW_LINE> <DEDENT> def get_trainer_config_with_overrides(self, overrides): <NEW_LINE> <INDENT> result = self.trainer_config.copy() <NEW_LINE> for key, value in overrides.items(): <NEW_LINE> <INDENT> common.add_nested_dict_value(result[const.TC_BEHAVIORS][self.behavior_name], key, value) <NEW_LINE> <DEDENT> if ( const.GS_BUFFER_SIZE_MULTIPLE in result[const.TC_BEHAVIORS][self.behavior_name][const.TC_HYPERPARAMETERS] ): <NEW_LINE> <INDENT> batch_size = self.get_batch_size_value(result, self.behavior_name) <NEW_LINE> result[const.TC_BEHAVIORS][self.behavior_name][const.TC_HYPERPARAMETERS][ const.HP_BUFFER_SIZE ] = ( batch_size * result[const.TC_BEHAVIORS][self.behavior_name][const.TC_HYPERPARAMETERS][ const.GS_BUFFER_SIZE_MULTIPLE ] ) <NEW_LINE> del result[const.TC_BEHAVIORS][self.behavior_name][const.TC_HYPERPARAMETERS][ const.GS_BUFFER_SIZE_MULTIPLE ] <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_batch_size_value(training_config, behavior_name): <NEW_LINE> <INDENT> return training_config[const.TC_BEHAVIORS][behavior_name][const.TC_HYPERPARAMETERS][ const.HP_BATCH_SIZE ] | Object that facilitates performing hyperparameter searches. | 625990893617ad0b5ee07d2c |
Subsets and Splits