code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class ComplexMaterial: <NEW_LINE> <INDENT> def __init__(self, setMaterialsAndWavelength, name): <NEW_LINE> <INDENT> self.__mat = setMaterialsAndWavelength <NEW_LINE> self.__name = name <NEW_LINE> <DEDENT> def get_mat(self): <NEW_LINE> <INDENT> return self.__mat <NEW_LINE> <DEDENT> def get_name(self): <NEW_LINE> <INDENT> return self.__name <NEW_LINE> <DEDENT> def set_mat(self, value): <NEW_LINE> <INDENT> self.__mat = value <NEW_LINE> <DEDENT> def set_name(self, value): <NEW_LINE> <INDENT> self.__name = value <NEW_LINE> <DEDENT> def del_mat(self): <NEW_LINE> <INDENT> del self.__mat <NEW_LINE> <DEDENT> def del_name(self): <NEW_LINE> <INDENT> del self.__name <NEW_LINE> <DEDENT> mat = property(get_mat, set_mat, del_mat, "mat's docstring") <NEW_LINE> name = property(get_name, set_name, del_name, "name's docstring") | This class has got a dictionary of SingleMaterial with his wavelength | 6259905aac7a0e7691f73abe |
class Control(ioctl.Control): <NEW_LINE> <INDENT> magic = BTRFS_IOCTL_MAGIC | A btrfs IOCTL. | 6259905a7047854f4634099c |
class PyCdlibISO9660(object): <NEW_LINE> <INDENT> __slots__ = ('pycdlib_obj',) <NEW_LINE> def __init__(self, pycdlib_obj): <NEW_LINE> <INDENT> self.pycdlib_obj = pycdlib_obj <NEW_LINE> <DEDENT> def get_file_from_iso(self, local_path, iso_path): <NEW_LINE> <INDENT> self.pycdlib_obj.get_file_from_iso(local_path, iso_path=iso_path) <NEW_LINE> <DEDENT> def get_file_from_iso_fp(self, outfp, iso_path): <NEW_LINE> <INDENT> self.pycdlib_obj.get_file_from_iso_fp(outfp, iso_path=iso_path) <NEW_LINE> <DEDENT> def add_fp(self, fp, length, iso_path): <NEW_LINE> <INDENT> rr_name = None <NEW_LINE> if self.pycdlib_obj.has_rock_ridge(): <NEW_LINE> <INDENT> rr_name = iso_path_to_rr_name(iso_path, self.pycdlib_obj.interchange_level, False) <NEW_LINE> <DEDENT> self.pycdlib_obj.add_fp(fp, length, iso_path=iso_path, rr_name=rr_name) <NEW_LINE> <DEDENT> def add_file(self, filename, iso_path): <NEW_LINE> <INDENT> rr_name = None <NEW_LINE> if self.pycdlib_obj.has_rock_ridge(): <NEW_LINE> <INDENT> rr_name = iso_path_to_rr_name(iso_path, self.pycdlib_obj.interchange_level, False) <NEW_LINE> <DEDENT> self.pycdlib_obj.add_file(filename, iso_path=iso_path, rr_name=rr_name) <NEW_LINE> <DEDENT> def add_directory(self, iso_path): <NEW_LINE> <INDENT> rr_name = None <NEW_LINE> if self.pycdlib_obj.has_rock_ridge(): <NEW_LINE> <INDENT> rr_name = iso_path_to_rr_name(iso_path, self.pycdlib_obj.interchange_level, True) <NEW_LINE> <DEDENT> self.pycdlib_obj.add_directory(iso_path=iso_path, rr_name=rr_name) <NEW_LINE> <DEDENT> def rm_file(self, iso_path): <NEW_LINE> <INDENT> self.pycdlib_obj.rm_file(iso_path=iso_path) <NEW_LINE> <DEDENT> def rm_directory(self, iso_path): <NEW_LINE> <INDENT> self.pycdlib_obj.rm_directory(iso_path=iso_path) <NEW_LINE> <DEDENT> def list_children(self, iso_path): <NEW_LINE> <INDENT> return self.pycdlib_obj.list_children(iso_path=iso_path) <NEW_LINE> <DEDENT> def get_record(self, iso_path): <NEW_LINE> <INDENT> ret = self.pycdlib_obj.get_record(iso_path=iso_path) <NEW_LINE> if not isinstance(ret, dr.DirectoryRecord): <NEW_LINE> <INDENT> raise pycdlibexception.PyCdlibInternalError('Invalid return type from get_record') <NEW_LINE> <DEDENT> return ret <NEW_LINE> <DEDENT> def walk(self, iso_path): <NEW_LINE> <INDENT> return self.pycdlib_obj.walk(iso_path=iso_path) <NEW_LINE> <DEDENT> def open_file_from_iso(self, iso_path): <NEW_LINE> <INDENT> return self.pycdlib_obj.open_file_from_iso(iso_path=iso_path) | The class representing the PyCdlib ISO9660 facade. | 6259905a435de62698e9d3e0 |
class UserChangeForm(forms.ModelForm): <NEW_LINE> <INDENT> password = ReadOnlyPasswordHashField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> model = MyUser <NEW_LINE> fields = ('username', 'password', 'is_active', 'is_admin') <NEW_LINE> <DEDENT> def clean_password(self): <NEW_LINE> <INDENT> return self.initial["password"] | A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field. | 6259905aa17c0f6771d5d690 |
class Logger(object): <NEW_LINE> <INDENT> logFile="logFile.txt" <NEW_LINE> @staticmethod <NEW_LINE> def writeAndPrintLine(text, errorLevel): <NEW_LINE> <INDENT> message=Logger.getTimeStamp()+' '+Logger.getErrorString(errorLevel)+':\t'+text <NEW_LINE> file=open(Logger.logFile, "a") <NEW_LINE> file.write(message+'\n') <NEW_LINE> file.close() <NEW_LINE> print(message) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def writeAndPrintLineFile(text, file, errorLevel): <NEW_LINE> <INDENT> message=Logger.getTimeStamp()+' '+Logger.getErrorString(errorLevel)+':\t'+text <NEW_LINE> file=open(file, "a") <NEW_LINE> file.write(message+'\n') <NEW_LINE> file.close() <NEW_LINE> print(message) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def getErrorString(errLevel): <NEW_LINE> <INDENT> return {0 : "[SYSTEM]", 1 : "[INFO]", 2 : "[WARNING]", 3 : "[ERROR]", 4 : "[FATAL]", 5 : "[DEBUG]" }.get(errLevel, "[UNKNOWN]") <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def getTimeStamp(): <NEW_LINE> <INDENT> return str(time.strftime('%Y-%m-%d %H:%M:%S')) | description of class | 6259905aadb09d7d5dc0bb47 |
class RescaleTransformTest(ClassTest): <NEW_LINE> <INDENT> def define_tests(self, dataset, range_): <NEW_LINE> <INDENT> min_, max_ = range_ <NEW_LINE> return [ RescaleTransformTestMin(dataset, min_), RescaleTransformTestMax(dataset, max_), ] <NEW_LINE> <DEDENT> def define_class_name(self): <NEW_LINE> <INDENT> return "RescaleTransform" | Test class RescaleTransform | 6259905a8a43f66fc4bf376a |
class RateLimit(object): <NEW_LINE> <INDENT> def __init__(self, verb, uri, regex, value, remain, unit, next_available): <NEW_LINE> <INDENT> self.verb = verb <NEW_LINE> self.uri = uri <NEW_LINE> self.regex = regex <NEW_LINE> self.value = value <NEW_LINE> self.remain = remain <NEW_LINE> self.unit = unit <NEW_LINE> self.next_available = next_available <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.uri == other.uri and self.regex == other.regex and self.value == other.value and self.verb == other.verb and self.remain == other.remain and self.unit == other.unit and self.next_available == other.next_available <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return "<RateLimit: verb=%s uri=%s>" % (self.verb, self.uri) | Data model that represents a flattened view of a single rate limit. | 6259905a21bff66bcd724242 |
class CustomIndexDashboard(Dashboard): <NEW_LINE> <INDENT> def init_with_context(self, context): <NEW_LINE> <INDENT> site_name = get_admin_site_name(context) <NEW_LINE> self.children.append(modules.ModelList( _('User Administration'), column=1, collapsible=False, models=('django.contrib.auth.*',) ), ) <NEW_LINE> self.children.append(modules.AppList( _('FixMyCity Management'), collapsible=False, column=1, models=('api.*', 'sapi.*',), exclude=('api.models.Rating', 'api.models.Photo', 'api.models.Address', 'api.models.Comment',), )) <NEW_LINE> self.children.append(modules.ModelList( _('Social Authentication Module'), collapsible=True, column=1, css_classes=('collapse closed',), models=('social_auth.*',), )) <NEW_LINE> self.children.append(modules.ModelList( _('Asynchronous Task Queue'), collapsible=True, column=1, css_classes=('collapse closed',), models=('djcelery.*',), )) <NEW_LINE> self.children.append(modules.AppList( _('Miscellaneous'), collapsible=True, column=1, css_classes=('collapse closed',), exclude=('django.contrib.auth.*', 'sapi.*', 'social_auth.*', 'api.*', 'djcelery.*',), )) <NEW_LINE> self.children.append(modules.LinkList( _('Support'), column=2, children=[ { 'title': _('FixMyCity Website'), 'url': 'http://www.fixmycity.de/', 'external': True, }, { 'title': _('FixMyCity Android App'), 'url': '/static/FixMyCity.apk', 'external': True, }, { 'title': _('Django Documentation'), 'url': 'http://docs.djangoproject.com/', 'external': True, }, { 'title': _('Grappelli Documentation'), 'url': 'http://packages.python.org/django-grappelli/', 'external': True, }, { 'title': _('Grappelli Google-Code'), 'url': 'http://code.google.com/p/django-grappelli/', 'external': True, }, ] )) <NEW_LINE> self.children.append(modules.Feed( _('e-Government News'), column=2, feed_url='http://www.guardian.co.uk/technology/e-government/rss', limit=5 )) <NEW_LINE> self.children.append(modules.RecentActions( _('Recent Actions'), limit=5, collapsible=False, column=3, )) | Custom index dashboard for www. | 6259905abe8e80087fbc0660 |
class RegisterClass(): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def getProfile(self, entryList): <NEW_LINE> <INDENT> custParms = [] <NEW_LINE> for i in entryList: <NEW_LINE> <INDENT> custParms.append(i.get()) <NEW_LINE> <DEDENT> custLogic = Customer(**custParms) <NEW_LINE> custLogic.setCustDb() <NEW_LINE> profTab = tkinter.Tk() <NEW_LINE> profTab.title('Customer Info shuld be saved on DB') <NEW_LINE> nameLabel = tkinter.Label(profTab, text='Name '+str(custLogic.name)) <NEW_LINE> nameLabel.pack() <NEW_LINE> profTab.mainloop <NEW_LINE> <DEDENT> def askInfo(self, mainForm): <NEW_LINE> <INDENT> registerTab = tkinter.Toplevel(mainForm) <NEW_LINE> registerTab.after(1, lambda: registerTab.focus_force()) <NEW_LINE> registerTab.title('Please provide your information') <NEW_LINE> nameEntry = tkinter.Entry(registerTab) <NEW_LINE> nameLabel = tkinter.Label(registerTab, text='Name') <NEW_LINE> lastNameEntry = tkinter.Entry(registerTab,) <NEW_LINE> lastNameLabel = tkinter.Label(registerTab, text='Last name') <NEW_LINE> phoneEntry = tkinter.Entry(registerTab) <NEW_LINE> phoneLabel = tkinter.Label(registerTab, text='Phone') <NEW_LINE> addressEntry = tkinter.Entry(registerTab) <NEW_LINE> addressLabel = tkinter.Label(registerTab, text='Address ') <NEW_LINE> userEntry = tkinter.Entry(registerTab) <NEW_LINE> userLabel = tkinter.Label(registerTab, text='P ') <NEW_LINE> passwordEntry = tkinter.Entry(registerTab) <NEW_LINE> passwordLabel = tkinter.Label(registerTab, text='Address ') <NEW_LINE> entryList = [nameEntry, lastNameEntry, phoneEntry, addressEntry] <NEW_LINE> registerBtn = tkinter.Button(registerTab, text='Save ', command=lambda: self.getProfile(entryList)) <NEW_LINE> nameEntry.pack() <NEW_LINE> nameLabel.pack() <NEW_LINE> lastNameEntry.pack() <NEW_LINE> lastNameLabel.pack() <NEW_LINE> phoneEntry.pack() <NEW_LINE> phoneLabel.pack() <NEW_LINE> addressEntry.pack() <NEW_LINE> addressLabel.pack() <NEW_LINE> registerBtn.pack() <NEW_LINE> return (registerTab) | This class models the Register for new customers. Takes customer
information and validates customer via email or cellphone | 6259905aa219f33f346c7de2 |
class JwtPublicKeySignInternal(metaclass=abc.ABCMeta): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def sign_and_encode_with_kid(self, token: _raw_jwt.RawJwt, kid: Optional[str]) -> str: <NEW_LINE> <INDENT> raise NotImplementedError() | Internal interface for creating a signed JWT.
"kid" is an optional value that is set by the wrapper for keys with output
prefix TINK, and it is set to None for output prefix RAW. | 6259905a99cbb53fe68324bd |
class SpokeKVConn: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.config = config.setup() <NEW_LINE> self.log = logger.setup(__name__) <NEW_LINE> self.kv_host = self.config.get('KV', 'kv_host') <NEW_LINE> self.kv_port = int(self.config.get('KV', 'kv_port', 6379)) <NEW_LINE> self.kv_db = self.config.get('KV', 'kv_db', '0') <NEW_LINE> try: <NEW_LINE> <INDENT> self.KV = redis.StrictRedis(host=self.kv_host, port=self.kv_port, db=self.kv_db) <NEW_LINE> self.KV.keys() <NEW_LINE> <DEDENT> except redis.exceptions.ConnectionError: <NEW_LINE> <INDENT> msg = 'Connection to Redis server %s:%s as %s failed' % (self.kv_host, self.kv_port, self.kv_db) <NEW_LINE> trace = traceback.format_exc() <NEW_LINE> raise error.RedisError(msg, trace) | Class representing Redis server connection. | 6259905a07f4c71912bb0a18 |
class AutoscalingModule(_messages.Message): <NEW_LINE> <INDENT> coolDownPeriodSec = _messages.IntegerField(1, variant=_messages.Variant.INT32) <NEW_LINE> description = _messages.StringField(2) <NEW_LINE> maxNumReplicas = _messages.IntegerField(3, variant=_messages.Variant.INT32) <NEW_LINE> minNumReplicas = _messages.IntegerField(4, variant=_messages.Variant.INT32) <NEW_LINE> signalType = _messages.StringField(5) <NEW_LINE> targetModule = _messages.StringField(6) <NEW_LINE> targetUtilization = _messages.FloatField(7) | A AutoscalingModule object.
Fields:
coolDownPeriodSec: A integer attribute.
description: A string attribute.
maxNumReplicas: A integer attribute.
minNumReplicas: A integer attribute.
signalType: A string attribute.
targetModule: A string attribute.
targetUtilization: target_utilization should be in range [0,1]. | 6259905a3cc13d1c6d466d1d |
class ScanNet(Dataset): <NEW_LINE> <INDENT> def __init__(self, io, dataroot, partition='train'): <NEW_LINE> <INDENT> self.partition = partition <NEW_LINE> self.data, self.label = load_data_h5py_scannet10(self.partition, dataroot) <NEW_LINE> self.num_examples = self.data.shape[0] <NEW_LINE> if partition == "train": <NEW_LINE> <INDENT> self.train_ind = np.asarray([i for i in range(self.num_examples) if i % 10 < 8]).astype(np.int) <NEW_LINE> np.random.shuffle(self.train_ind) <NEW_LINE> self.val_ind = np.asarray([i for i in range(self.num_examples) if i % 10 >= 8]).astype(np.int) <NEW_LINE> np.random.shuffle(self.val_ind) <NEW_LINE> <DEDENT> io.cprint("number of " + partition + " examples in scannet" + ": " + str(self.data.shape[0])) <NEW_LINE> unique, counts = np.unique(self.label, return_counts=True) <NEW_LINE> io.cprint("Occurrences count of classes in scannet " + partition + " set: " + str(dict(zip(unique, counts)))) <NEW_LINE> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> pointcloud = np.copy(self.data[item])[:, :3] <NEW_LINE> label = np.copy(self.label[item]) <NEW_LINE> pointcloud = scale_to_unit_cube(pointcloud) <NEW_LINE> pointcloud = self.rotate_pc(pointcloud) <NEW_LINE> if pointcloud.shape[0] > NUM_POINTS: <NEW_LINE> <INDENT> pointcloud = np.swapaxes(np.expand_dims(pointcloud, 0), 1, 2) <NEW_LINE> _, pointcloud = farthest_point_sample_np(pointcloud, NUM_POINTS) <NEW_LINE> pointcloud = np.swapaxes(pointcloud.squeeze(), 1, 0).astype('float32') <NEW_LINE> <DEDENT> if self.partition == 'train' and item not in self.val_ind: <NEW_LINE> <INDENT> pointcloud = jitter_pointcloud(random_rotate_one_axis(pointcloud, "z")) <NEW_LINE> <DEDENT> return (pointcloud, label) <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return self.data.shape[0] <NEW_LINE> <DEDENT> def rotate_pc(self, pointcloud): <NEW_LINE> <INDENT> pointcloud = rotate_shape(pointcloud, 'x', -np.pi / 2) <NEW_LINE> return pointcloud | scannet dataset for pytorch dataloader | 6259905a15baa7234946356f |
class StoryList(BaseListAPIView): <NEW_LINE> <INDENT> serializer_class = StoryReadSerializer <NEW_LINE> model = Story | This endpoint allows you to list stories.
## Listing stories
By making a ```GET``` request you can list all the stories for an organization, filtering them as needed. Each
story has the following attributes:
* **id** - the ID of the story (int)
* **title** - the TITLE of the story (string)
* **featured** - whether the story if FEATURED or not (boolean)
* **org** - the ID of the org that owns this story (int)
* **summary** - the summary of the story (string)
* **content** - the content of the story (string), this can be containing HTML code data as the content is managed as WYSIWYG
* **video_id** - YouTube ID of the video in this story (string)
* **audio_link** - the AUDIO_LINK in this story (string)
* **tags** - the TAGS in this story (string)
* **images** - the IMAGES in this story (list of strings)
* **category** - the CATEGORY of the asset (dictionary)
Example:
GET /api/v1/stories/org/1/
Response is the list of stories of the organisation, most recent first:
{
"count": 389,
"next": "/api/v1/stories/org/1/?page=2",
"previous": null,
"results": [
{
"id": 1,
"title": "Test Story",
"featured": true,
"summary": "This is the summary of the story.",
"content": "This is the <b>content</b> of the story.",
"video_id": "",
"audio_link": null,
"tags": " test, story ",
"org": 1,
"images": [
"http://test.ureport.in/media/stories/StraightOuttaSomewhere_1.jpg",
"http://test.ureport.in/media/stories/StraightOuttaSomewhere.jpg"
],
"category": {
"image_url": "http://test.ureport.in/media/categories/StraightOuttaSomewhere_2.jpg",
"name": "tests"
}
},
...
}
If you want to get stories with only specific attributes:
Example:
GET /api/v1/stories/org/{org}/?fields=title,content
Response is stories with only title and content attributes.
If you want to get stories without specific attributes:
Example:
GET /api/v1/stories/org/{org}/?exclude=title,content
Response is stories without title and content attributes. | 6259905a63d6d428bbee3d76 |
class ScreenRecord(AbstractTimestampTrashBinModel): <NEW_LINE> <INDENT> case = models.ForeignKey(Case, related_name='screens', on_delete=models.CASCADE) <NEW_LINE> name = models.CharField("screen name", max_length=40) <NEW_LINE> start_time = models.DateTimeField(default=now) <NEW_LINE> end_time = models.DateTimeField(null=True, blank=True) <NEW_LINE> button = models.CharField( help_text="Button the operator pressed to finish the screen", choices=BUTTON_CHOICES, max_length=10, blank=True, ) <NEW_LINE> input = models.CharField( help_text="Input field from screen", blank=True, default='', max_length=80, ) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = _("screen record") <NEW_LINE> verbose_name_plural = _("screen records") <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def end(self, case, button=None, input=None): <NEW_LINE> <INDENT> self.button = button or '' <NEW_LINE> self.input = input or '' <NEW_LINE> self.end_time = now() <NEW_LINE> self.save() <NEW_LINE> case.current_screen = None <NEW_LINE> case.save() | A record of each screen that was visited during the call,
and the operator's input. | 6259905ae76e3b2f99fd9fdc |
class TestFusion(unittest.TestCase): <NEW_LINE> <INDENT> def test_fusion_command(self): <NEW_LINE> <INDENT> gtf_file = '/'.join([ '/cluster/projects/carlsgroup/workinprogress/abdel', '20170418_INSPIRE_RNA/gencode.v26.annotation.gtf' ]) <NEW_LINE> fusions = get_fusions( junction='STAR/LTS-035_T_RNA_GCCAAT_L007Chimeric.out.junction', prefix='STAR_fusion/LTS-035_T_RNA_GCCAAT_L007', out_sam='STAR/LTS-035_T_RNA_GCCAAT_L007Chimeric.out.sam', gtf=gtf_file) <NEW_LINE> expected_command = " ".join([ 'STAR-Fusion', '--chimeric_junction STAR/LTS-035_T_RNA_GCCAAT_L007Chimeric.out.junction', '--chimeric_out_sam STAR/LTS-035_T_RNA_GCCAAT_L007Chimeric.out.sam', '--ref_GTF', gtf_file, '--out_prefix STAR_fusion/LTS-035_T_RNA_GCCAAT_L007']) <NEW_LINE> self.assertEqual(fusions['command'], expected_command) | A simple test class. | 6259905a9c8ee82313040c79 |
class Structure(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=256, verbose_name=_(u"Nom")) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = _(u"Structure") <NEW_LINE> verbose_name_plural = _(u"Structures") <NEW_LINE> ordering = ['name'] <NEW_LINE> permissions = (("can_bypass_structure", _("Can bypass structure")),) | Represents an organisational structure, to which users are related. | 6259905a379a373c97d9a602 |
class Update(_UpdateBase): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> @staticmethod <NEW_LINE> def from_dict(message_update): <NEW_LINE> <INDENT> if message_update is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return Update(message_update.get('update_id'), Message.from_result(message_update.get('message')), InlineQuery.from_result(message_update.get('inline_query')), ChosenInlineResult.from_result(message_update.get('chosen_inline_result'))) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_result(result): <NEW_LINE> <INDENT> if result is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return [Update.from_dict(message_update) for message_update in result] | This object represents an incoming update.
Attributes:
update_id (int) :The update‘s unique identifier. Update identifiers start from a certain
positive number and increase sequentially. This ID becomes especially handy
if you’re using Webhooks, since it allows you to ignore repeated updates or to
restore the correct update sequence, should they get out of order.
message (Message) :*Optional.* New incoming message of any kind — text, photo, sticker, etc.
inline_query (InlineQuery) :*Optional.* New incoming inline query
chosen_inline_result (ChosenInlineResult) :*Optional.* The result of a inline query that was chosen by
a user and sent to their chat partner | 6259905aac7a0e7691f73ac0 |
class Corr2d: <NEW_LINE> <INDENT> def __init__(self, data, labels=None, **kw): <NEW_LINE> <INDENT> if labels == None: <NEW_LINE> <INDENT> labels = ["P"+str(i+1) for i,_ in enumerate(data)] <NEW_LINE> <DEDENT> self.N = len(data) <NEW_LINE> self.labels = labels <NEW_LINE> self.data = data <NEW_LINE> self.hists = _hists(data, **kw) <NEW_LINE> <DEDENT> def R(self): <NEW_LINE> <INDENT> return numpy.corrcoef(self.data) <NEW_LINE> <DEDENT> def __getitem__(self, i, j): <NEW_LINE> <INDENT> return self.hists[i,j] <NEW_LINE> <DEDENT> def plot(self, title=None): <NEW_LINE> <INDENT> import pylab <NEW_LINE> fig = pylab.gcf() <NEW_LINE> if title != None: <NEW_LINE> <INDENT> fig.text(0.5, 0.95, title, horizontalalignment='center', fontproperties=FontProperties(size=16)) <NEW_LINE> <DEDENT> self.ax = _plot(fig, self.hists, self.labels, self.N) | Generate and manage 2D correlation histograms. | 6259905a435de62698e9d3e2 |
class GraphObjectFactory(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def create(object_name, *args, **kwargs): <NEW_LINE> <INDENT> is_array = object_name in graph_reference.ARRAYS <NEW_LINE> is_object = object_name in graph_reference.OBJECTS <NEW_LINE> if not (is_array or is_object): <NEW_LINE> <INDENT> raise exceptions.PlotlyError( "'{}' is not a valid object name.".format(object_name) ) <NEW_LINE> <DEDENT> class_name = graph_reference.OBJECT_NAME_TO_CLASS_NAME.get(object_name) <NEW_LINE> if class_name in ['Figure', 'Data', 'Frames']: <NEW_LINE> <INDENT> return globals()[class_name](*args, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> kwargs['_name'] = object_name <NEW_LINE> if is_array: <NEW_LINE> <INDENT> return PlotlyList(*args, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return PlotlyDict(*args, **kwargs) | GraphObject creation in this module should run through this factory. | 6259905a379a373c97d9a603 |
class ProjectBuildJobsResource(Resource): <NEW_LINE> <INDENT> @jwt_required <NEW_LINE> def get(self, project_id): <NEW_LINE> <INDENT> permissions.check_admin_permissions() <NEW_LINE> projects_service.get_project(project_id) <NEW_LINE> return playlists_service.get_build_jobs_for_project(project_id) | Retrieve all build jobs related to given project.
It's mainly used for synchronisation purpose. | 6259905a30dc7b76659a0d6f |
class NotFound(Exception): <NEW_LINE> <INDENT> pass | Raise when stats could not be found | 6259905a01c39578d7f14226 |
class GpVarDiagView(GpMeanVarBaseView): <NEW_LINE> <INDENT> _route_name = GP_VAR_DIAG_ROUTE_NAME <NEW_LINE> _pretty_route_name = GP_VAR_DIAG_PRETTY_ROUTE_NAME <NEW_LINE> response_schema = GpVarDiagResponse() <NEW_LINE> @view_config(route_name=_pretty_route_name, renderer=PRETTY_RENDERER) <NEW_LINE> def pretty_view(self): <NEW_LINE> <INDENT> return self.pretty_response() <NEW_LINE> <DEDENT> @view_config(route_name=_route_name, renderer='json', request_method='POST') <NEW_LINE> def gp_var_diag_view(self): <NEW_LINE> <INDENT> return self.form_response( self.gp_mean_var_response_dict(compute_mean=False, compute_var=True, var_diag=True) ) | Views for gp_var_diag endpoints. | 6259905ad99f1b3c44d06c80 |
class MockedConnectionTest(unittest.TestCase): <NEW_LINE> <INDENT> nsqd_ports = (12345, 12346) <NEW_LINE> def setUp(self): <NEW_LINE> <INDENT> with mock.patch('nsq.client.connection.Connection', MockConnection): <NEW_LINE> <INDENT> hosts = ['localhost:%s' % port for port in self.nsqd_ports] <NEW_LINE> self.client = Client(nsqd_tcp_addresses=hosts) <NEW_LINE> self.connections = self.client.connections() | Create a client with mocked connection objects | 6259905a2ae34c7f260ac6c6 |
class QueryParseException(Exception): <NEW_LINE> <INDENT> pass | Raised by parse_query() when a query is invalid. | 6259905aadb09d7d5dc0bb49 |
class OperationalError(exceptions.SQLOperationalError): <NEW_LINE> <INDENT> pass | Exception raised for errors that are related to the database's
operation and not necessarily under the control of the programmer,
e.g. an unexpected disconnect occurs, the data source name is not
found, a transaction could not be processed, a memory allocation
error occurred during processing, etc. | 6259905a8e71fb1e983bd0a9 |
class Format(object): <NEW_LINE> <INDENT> def __init__(self, name, acronym, extensions, content_types): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.acronym = acronym <NEW_LINE> self.extensions = extensions <NEW_LINE> self.content_types = content_types <NEW_LINE> <DEDENT> @property <NEW_LINE> def extension(self): <NEW_LINE> <INDENT> return self.extensions[0] <NEW_LINE> <DEDENT> @property <NEW_LINE> def content_type(self): <NEW_LINE> <INDENT> return self.content_types[0] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name | A format represents a file format. | 6259905aa219f33f346c7de4 |
class ImageTestCases(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> funny = Category(name = "funny") <NEW_LINE> funny.save() <NEW_LINE> africa = Location(name = "Africa") <NEW_LINE> africa.save() <NEW_LINE> self.new_image = Image(name = "image",description = "h",location = africa,category = funny) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> Image.objects.all().delete() <NEW_LINE> Category.objects.all().delete() <NEW_LINE> Location.objects.all().delete() <NEW_LINE> <DEDENT> def test_instance(self): <NEW_LINE> <INDENT> self.assertTrue(isinstance(self.new_image, Image)) <NEW_LINE> <DEDENT> def test_init(self): <NEW_LINE> <INDENT> self.assertTrue(self.new_image.name == "image") <NEW_LINE> <DEDENT> def test_save_image(self): <NEW_LINE> <INDENT> self.new_image.save_image() <NEW_LINE> self.assertTrue(len(Image.objects.all()) > 0) <NEW_LINE> <DEDENT> def test_delete_image(self): <NEW_LINE> <INDENT> self.new_image.save_image() <NEW_LINE> self.assertTrue(len(Image.objects.all()) > 0) <NEW_LINE> self.new_image.delete_image() <NEW_LINE> self.assertTrue(len(Image.objects.all()) == 0) <NEW_LINE> <DEDENT> def test_get_images(self): <NEW_LINE> <INDENT> self.new_image.save_image() <NEW_LINE> self.assertTrue(len(Image.get_images()) == 1) <NEW_LINE> <DEDENT> def test_search_image(self): <NEW_LINE> <INDENT> self.new_image.save_image() <NEW_LINE> self.assertTrue(len(Image.search_image("funny")) > 0) <NEW_LINE> <DEDENT> def test_filter_by_location(self): <NEW_LINE> <INDENT> self.new_image.save_image() <NEW_LINE> self.assertTrue(len(Image.filter_by_location("Africa")) == 1) | This is the class we will use to test the images | 6259905abaa26c4b54d50884 |
class PopupOperation(Popup): <NEW_LINE> <INDENT> def when_opened(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def update(self, title, text): <NEW_LINE> <INDENT> self.ids['message_operation_lbl'].text = text <NEW_LINE> self.title = title <NEW_LINE> <DEDENT> def close_after(self, dt=2.): <NEW_LINE> <INDENT> Clock.schedule_once(lambda t: self.dismiss(), dt) | display a popup while an operation occures | 6259905ae76e3b2f99fd9fde |
class Instance(Field.Instance): <NEW_LINE> <INDENT> pass | An instance of the String field. | 6259905acc0a2c111447c5be |
class tektronixDPO5054(tektronixDPO5000): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.__dict__.setdefault('_instrument_id', 'DPO5054') <NEW_LINE> super(tektronixDPO5054, self).__init__(*args, **kwargs) <NEW_LINE> self._analog_channel_count = 4 <NEW_LINE> self._digital_channel_count = 0 <NEW_LINE> self._bandwidth = 500e6 <NEW_LINE> self._init_channels() | Tektronix DPO5054 IVI oscilloscope driver | 6259905a63b5f9789fe86752 |
class Permutation(nn.Module): <NEW_LINE> <INDENT> def __init__(self, dim): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.dim = dim <NEW_LINE> <DEDENT> def forward(self, inputs): <NEW_LINE> <INDENT> if self.dim <= 1: <NEW_LINE> <INDENT> return inputs <NEW_LINE> <DEDENT> nr_dims = len(inputs.size()) <NEW_LINE> index = tuple(range(nr_dims - 1)) <NEW_LINE> start_dim = nr_dims - 1 - self.dim <NEW_LINE> assert start_dim > 0 <NEW_LINE> res = [] <NEW_LINE> for i in itertools.permutations(index[start_dim:]): <NEW_LINE> <INDENT> p = index[:start_dim] + i + (nr_dims - 1,) <NEW_LINE> res.append(inputs.permute(p)) <NEW_LINE> <DEDENT> return torch.cat(res, dim=-1) <NEW_LINE> <DEDENT> def get_output_dim(self, input_dim): <NEW_LINE> <INDENT> mul = 1 <NEW_LINE> for i in range(self.dim): <NEW_LINE> <INDENT> mul *= i + 1 <NEW_LINE> <DEDENT> return input_dim * mul | Create r! new predicates by permuting the axies for r-arity predicates. | 6259905a462c4b4f79dbcfe5 |
class TraceFreeBreakpoint(gdb.Breakpoint): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(TraceFreeBreakpoint, self).__init__("__libc_free", gdb.BP_BREAKPOINT, internal=True) <NEW_LINE> self.silent = True <NEW_LINE> return <NEW_LINE> <DEDENT> def stop(self): <NEW_LINE> <INDENT> if is_x86_32(): <NEW_LINE> <INDENT> addr = to_unsigned_long(dereference(current_arch.sp+4)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> addr = long(gdb.parse_and_eval(current_arch.function_parameters[0])) <NEW_LINE> <DEDENT> msg = [] <NEW_LINE> check_free_null = get_gef_setting("heap-analysis-helper.check_free_null") <NEW_LINE> check_double_free = get_gef_setting("heap-analysis-helper.check_double_free") <NEW_LINE> check_weird_free = get_gef_setting("heap-analysis-helper.check_weird_free") <NEW_LINE> check_uaf = get_gef_setting("heap-analysis-helper.check_uaf") <NEW_LINE> ok("{} - free({:#x})".format(Color.colorify("Heap-Analysis", attrs="yellow bold"), addr)) <NEW_LINE> if addr==0: <NEW_LINE> <INDENT> if check_free_null: <NEW_LINE> <INDENT> msg.append(Color.colorify("Heap-Analysis", attrs="yellow bold")) <NEW_LINE> msg.append("Attempting to free(NULL) at {:#x}".format(current_arch.pc)) <NEW_LINE> msg.append("Reason: if NULL page is allocatable, this can lead to code execution.") <NEW_LINE> push_context_message("warn", "\n".join(msg)) <NEW_LINE> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> if addr in [x for (x,y) in __heap_freed_list__]: <NEW_LINE> <INDENT> if check_double_free: <NEW_LINE> <INDENT> msg.append(Color.colorify("Heap-Analysis", attrs="yellow bold")) <NEW_LINE> msg.append("Double-free detected {} free({:#x}) is called at {:#x} but is already in the free-ed list".format(RIGHT_ARROW, addr, current_arch.pc)) <NEW_LINE> msg.append("Execution will likely crash...") <NEW_LINE> push_context_message("warn", "\n".join(msg)) <NEW_LINE> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> idx = [x for x,y in __heap_allocated_list__].index(addr) <NEW_LINE> item = __heap_allocated_list__.pop(idx) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> if check_weird_free: <NEW_LINE> <INDENT> msg.append(Color.colorify("Heap-Analysis", attrs="yellow bold")) <NEW_LINE> msg.append("Heap inconsistency detected:") <NEW_LINE> msg.append("Attempting to free an unknown value: {:#x}".format(addr)) <NEW_LINE> push_context_message("warn", "\n".join(msg)) <NEW_LINE> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> __heap_freed_list__.append(item) <NEW_LINE> self.retbp = None <NEW_LINE> if check_uaf: <NEW_LINE> <INDENT> self.retbp = TraceFreeRetBreakpoint(addr) <NEW_LINE> <DEDENT> return False | Track calls to free() and attempts to detect inconsistencies. | 6259905a460517430c432b42 |
class KeyFSettings(FSettings): <NEW_LINE> <INDENT> def __init__(self, service_name = 'KeyFSettings'): <NEW_LINE> <INDENT> self.service_name = service_name <NEW_LINE> <DEDENT> def set(self, settings): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> for k,v in settings.items(): <NEW_LINE> <INDENT> keyring.set_password(self.service_name, k, v) <NEW_LINE> <DEDENT> return True <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.error(e) <NEW_LINE> <DEDENT> <DEDENT> def delete(self, keys): <NEW_LINE> <INDENT> if type(keys) != list: <NEW_LINE> <INDENT> keys = [keys] <NEW_LINE> <DEDENT> for key in keys: <NEW_LINE> <INDENT> keyring.delete_password(self.service_name, key) <NEW_LINE> <DEDENT> <DEDENT> def get(self, keys): <NEW_LINE> <INDENT> if type(keys) != list: <NEW_LINE> <INDENT> keys = [keys] <NEW_LINE> <DEDENT> result = {} <NEW_LINE> try: <NEW_LINE> <INDENT> for key in keys: <NEW_LINE> <INDENT> result[key] = keyring.get_password(self.service_name, key) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return None | A keyring based class settings
| 6259905aac7a0e7691f73ac2 |
class ModelAPI(StorageAPI): <NEW_LINE> <INDENT> def __init__(self, model_cls, name=None, **kwargs): <NEW_LINE> <INDENT> super(ModelAPI, self).__init__(**kwargs) <NEW_LINE> self._model_cls = model_cls <NEW_LINE> self._name = name or model_cls.__modelname__ <NEW_LINE> self._thread_local = threading.local() <NEW_LINE> self._thread_local._instrumentation = [] <NEW_LINE> <DEDENT> @property <NEW_LINE> def _instrumentation(self): <NEW_LINE> <INDENT> if not hasattr(self._thread_local, '_instrumentation'): <NEW_LINE> <INDENT> self._thread_local._instrumentation = [] <NEW_LINE> <DEDENT> return self._thread_local._instrumentation <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def model_cls(self): <NEW_LINE> <INDENT> return self._model_cls <NEW_LINE> <DEDENT> def get(self, entry_id, filters=None, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError('Subclass must implement abstract get method') <NEW_LINE> <DEDENT> def put(self, entry, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError('Subclass must implement abstract store method') <NEW_LINE> <DEDENT> def delete(self, entry_id, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError('Subclass must implement abstract delete method') <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self.iter() <NEW_LINE> <DEDENT> def iter(self, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError('Subclass must implement abstract iter method') <NEW_LINE> <DEDENT> def update(self, entry, **kwargs): <NEW_LINE> <INDENT> raise NotImplementedError('Subclass must implement abstract update method') | Base class for model APIs ("MAPI"). | 6259905a99cbb53fe68324c0 |
class GridNode(): <NEW_LINE> <INDENT> def __init__(self, world, ID = None, **kwProperties): <NEW_LINE> <INDENT> self.__getAgent = world.getAgent <NEW_LINE> <DEDENT> def register(self, world, parentEntity=None, liTypeID=None, ghost=False): <NEW_LINE> <INDENT> world.addAgent(self, ghost=ghost) <NEW_LINE> world.grid.registerNode(self, *self.attr['coord']) <NEW_LINE> self.gridPeers = world._graph._addNoneEdge(self.attr['ID']) <NEW_LINE> if parentEntity is not None: <NEW_LINE> <INDENT> self.mpiGhostRanks = parentEntity.registerChild(world, self, liTypeID) <NEW_LINE> <DEDENT> <DEDENT> def getGridPeers(self): <NEW_LINE> <INDENT> return self._graph.nodes[self.gridPeers[0]]['instance'][self.gridPeers[1]] <NEW_LINE> <DEDENT> def getAttrOfGridPeers(self, attribute): <NEW_LINE> <INDENT> return self._graph.nodes[self.gridPeers][attribute][self.gridPeers[1]] | This enhancement identifies the agent as part of a grid. Currently, it only
registers itself in the location dictionary, found in the world
(see world.grid.registerNode()) | 6259905ad53ae8145f919a42 |
class OnBotUnmuteEventThread(Thread): <NEW_LINE> <INDENT> def __init__( self, plugin_name: str, event: Event ): <NEW_LINE> <INDENT> Thread.__init__(self) <NEW_LINE> self.plugin_name = plugin_name <NEW_LINE> self.event = event <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> exec("from plugins import " + self.plugin_name) <NEW_LINE> try: <NEW_LINE> <INDENT> exec(self.plugin_name + ".on_bot_unmute_event(self.event, Conn)") <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass | Bot被取消禁言调用 | 6259905a8e71fb1e983bd0aa |
class CachedProperty(object): <NEW_LINE> <INDENT> def __init__(self, func): <NEW_LINE> <INDENT> update_wrapper(self, func) <NEW_LINE> self.func = func <NEW_LINE> <DEDENT> def __get__(self, obj, cls): <NEW_LINE> <INDENT> if obj is None: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> value = obj.__dict__[self.func.__name__] = self.func(obj) <NEW_LINE> return value | A property that is only computed once per instance and then replaces
itself with an ordinary attribute. Deleting the attribute resets the
property. | 6259905abaa26c4b54d50885 |
class HomeSeerStatusDevice: <NEW_LINE> <INDENT> def __init__(self, raw_data: dict, request: Callable) -> None: <NEW_LINE> <INDENT> self._raw_data = raw_data <NEW_LINE> self._request = request <NEW_LINE> self._update_callback = None <NEW_LINE> self._suppress_update_callback = False <NEW_LINE> <DEDENT> @property <NEW_LINE> def ref(self) -> int: <NEW_LINE> <INDENT> return int(self._raw_data["ref"]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self) -> str: <NEW_LINE> <INDENT> return self._raw_data["name"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def location(self) -> str: <NEW_LINE> <INDENT> return self._raw_data["location"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def location2(self) -> str: <NEW_LINE> <INDENT> return self._raw_data["location2"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def value(self) -> Union[int, float]: <NEW_LINE> <INDENT> if "." in str(self._raw_data["value"]): <NEW_LINE> <INDENT> return float(self._raw_data["value"]) <NEW_LINE> <DEDENT> return int(self._raw_data["value"]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def status(self) -> str: <NEW_LINE> <INDENT> return self._raw_data["status"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_type_string(self) -> Optional[str]: <NEW_LINE> <INDENT> if self._raw_data["device_type_string"]: <NEW_LINE> <INDENT> return self._raw_data["device_type_string"] <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def last_change(self) -> str: <NEW_LINE> <INDENT> return self._raw_data["last_change"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def relationship(self) -> int: <NEW_LINE> <INDENT> relationship = int(self._raw_data["relationship"]) <NEW_LINE> if relationship == RELATIONSHIP_ROOT: <NEW_LINE> <INDENT> return RELATIONSHIP_ROOT <NEW_LINE> <DEDENT> elif relationship == RELATIONSHIP_CHILD: <NEW_LINE> <INDENT> return RELATIONSHIP_CHILD <NEW_LINE> <DEDENT> elif relationship == RELATIONSHIP_STANDALONE: <NEW_LINE> <INDENT> return RELATIONSHIP_STANDALONE <NEW_LINE> <DEDENT> return relationship <NEW_LINE> <DEDENT> @property <NEW_LINE> def associated_devices(self) -> list: <NEW_LINE> <INDENT> return self._raw_data["associated_devices"] <NEW_LINE> <DEDENT> @property <NEW_LINE> def interface_name(self) -> Optional[str]: <NEW_LINE> <INDENT> if self._raw_data["interface_name"]: <NEW_LINE> <INDENT> return self._raw_data["interface_name"] <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> def register_update_callback( self, callback: Callable, suppress_on_connection: bool = False ) -> None: <NEW_LINE> <INDENT> self._suppress_update_callback = suppress_on_connection <NEW_LINE> self._update_callback = callback <NEW_LINE> <DEDENT> def update_data(self, new_data: dict = None, connection_flag: bool = False) -> None: <NEW_LINE> <INDENT> if new_data is not None: <NEW_LINE> <INDENT> _LOGGER.debug( f"Updating data for {self.location2} {self.location} {self.name} ({self.ref})" ) <NEW_LINE> self._raw_data = new_data <NEW_LINE> <DEDENT> if connection_flag and self._suppress_update_callback: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if self._update_callback is not None: <NEW_LINE> <INDENT> self._update_callback() | Representation of a HomeSeer device with no controls (i.e. status only).
Base representation for all other HomeSeer device objects. | 6259905a91f36d47f2231980 |
class Solution: <NEW_LINE> <INDENT> def winSum(self, nums, k): <NEW_LINE> <INDENT> if k <= 0 or k > len(nums): <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> n = len(nums) <NEW_LINE> sums = [0] * (n - k + 1) <NEW_LINE> for i in range(k): <NEW_LINE> <INDENT> sums[0] += nums[i] <NEW_LINE> <DEDENT> for i in range(1, n - k + 1): <NEW_LINE> <INDENT> sums[i] = sums[i-1] - nums[i - 1] + nums[i + k - 1] <NEW_LINE> <DEDENT> return sums | @param: nums: a list of integers.
@param: k: length of window.
@return: the sum of the element inside the window at each moving. | 6259905a2ae34c7f260ac6c8 |
class ConfigResource(CORSResource, MarketplaceResource): <NEW_LINE> <INDENT> version = fields.CharField() <NEW_LINE> flags = fields.DictField('flags') <NEW_LINE> settings = fields.DictField('settings') <NEW_LINE> class Meta(MarketplaceResource.Meta): <NEW_LINE> <INDENT> detail_allowed_methods = ['get'] <NEW_LINE> list_allowed_methods = [] <NEW_LINE> resource_name = 'config' <NEW_LINE> <DEDENT> def obj_get(self, request, **kw): <NEW_LINE> <INDENT> if kw['pk'] != 'site': <NEW_LINE> <INDENT> raise ImmediateHttpResponse(response=http.HttpNotFound()) <NEW_LINE> <DEDENT> return GenericObject({ 'version': getattr(settings, 'BUILD_ID_JS', ''), 'flags': waffles(), 'settings': get_settings(), }) | A resource that is designed to be exposed externally and contains
settings or waffle flags that might be relevant to the client app. | 6259905a8a43f66fc4bf376e |
class Alien(Sprite): <NEW_LINE> <INDENT> def __init__(self, ai_settings, screen): <NEW_LINE> <INDENT> super(Alien, self).__init__() <NEW_LINE> self.screen = screen <NEW_LINE> self.ai_settings = ai_settings <NEW_LINE> self.image = pygame.image.load('images/alien.bmp') <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.x = self.rect.width <NEW_LINE> self.rect.y = self.rect.height <NEW_LINE> self.x = float(self.rect.x) <NEW_LINE> <DEDENT> def blitme(self): <NEW_LINE> <INDENT> self.screen.blit(self.image, self.rect) <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.x += self.ai_settings.alien_speed_factor <NEW_LINE> self.rect.x = self.x <NEW_LINE> <DEDENT> def check_edges(self): <NEW_LINE> <INDENT> screen_rect = self.screen.get_rect() <NEW_LINE> if self.rect.right >= screen_rect.right: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.rect.left <= 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.x += (self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction) <NEW_LINE> self.rect.x = self.x | 表示单个外星人的类 | 6259905a8e71fb1e983bd0ab |
class Sections(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> if self.__class__ is Sections: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> self._sections = {} <NEW_LINE> <DEDENT> def get_section_content(self, section_name): <NEW_LINE> <INDENT> return self._sections[section_name] <NEW_LINE> <DEDENT> def _check_for_section_begin(self, line): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _is_section_end(self, line): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _parse(self, file_path): <NEW_LINE> <INDENT> self._sections = {} <NEW_LINE> try: <NEW_LINE> <INDENT> input_file = open(file_path, "r" ) <NEW_LINE> <DEDENT> except IOError: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> lines = input_file.readlines() <NEW_LINE> input_file.close() <NEW_LINE> in_user_section = False <NEW_LINE> for line in lines: <NEW_LINE> <INDENT> line = line[:-1] <NEW_LINE> if not in_user_section: <NEW_LINE> <INDENT> section_begin, section_name, first_line = self._check_for_section_begin(line) <NEW_LINE> if section_begin: <NEW_LINE> <INDENT> in_user_section = True <NEW_LINE> content = [] <NEW_LINE> if first_line is not None: <NEW_LINE> <INDENT> content.append(first_line) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if not self._is_section_end(line): <NEW_LINE> <INDENT> content.append(line) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._sections[section_name] = content <NEW_LINE> in_user_section = False <NEW_LINE> section_name = "" | Abstract class to be inherited by all classes that implement
user editable code sections | 6259905a4428ac0f6e659b1d |
class Robot_data(object): <NEW_LINE> <INDENT> def __init__(self,data_dir,filename_list,batch_size,imshape,num_classes,crop_shape=[0,0,0], if_random_crop=True, if_flip=False, if_bright=False, if_contrast=False, if_whiten=False, num_epochs=0): <NEW_LINE> <INDENT> self.data_dir=data_dir <NEW_LINE> self.filename_list=filename_list <NEW_LINE> self.batch_size=batch_size <NEW_LINE> self.num_epochs=num_epochs <NEW_LINE> self.imshape=imshape <NEW_LINE> self.crop_shape=crop_shape <NEW_LINE> self.if_random_crop=if_random_crop <NEW_LINE> self.if_flip=if_flip <NEW_LINE> self.if_bright=if_bright <NEW_LINE> self.if_contrast=if_contrast <NEW_LINE> self.if_whiten=if_whiten <NEW_LINE> self.num_classes=num_classes <NEW_LINE> <DEDENT> def raw_label_input(self): <NEW_LINE> <INDENT> file_list=[] <NEW_LINE> for filename in self.filename_list: <NEW_LINE> <INDENT> file_list.append(os.path.join(self.data_dir,filename)) <NEW_LINE> <DEDENT> images, labels = tf_inputs.inputs(file_list,self.batch_size,num_epochs=self.num_epochs,num_threads=1,imshape=self.imshape, crop_shape=self.crop_shape, if_random_crop=self.if_random_crop, if_flip=self.if_flip, if_bright=self.if_bright, if_contrast=self.if_contrast, if_whiten=self.if_whiten) <NEW_LINE> return images, labels <NEW_LINE> <DEDENT> def one_hot_input(self): <NEW_LINE> <INDENT> file_list=[] <NEW_LINE> for filename in self.filename_list: <NEW_LINE> <INDENT> file_list.append(os.path.join(self.data_dir,filename)) <NEW_LINE> <DEDENT> images, labels = tf_inputs.inputs(file_list,self.batch_size,num_epochs=self.num_epochs,num_threads=1,imshape=self.imshape, crop_shape=self.crop_shape, if_random_crop=self.if_random_crop, if_flip=self.if_flip, if_bright=self.if_bright,if_contrast=self.if_contrast, if_whiten=self.if_whiten) <NEW_LINE> num_labels=tf.constant(self.num_classes) <NEW_LINE> hot_labels=convert_one_hot(labels, num_labels) <NEW_LINE> return images, hot_labels | Function: read image data from .tfrecords file. and provide for Net trainning.
raw_label_input() return labels with shape [batch];
one_hot_input() return one-hot labels with shape [batch,num_labels]
@author: shuang | 6259905a3c8af77a43b68a31 |
class AutomatedRunMixin(object): <NEW_LINE> <INDENT> def get_menu(self, *args): <NEW_LINE> <INDENT> jump = MenuManager(Action(name='Jump to End', action='jump_to_end'), Action(name='Jump to Start', action='jump_to_start'), name='Jump') <NEW_LINE> move = MenuManager(Action(name='Move to Start', action='move_to_start'), Action(name='Move to End', action='move_to_end'), Action(name='Move to ...', action='move_to_row'), name='Move') <NEW_LINE> copy = MenuManager(Action(name='Copy to Start', action='copy_to_start'), Action(name='Copy to End', action='copy_to_end'), name='Copy') <NEW_LINE> blocks = MenuManager(Action(name='Make Block', action='make_block'), Action(name='Repeat Block', action='repeat_block'), name='Blocks') <NEW_LINE> selects = MenuManager(Action(name='Select Unknowns', action='select_unknowns'), Action(name='Select Same Labnumber', action='select_same'), Action(name='Select Same Attributes...', action='select_same_attr'), name='Select') <NEW_LINE> return MenuManager(move, copy, jump, blocks, selects, Action(name='Unselect', action='unselect'), Action(name='Toggle End After', action='toggle_end_after'), Action(name='Toggle Skip', action='toggle_skip')) | mixin for table of automated runs that have not yet been executed | 6259905a21a7993f00c6754f |
class ThisSchema(object): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(ThisSchema, self).__init__() <NEW_LINE> self.args = args <NEW_LINE> self.kwargs = kwargs | Tool Used to set inner schemas with the same type with specific arguments
.
ThisSchema one might be use at the condition instanciation methods must not
reference the class.
..example::
class Test(Schema):
# contain an inner schema nullable 'test' of type Test.
test = ThisSchema(nullable=False)
def __init__(self, *args, **kwargs):
# old style call because when the schema will be automatically
# updated, the class Test does not exist in the scope
Schema.__init__(self, *args, **kwargs)
:param args: schema class vargs to use.
:param kwargs: schema class kwargs to use.
:return: input args and kwargs.
:rtype: tuple | 6259905a7b25080760ed87d0 |
class Status(Enum): <NEW_LINE> <INDENT> pending = 'pending' <NEW_LINE> complete = 'complete' | Enumeration of values for `CoinbaseTransaction.status`. | 6259905a55399d3f05627b01 |
class CustomUserUpdateView( LoginRequiredMixin, PermissionRequiredMixin, UpdateView ): <NEW_LINE> <INDENT> model = CustomUser <NEW_LINE> template_name = "customuser_update.html" <NEW_LINE> fields = ( "username", "first_name", "last_name", "email", "shifts_per_roster", "enforce_shifts_per_roster", "enforce_one_shift_per_day", "max_shifts", "available", "roles", ) <NEW_LINE> login_url = "login" <NEW_LINE> permission_required = "rosters.change_roster" | UserUpdateView. | 6259905a73bcbd0ca4bcb875 |
class User(ResponseObject): <NEW_LINE> <INDENT> REQUEST_URL = "user.json" <NEW_LINE> def __init__(self, api): <NEW_LINE> <INDENT> response = api.get(url=self.REQUEST_URL) <NEW_LINE> super().__init__(response) | A user represents a single Buffer user account. | 6259905a76e4537e8c3f0b6e |
class BugOra19584051(tests.MySQLConnectorTests): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> config = tests.get_mysql_config() <NEW_LINE> self.cnx = connection.MySQLConnection(**config) <NEW_LINE> self.cursor = self.cnx.cursor() <NEW_LINE> self.tbl = 'Bug19584051' <NEW_LINE> self.cursor.execute("DROP TABLE IF EXISTS %s" % self.tbl) <NEW_LINE> create = ('CREATE TABLE {0}(col1 INT NOT NULL, col2 BLOB, ' 'col3 VARCHAR(10), col4 DECIMAL(4,2), ' 'col5 DATETIME , col6 YEAR, ' 'PRIMARY KEY(col1))'.format(self.tbl)) <NEW_LINE> self.cursor.execute(create) <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.cursor.execute("DROP TABLE IF EXISTS %s" % self.tbl) <NEW_LINE> self.cursor.close() <NEW_LINE> self.cnx.close() <NEW_LINE> <DEDENT> def test_dbapi(self): <NEW_LINE> <INDENT> cur = self.cnx.cursor() <NEW_LINE> sql = ("INSERT INTO {0}(col1, col2, col3, col4, col5, col6) " "VALUES (%s, %s, %s, %s, %s, %s)".format(self.tbl)) <NEW_LINE> params = (100, 'blob-data', 'foo', 1.2, datetime(2014, 8, 4, 9, 11, 14), 2014) <NEW_LINE> exp = [ mysql.connector.NUMBER, mysql.connector.BINARY, mysql.connector.STRING, mysql.connector.NUMBER, mysql.connector.DATETIME, mysql.connector.NUMBER, ] <NEW_LINE> cur.execute(sql, params) <NEW_LINE> sql = "SELECT * FROM {0}".format(self.tbl) <NEW_LINE> cur.execute(sql) <NEW_LINE> temp = cur.fetchone() <NEW_LINE> type_codes = [row[1] for row in cur.description] <NEW_LINE> self.assertEqual(exp, type_codes) <NEW_LINE> cur.close() | BUG#19584051: TYPE_CODE DOES NOT COMPARE EQUAL
| 6259905aa79ad1619776b5ae |
@attr.s(auto_attribs=True, init=False) <NEW_LINE> class LookmlModelExploreSet(model.Model): <NEW_LINE> <INDENT> name: Optional[str] = None <NEW_LINE> value: Optional[Sequence[str]] = None <NEW_LINE> def __init__( self, *, name: Optional[str] = None, value: Optional[Sequence[str]] = None ): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.value = value | Attributes:
name: Name
value: Value set | 6259905ad6c5a102081e3703 |
class ValidationError(ValidationErrors): <NEW_LINE> <INDENT> def __init__(self, message, value, invalid, against, path=None): <NEW_LINE> <INDENT> errors = [{ 'error': 'ValidationError', 'message': message, 'value': value, 'invalid': invalid, 'against': against, 'path': path or '', }] <NEW_LINE> super(ValidationError, self).__init__( message, value, errors=errors ) <NEW_LINE> self.invalid = invalid <NEW_LINE> self.against = against <NEW_LINE> self.path = path | Cover a single validation error | 6259905a56ac1b37e63037d8 |
class InvalidLanguage(Exception): <NEW_LINE> <INDENT> pass | Error if the selected language is not available. | 6259905a3617ad0b5ee0772d |
class HalMessageError(object): <NEW_LINE> <INDENT> def __init__(self, source = "", message = "", m_exception = None, stack_trace = "NA", **kwds): <NEW_LINE> <INDENT> super().__init__(**kwds) <NEW_LINE> if not isinstance(source, str): <NEW_LINE> <INDENT> raise HalMessageException("source is not of type 'str'") <NEW_LINE> <DEDENT> if not isinstance(message, str): <NEW_LINE> <INDENT> raise HalMessageException("message is not of type 'str'") <NEW_LINE> <DEDENT> if not isinstance(m_exception, Exception): <NEW_LINE> <INDENT> raise HalMessageException("m_exception is not of type 'Exception'") <NEW_LINE> <DEDENT> self.message = message <NEW_LINE> self.m_exception = m_exception <NEW_LINE> self.source = source <NEW_LINE> if (stack_trace == "NA"): <NEW_LINE> <INDENT> self.stack_trace = traceback.format_exc() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.stack_trace = stack_trace <NEW_LINE> <DEDENT> <DEDENT> def getException(self): <NEW_LINE> <INDENT> return self.m_exception <NEW_LINE> <DEDENT> def hasException(self): <NEW_LINE> <INDENT> return self.m_exception is not None <NEW_LINE> <DEDENT> def printException(self): <NEW_LINE> <INDENT> e_msg = "\n" <NEW_LINE> e_msg += "Got an exception from '" + self.source + "' of type '" + self.message + "'!\n" <NEW_LINE> e_msg += "\n" <NEW_LINE> e_msg += "Traceback when the exception occurred:" <NEW_LINE> e_msg += "\n" <NEW_LINE> e_msg += self.stack_trace <NEW_LINE> e_msg += "\n" <NEW_LINE> print(e_msg) <NEW_LINE> hdebug.logText(e_msg) | If a module has a problem with a message that it can't handle then
it should call the message's addError() method with one of these objects. | 6259905a4e4d5625663739e9 |
class HashTest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.model = gensim.models.fasttext.load_facebook_model(datapath('crime-and-punishment.bin')) <NEW_LINE> with smart_open.smart_open(datapath('crime-and-punishment.vec'), 'r', encoding='utf-8') as fin: <NEW_LINE> <INDENT> self.expected = dict(load_vec(fin)) <NEW_LINE> <DEDENT> <DEDENT> def test_ascii(self): <NEW_LINE> <INDENT> word = u'landlady' <NEW_LINE> expected = self.expected[word] <NEW_LINE> actual = self.model.wv[word] <NEW_LINE> self.assertTrue(np.allclose(expected, actual, atol=1e-5)) <NEW_LINE> <DEDENT> def test_unicode(self): <NEW_LINE> <INDENT> word = u'хозяйка' <NEW_LINE> expected = self.expected[word] <NEW_LINE> actual = self.model.wv[word] <NEW_LINE> self.assertTrue(np.allclose(expected, actual, atol=1e-5)) <NEW_LINE> <DEDENT> def test_out_of_vocab(self): <NEW_LINE> <INDENT> longword = u'rechtsschutzversicherungsgesellschaften' <NEW_LINE> expected = { u'steamtrain': np.array([0.031988, 0.022966, 0.059483, 0.094547, 0.062693]), u'паровоз': np.array([-0.0033987, 0.056236, 0.036073, 0.094008, 0.00085222]), longword: np.array([-0.012889, 0.029756, 0.018020, 0.099077, 0.041939]), } <NEW_LINE> actual = {w: self.model.wv[w] for w in expected} <NEW_LINE> self.assertTrue(np.allclose(expected[u'steamtrain'], actual[u'steamtrain'], atol=1e-5)) <NEW_LINE> self.assertTrue(np.allclose(expected[u'паровоз'], actual[u'паровоз'], atol=1e-5)) <NEW_LINE> self.assertTrue(np.allclose(expected[longword], actual[longword], atol=1e-5)) | Loosely based on the test described here:
https://github.com/RaRe-Technologies/gensim/issues/2059#issuecomment-432300777
With a broken hash, vectors for non-ASCII keywords don't match when loaded
from a native model. | 6259905a7047854f463409a2 |
class BinarySearchTreeNode(BinaryTreeNode): <NEW_LINE> <INDENT> def __init__(self, d: int, parent: 'BinarySearchTreeNode'): <NEW_LINE> <INDENT> super().__init__(d) <NEW_LINE> self.parent = parent <NEW_LINE> self.size = 1 <NEW_LINE> <DEDENT> def insert(self, d: int) -> 'BinarySearchTreeNode': <NEW_LINE> <INDENT> self.size += 1 <NEW_LINE> if d <= self.data: <NEW_LINE> <INDENT> if self.left is None: <NEW_LINE> <INDENT> self.left = BinarySearchTreeNode(d, self) <NEW_LINE> return self.left <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.left.insert(d) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.right is None: <NEW_LINE> <INDENT> self.right = BinarySearchTreeNode(d, self) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.right.insert(d) <NEW_LINE> return self.right <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def find(self, d: int) -> 'BinarySearchTreeNode': <NEW_LINE> <INDENT> curr = self <NEW_LINE> while curr is not None: <NEW_LINE> <INDENT> if d == curr.data: <NEW_LINE> <INDENT> return curr <NEW_LINE> <DEDENT> elif d < curr.data: <NEW_LINE> <INDENT> curr = curr.left <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> curr = curr.right <NEW_LINE> <DEDENT> <DEDENT> return curr <NEW_LINE> <DEDENT> def __find_min(self): <NEW_LINE> <INDENT> curr = self <NEW_LINE> while curr.left is not None: <NEW_LINE> <INDENT> curr = curr.left <NEW_LINE> <DEDENT> return curr <NEW_LINE> <DEDENT> def __replace_node_in_parent(self, replacement: 'BinarySearchTreeNode' = None): <NEW_LINE> <INDENT> if self.parent is not None: <NEW_LINE> <INDENT> if self is self.parent.left: <NEW_LINE> <INDENT> self.parent.left = replacement <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.parent.right = replacement <NEW_LINE> <DEDENT> <DEDENT> if replacement is not None: <NEW_LINE> <INDENT> replacement.parent = self.parent <NEW_LINE> <DEDENT> <DEDENT> def delete(self, d: int): <NEW_LINE> <INDENT> self.size -= 1 <NEW_LINE> if d < self.data: <NEW_LINE> <INDENT> return self.left.delete(d) <NEW_LINE> <DEDENT> elif d > self.data: <NEW_LINE> <INDENT> return self.right.delete(d) <NEW_LINE> <DEDENT> if self.left is not None and self.right is not None: <NEW_LINE> <INDENT> successor = self.right.__find_min() <NEW_LINE> self.data = successor.data <NEW_LINE> successor.delete(successor.data) <NEW_LINE> <DEDENT> elif self.left is not None: <NEW_LINE> <INDENT> self.__replace_node_in_parent(self.left) <NEW_LINE> <DEDENT> elif self.right is not None: <NEW_LINE> <INDENT> self.__replace_node_in_parent(self.right) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__replace_node_in_parent(None) <NEW_LINE> <DEDENT> <DEDENT> def get_random_node(self) -> 'BinarySearchTreeNode': <NEW_LINE> <INDENT> if self.left is None and self.right is None: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> rand = randint(1, self.size) <NEW_LINE> if self.left is None: <NEW_LINE> <INDENT> return self if rand == 1 else self.right.get_random_node() <NEW_LINE> <DEDENT> elif self.right is None: <NEW_LINE> <INDENT> return self if rand == self.size else self.left.get_random_node() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if rand <= self.left.size: <NEW_LINE> <INDENT> return self.left.get_random_node() <NEW_LINE> <DEDENT> elif rand > self.left.size + 1: <NEW_LINE> <INDENT> return self.right.get_random_node() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self | A very basic node in a binary tree.
Insert, find, and delete functionality shamelessly modeled from code at
https://en.wikipedia.org/wiki/Binary_search_tree
Attributes:
parent: The parent node
size: The number of nodes in this subtree, beginning at 1. | 6259905ad53ae8145f919a44 |
class Mouse(object): <NEW_LINE> <INDENT> def __init__(self, filename='/dev/input/mice'): <NEW_LINE> <INDENT> self.mouse = open(filename, 'rb') <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, exc_type, exc_value, traceback): <NEW_LINE> <INDENT> self.mouse.close() <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> status, dx, dy = tuple(self.mouse.read(3)) <NEW_LINE> return self.interpret_status(status), self.to_signed(dx), self.to_signed(dy) <NEW_LINE> <DEDENT> def to_signed(self, num): <NEW_LINE> <INDENT> return num - ((0x80 & num) << 1) <NEW_LINE> <DEDENT> def interpret_status(self, status): <NEW_LINE> <INDENT> y_overflow = status & 0x80 > 0 <NEW_LINE> x_overflow = status & 0x40 > 0 <NEW_LINE> y_sign = status & 0x20 > 0 <NEW_LINE> x_sign = status & 0x10 > 0 <NEW_LINE> middle_button = status & 0x4 > 0 <NEW_LINE> right_button = status & 0x2 > 0 <NEW_LINE> left_button = status & 0x1 > 0 <NEW_LINE> return y_overflow, x_overflow, y_sign, x_sign, middle_button, right_button, left_button | Provides the ability to use `with Mouse() as mouse:` syntax to grab
mouse updates over in the Robot class | 6259905ae5267d203ee6ceb1 |
class ConnectionObject(object): <NEW_LINE> <INDENT> def __init__(self, region): <NEW_LINE> <INDENT> self.__conns = {} <NEW_LINE> self.conn_obj = AwsAuth() <NEW_LINE> self.region = region <NEW_LINE> <DEDENT> def get_conn(self): <NEW_LINE> <INDENT> conn = self.__conns.get(self.region) <NEW_LINE> if conn is None: <NEW_LINE> <INDENT> conn = self.conn_obj.get_ec2_conn(self.region) <NEW_LINE> self.__conns.update({self.region: conn}) <NEW_LINE> <DEDENT> return conn | Help on class ConnectionObject in auth_manager module:
NAME
ConnectionObject
DESCRIPTION
This class provides an object of AwsAuth class.
self.__conns attribute stores already initialized connection objects.
If requested connection object doesn't exist in self.__conns get_conn method
will get it from get_ec2_conn method of AwsAuth class and store it to self.__conns.
Other classes should inherit this class for quick access to the connection objects.
METHODS
__init__(self, region)
Init method initialize self.__conns dictionary for connection objects storing.
It also create AwsAuth class instance and initialize requested region attribute.
get_conn(self)
Tries grab connection object from self.__conns attribute. If there is no such
object method tries calls this object from get_ec2_conn method from AwsAuth class.
:return: connection to the EC2 region by requested region. | 6259905abaa26c4b54d50887 |
class WordlistTable(wx.ListCtrl): <NEW_LINE> <INDENT> def __init__(self, parent, *args, **kwargs): <NEW_LINE> <INDENT> wx.ListCtrl.__init__(self, parent, *args, **kwargs) <NEW_LINE> self.parent = parent <NEW_LINE> self.wordlist = None <NEW_LINE> self.sortbyend = False <NEW_LINE> self.sortbyfreq = False <NEW_LINE> self.searchterm = '' <NEW_LINE> droptarget = TableDND(self) <NEW_LINE> self.SetDropTarget(droptarget) <NEW_LINE> <DEDENT> def find(self): <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> sel = self.GetNextSelected(-1) <NEW_LINE> if sel == -1: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> self.Select(sel, False) <NEW_LINE> <DEDENT> self.lasthit = self.FindItem(-1, self.searchterm, partial=True) <NEW_LINE> if self.lasthit == -1: <NEW_LINE> <INDENT> self.parent.SetStatusText('Search term not found') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.Select(self.lasthit) <NEW_LINE> self.Focus(self.lasthit) <NEW_LINE> <DEDENT> <DEDENT> def find_next(self): <NEW_LINE> <INDENT> newhit = self.FindItem(self.lasthit + 1, self.searchterm, partial=True) <NEW_LINE> if newhit == -1: <NEW_LINE> <INDENT> self.parent.SetStatusText('Search reached the end. Starting from the beginning.') <NEW_LINE> self.find() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.Select(self.lasthit, False) <NEW_LINE> self.Select(newhit) <NEW_LINE> self.Focus(newhit) <NEW_LINE> self.lasthit = newhit <NEW_LINE> <DEDENT> <DEDENT> def get_sorted(self): <NEW_LINE> <INDENT> if self.sortbyfreq: <NEW_LINE> <INDENT> return self.wordlist.items_by_frequency() <NEW_LINE> <DEDENT> if self.sortbyend: <NEW_LINE> <INDENT> return self.wordlist.items_by_wordend() <NEW_LINE> <DEDENT> return sorted(self.wordlist.items_by_wordbeginning()) <NEW_LINE> <DEDENT> def update(self, wordlist=None): <NEW_LINE> <INDENT> if wordlist: <NEW_LINE> <INDENT> self.wordlist = wordlist <NEW_LINE> <DEDENT> self.parent.SetStatusText('Updating wordlist...') <NEW_LINE> self.ClearAll() <NEW_LINE> if self.wordlist: <NEW_LINE> <INDENT> values = self.get_sorted() <NEW_LINE> align = wx.LIST_FORMAT_LEFT <NEW_LINE> if self.sortbyend: <NEW_LINE> <INDENT> align = wx.LIST_FORMAT_RIGHT <NEW_LINE> <DEDENT> self.InsertColumn(0, 'word', align, width=120) <NEW_LINE> self.InsertColumn(1, 'frequency', wx.LIST_FORMAT_RIGHT, width=90) <NEW_LINE> for i in values: <NEW_LINE> <INDENT> self.Append(i) <NEW_LINE> <DEDENT> <DEDENT> self.parent.SetStatusText('Wordlist updated.') | table for displaying the wordlist
attributes:
sortbyend sort wordlist by word ends?
sortbyfreq sort wordlist by frequency?
searchterm term that is searched within the list
lasthit index of the last found item
parent the parent window
wordlist the wordlist to be displayed | 6259905a507cdc57c63a6388 |
class CoreApi(object): <NEW_LINE> <INDENT> def __init__(self, api_client=None): <NEW_LINE> <INDENT> if api_client is None: <NEW_LINE> <INDENT> api_client = ApiClient() <NEW_LINE> <DEDENT> self.api_client = api_client <NEW_LINE> <DEDENT> def get_api_versions(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.get_api_versions_with_http_info(**kwargs) <NEW_LINE> <DEDENT> def get_api_versions_with_http_info(self, **kwargs): <NEW_LINE> <INDENT> local_var_params = locals() <NEW_LINE> all_params = [ ] <NEW_LINE> all_params.extend( [ 'async_req', '_return_http_data_only', '_preload_content', '_request_timeout' ] ) <NEW_LINE> for key, val in six.iteritems(local_var_params['kwargs']): <NEW_LINE> <INDENT> if key not in all_params: <NEW_LINE> <INDENT> raise ApiTypeError( "Got an unexpected keyword argument '%s'" " to method get_api_versions" % key ) <NEW_LINE> <DEDENT> local_var_params[key] = val <NEW_LINE> <DEDENT> del local_var_params['kwargs'] <NEW_LINE> collection_formats = {} <NEW_LINE> path_params = {} <NEW_LINE> query_params = [] <NEW_LINE> header_params = {} <NEW_LINE> form_params = [] <NEW_LINE> local_var_files = {} <NEW_LINE> body_params = None <NEW_LINE> header_params['Accept'] = self.api_client.select_header_accept( ['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) <NEW_LINE> auth_settings = ['BearerToken'] <NEW_LINE> return self.api_client.call_api( '/api/', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1APIVersions', auth_settings=auth_settings, async_req=local_var_params.get('async_req'), _return_http_data_only=local_var_params.get('_return_http_data_only'), _preload_content=local_var_params.get('_preload_content', True), _request_timeout=local_var_params.get('_request_timeout'), collection_formats=collection_formats) | NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually. | 6259905aa17c0f6771d5d693 |
class View(six.with_metaclass(ViewMeta, models.Model)): <NEW_LINE> <INDENT> _deferred = False <NEW_LINE> class Meta: <NEW_LINE> <INDENT> abstract = True <NEW_LINE> managed = False | Helper for exposing Postgres views as Django models.
| 6259905a435de62698e9d3e7 |
class SendDialog(Widget): <NEW_LINE> <INDENT> def handle_paint(self, event): print('SendDialog: {}'.format(event)) | SendDialog是行为的控件。SendDialog仅能处理paint事件。 | 6259905a32920d7e50bc7629 |
class HexPresentor: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def present(self, data: bytes, step: int, pos: int, early=False) -> (list, list, list, int): <NEW_LINE> <INDENT> hex_rows = self._hex_creator(data, step) <NEW_LINE> ascii_rows = self._ascii_creator(data, step) <NEW_LINE> rows = self._row_creator(len(hex_rows), step, pos, early) <NEW_LINE> return rows, hex_rows, ascii_rows <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _hex_creator(data: bytes, step: int) -> list: <NEW_LINE> <INDENT> hex_list = [] <NEW_LINE> hex_row = [] <NEW_LINE> data = data.hex() <NEW_LINE> for i in range(len(data) // 2): <NEW_LINE> <INDENT> hex_row.append(data[i * 2:i * 2 + 2]) <NEW_LINE> if len(hex_row) == step: <NEW_LINE> <INDENT> hex_list.append(hex_row) <NEW_LINE> hex_row = [] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> residue = len(data) % (step * 2) <NEW_LINE> if residue != 0: <NEW_LINE> <INDENT> for j in range(step - residue): <NEW_LINE> <INDENT> hex_row.append('00') <NEW_LINE> <DEDENT> hex_list.append(hex_row) <NEW_LINE> <DEDENT> <DEDENT> return hex_list <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _ascii_creator(data: bytes, step: int) -> list: <NEW_LINE> <INDENT> hex_list = [] <NEW_LINE> ascii_row = [] <NEW_LINE> for i in range(len(data)): <NEW_LINE> <INDENT> symbol = data[i:i + 1] <NEW_LINE> try: <NEW_LINE> <INDENT> ascii_row.append(symbol.decode('ascii')) <NEW_LINE> <DEDENT> except UnicodeDecodeError: <NEW_LINE> <INDENT> ascii_row.append('.') <NEW_LINE> <DEDENT> if len(ascii_row) == step: <NEW_LINE> <INDENT> hex_list.append(ascii_row) <NEW_LINE> ascii_row = [] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> residue = len(data) % step <NEW_LINE> if residue != 0: <NEW_LINE> <INDENT> for j in range(step - residue): <NEW_LINE> <INDENT> ascii_row.append('.') <NEW_LINE> <DEDENT> hex_list.append(ascii_row) <NEW_LINE> <DEDENT> <DEDENT> return hex_list <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _row_creator(len_row: int, step: int, pos: int, early=False) -> (list, int): <NEW_LINE> <INDENT> rows = [] <NEW_LINE> row = pos * step - step <NEW_LINE> if early is True: <NEW_LINE> <INDENT> pos -= len_row * 2 <NEW_LINE> row = pos * step - step <NEW_LINE> <DEDENT> for inc in range(len_row): <NEW_LINE> <INDENT> row = row + step <NEW_LINE> rows.append(f'{row:08d}') <NEW_LINE> <DEDENT> return rows | Класс предоставляет метод для конвертации данных в хекс формат.
Не меняйте длинну строки для уже сформированных данных. | 6259905a6e29344779b01c30 |
class UnauthorizedException(Exception): <NEW_LINE> <INDENT> pass | Authorization failed | 6259905a2ae34c7f260ac6ca |
class Languages(Base): <NEW_LINE> <INDENT> __tablename__ = 'languages_tb' <NEW_LINE> language = Column(String, primary_key=True) <NEW_LINE> fullname = Column(String, nullable=False) <NEW_LINE> enabled_ddtss = Column(Boolean, nullable=False, default=True) <NEW_LINE> translation_model = Column(TranslationModelType, nullable=False) <NEW_LINE> milestone_high = Column(String, ForeignKey('description_milestone_tb.milestone')) <NEW_LINE> milestone_medium = Column(String, ForeignKey('description_milestone_tb.milestone')) <NEW_LINE> milestone_low = Column(String, ForeignKey('description_milestone_tb.milestone')) <NEW_LINE> @property <NEW_LINE> def coordinators(self): <NEW_LINE> <INDENT> return Session.object_session(self).query(Users).join(UserAuthority). filter(UserAuthority.language_ref==self.language). filter(UserAuthority.auth_level==UserAuthority.AUTH_LEVEL_COORDINATOR).all() <NEW_LINE> <DEDENT> @property <NEW_LINE> def trusted_users(self): <NEW_LINE> <INDENT> return Session.object_session(self).query(Users).join(UserAuthority). filter(UserAuthority.language_ref==self.language). filter(UserAuthority.auth_level==UserAuthority.AUTH_LEVEL_TRUSTED).all() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<Languages %s (%s)>' % (self.language, self.fullname) <NEW_LINE> <DEDENT> def get_next_to_translate(self, session): <NEW_LINE> <INDENT> lang_cte = session.query(Languages).filter_by(language=self.language).cte("language") <NEW_LINE> prio = session.query(Description.description_id, Description.prioritize) <NEW_LINE> high = session.query(DescriptionMilestone.description_id, literal(50).label("prioritize")).join(lang_cte, lang_cte.c.milestone_high==DescriptionMilestone.milestone) <NEW_LINE> medium = session.query(DescriptionMilestone.description_id, literal(30).label("prioritize")).join(lang_cte, lang_cte.c.milestone_medium==DescriptionMilestone.milestone) <NEW_LINE> low = session.query(DescriptionMilestone.description_id, literal(10).label("prioritize")).join(lang_cte, lang_cte.c.milestone_low==DescriptionMilestone.milestone) <NEW_LINE> prio_cte = union_all(prio, high, medium, low).cte() <NEW_LINE> q = session.query(prio_cte.c.description_tb_description_id). filter(~exists([1], Translation.description_id == prio_cte.c.description_tb_description_id)). filter(~exists([1], PendingTranslation.description_id == prio_cte.c.description_tb_description_id)). group_by(prio_cte.c.description_tb_description_id). order_by(func.sum(prio_cte.c.description_tb_prioritize).desc()) <NEW_LINE> row = q.first() <NEW_LINE> if row: <NEW_LINE> <INDENT> return row[0] | Each language also has metainfo | 6259905a1b99ca4002290029 |
class _FilePointer(ndb.Model): <NEW_LINE> <INDENT> changeset_num = ndb.IntegerProperty(required=True) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '<_FilePointer path:%s namespace:%s changeset: %s>' % ( self.key.id(), self.key.namespace(), self.changeset_num) <NEW_LINE> <DEDENT> @property <NEW_LINE> def versioned_path(self): <NEW_LINE> <INDENT> return VERSIONS_PATH_FORMAT % (self.changeset_num, self.key.id()) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_root_key(namespace): <NEW_LINE> <INDENT> return ndb.Key(_FilePointer, '/', namespace=namespace) | Pointer from a root file path to its current file version.
All _FilePointers are in the same entity group. As such, the entities
are updated atomically to point a set of files at new versions.
Attributes:
key.id(): Root file path string. Example: '/foo.html'
changeset_num: An integer pointing to the file's latest committed changeset.
Technically, this is the 'deleted-by-submit' content changeset.
versioned_path: Versioned file path. Example: '/_titan/ver/1/foo.html' | 6259905a2c8b7c6e89bd4dd1 |
class SessionSupport: <NEW_LINE> <INDENT> def session(self): <NEW_LINE> <INDENT> return openSession() | Class that provides for the services that use SQLAlchemy the session support.
All services that use SQLAlchemy have to extend this class in order to provide the sql alchemy session
of the request, the session will be automatically handled by the session processor. | 6259905a8da39b475be047c9 |
class ValueFromStringSubstring(Transformation): <NEW_LINE> <INDENT> def __init__(self, variable, patterns, case_sensitive=False, match_beginning=False): <NEW_LINE> <INDENT> super().__init__(variable) <NEW_LINE> self.patterns = patterns <NEW_LINE> self.case_sensitive = case_sensitive <NEW_LINE> self.match_beginning = match_beginning <NEW_LINE> <DEDENT> def transform(self, c): <NEW_LINE> <INDENT> nans = np.equal(c, None) <NEW_LINE> c = c.astype(str) <NEW_LINE> c[nans] = "" <NEW_LINE> res = map_by_substring( c, self.patterns, self.case_sensitive, self.match_beginning) <NEW_LINE> res[nans] = np.nan <NEW_LINE> return res | Transformation that computes a discrete variable from a string variable by
pattern matching.
Given patterns `["abc", "a", "bc", ""]`, string data
`["abcd", "aa", "bcd", "rabc", "x"]` is transformed to values of the new
attribute with indices`[0, 1, 2, 0, 3]`.
Args:
variable (:obj:`~Orange.data.StringVariable`): the original variable
patterns (list of str): list of string patterns
case_sensitive (bool, optional): if set to `True`, the match is case
sensitive
match_beginning (bool, optional): if set to `True`, the pattern must
appear at the beginning of the string | 6259905a3539df3088ecd87f |
class TestViewsDepends(ModuleTestCase): <NEW_LINE> <INDENT> module = "inventory_report" | Test views and depends | 6259905a7b25080760ed87d1 |
class SpiderServicer(object): <NEW_LINE> <INDENT> def SpiderConn(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') <NEW_LINE> <DEDENT> def Report(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!') | The spider service definition.
| 6259905a55399d3f05627b03 |
class getProductDesc_result(object): <NEW_LINE> <INDENT> def __init__(self, success=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.STRING: <NEW_LINE> <INDENT> self.success = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('getProductDesc_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.STRING, 0) <NEW_LINE> oprot.writeString(self.success.encode('utf-8') if sys.version_info[0] == 2 else self.success) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- success | 6259905a63b5f9789fe86756 |
class Profile(ndb.Model): <NEW_LINE> <INDENT> displayName = ndb.StringProperty() <NEW_LINE> mainEmail = ndb.StringProperty() <NEW_LINE> teeShirtSize = ndb.StringProperty(default='NOT_SPECIFIED') <NEW_LINE> conferenceKeysToAttend = ndb.StringProperty(repeated=True) <NEW_LINE> sessionsWishList = ndb.StringProperty(repeated=True) | Profile -- User profile object | 6259905a07f4c71912bb0a1f |
class AMQPAdmin(object): <NEW_LINE> <INDENT> Shell = AMQShell <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.app = kwargs['app'] <NEW_LINE> self.out = kwargs.setdefault('out', sys.stderr) <NEW_LINE> self.silent = kwargs.get('silent') <NEW_LINE> self.args = args <NEW_LINE> <DEDENT> def connect(self, conn=None): <NEW_LINE> <INDENT> if conn: <NEW_LINE> <INDENT> conn.close() <NEW_LINE> <DEDENT> conn = self.app.connection() <NEW_LINE> self.note('-> connecting to {0}.'.format(conn.as_uri())) <NEW_LINE> conn.connect() <NEW_LINE> self.note('-> connected.') <NEW_LINE> return conn <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> shell = self.Shell(connect=self.connect, out=self.out) <NEW_LINE> if self.args: <NEW_LINE> <INDENT> return shell.onecmd(self.args) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return shell.cmdloop() <NEW_LINE> <DEDENT> except KeyboardInterrupt: <NEW_LINE> <INDENT> self.note('(bibi)') <NEW_LINE> <DEDENT> <DEDENT> def note(self, m): <NEW_LINE> <INDENT> if not self.silent: <NEW_LINE> <INDENT> say(m, file=self.out) | The celery :program:`celery amqp` utility. | 6259905a379a373c97d9a608 |
class PrivateTagsApiTests(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.user = get_user_model().objects.create_user( '[email protected]', 'password123' ) <NEW_LINE> self.client = APIClient() <NEW_LINE> self.client.force_authenticate(self.user) <NEW_LINE> <DEDENT> def test_retrieve_tags(self): <NEW_LINE> <INDENT> Tag.objects.create(user= self.user, name= 'Vegan') <NEW_LINE> Tag.objects.create(user= self.user, name= 'Dessert') <NEW_LINE> res = self.client.get(TAGS_URL) <NEW_LINE> tags = Tag.objects.all().order_by('-name') <NEW_LINE> serialazer = TagSerializer(tags, many=True) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(res.data, serialazer.data) <NEW_LINE> <DEDENT> def test_tags_limited_to_user_(self): <NEW_LINE> <INDENT> user2 = get_user_model().objects.create_user( '[email protected]', 'other1234' ) <NEW_LINE> Tag.objects.create(user= user2, name= 'Fruit') <NEW_LINE> tag = Tag.objects.create(user= self.user, name= 'Comfort Food') <NEW_LINE> res = self.client.get(TAGS_URL) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_200_OK) <NEW_LINE> self.assertEqual(len(res.data), 1) <NEW_LINE> self.assertEqual(res.data[0]['name'], tag.name) <NEW_LINE> <DEDENT> def test_create_tag_successful(self): <NEW_LINE> <INDENT> payload = { 'name':'test tag' } <NEW_LINE> self.client.post(TAGS_URL, payload) <NEW_LINE> exists = Tag.objects.filter(user = self.user, name=payload['name']).exists() <NEW_LINE> self.assertTrue(exists) <NEW_LINE> <DEDENT> def test_create_tag_invalid(self): <NEW_LINE> <INDENT> payload = {'name':''} <NEW_LINE> res = self.client.post(TAGS_URL, payload) <NEW_LINE> self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) <NEW_LINE> <DEDENT> def test_recieve_tags_assigned_to_recipes(self): <NEW_LINE> <INDENT> tag1 = Tag.objects.create(user= self.user, name = 'breakfast') <NEW_LINE> tag2 = Tag.objects.create(user= self.user, name = 'lunch') <NEW_LINE> recipe = Recipe.objects.create( user = self.user, title = 'corafsa', time_minutes = 20, price = 200 ) <NEW_LINE> recipe.tags.add(tag1) <NEW_LINE> res = self.client.get(TAGS_URL, {'assigned_only':1}) <NEW_LINE> serializer1 = TagSerializer(tag1) <NEW_LINE> serializer2 = TagSerializer(tag2) <NEW_LINE> self.assertIn(serializer1.data, res.data) <NEW_LINE> self.assertNotIn(serializer2.data, res.data) <NEW_LINE> <DEDENT> def test_retrive_tags_assigned_unique(self): <NEW_LINE> <INDENT> tag = Tag.objects.create(user =self.user, name ='sadasd') <NEW_LINE> Tag.objects.create(user =self.user, name ='saasdasddasd') <NEW_LINE> recipe1 = Recipe.objects.create( user = self.user, title = 'coraaasadasffsa', time_minutes = 20, price = 200 ) <NEW_LINE> recipe2 = Recipe.objects.create( user = self.user, title = 'corafdasfdssa', time_minutes = 20, price = 200 ) <NEW_LINE> recipe1.tags.add(tag) <NEW_LINE> recipe2.tags.add(tag) <NEW_LINE> res = self.client.get(TAGS_URL, {'assigned_only':1}) <NEW_LINE> self.assertEqual(len(res.data), 1) | test the authorized user tags API | 6259905a460517430c432b44 |
class TestHasOnlyReadOnly(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 test_HasOnlyReadOnly(self): <NEW_LINE> <INDENT> pass | HasOnlyReadOnly unit test stubs | 6259905aac7a0e7691f73ac6 |
class Median(RMS) : <NEW_LINE> <INDENT> def __init__ ( self , xmin , xmax ) : <NEW_LINE> <INDENT> RMS.__init__ ( self , xmin , xmax , err = False ) <NEW_LINE> <DEDENT> def _median_ ( self , func , xmin , xmax , *args ) : <NEW_LINE> <INDENT> from ostap.math.integral import Integral <NEW_LINE> iint = Integral ( func , xmin , err = False , args = args ) <NEW_LINE> half = 2.0 / iint ( xmax ) <NEW_LINE> ifun = lambda x : iint( x ) * half - 1.0 <NEW_LINE> from ostap.math.rootfinder import findroot <NEW_LINE> try: <NEW_LINE> <INDENT> meanv = Mean . __call__ ( self , func , *args ) <NEW_LINE> sigma = RMS . __call__ ( self , func , *args ) <NEW_LINE> import math <NEW_LINE> xmn = meanv - 2 * sigma <NEW_LINE> xmx = meanv + 2 * sigma <NEW_LINE> if isinstance ( xmin , float ) : xmn = max ( xmn , xmin ) <NEW_LINE> if isinstance ( xmax , float ) : xmx = min ( xmx , xmax ) <NEW_LINE> result = findroot ( ifun , xmn , xmx ) <NEW_LINE> <DEDENT> except : <NEW_LINE> <INDENT> result = findroot ( ifun , xmin , xmax ) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def __call__ ( self , func , *args ) : <NEW_LINE> <INDENT> return self._median_ ( func , self.xmin , self.xmax , *args ) <NEW_LINE> <DEDENT> def __str__ ( self ) : <NEW_LINE> <INDENT> return "Median(%s,%s)" % ( self.xmin , self.xmax ) | Calculate median for the distribution or function
>>> xmin,xmax = 0,math.pi
>>> median = Median ( xmin,xmax ) ## specify min/max
>>> value = median ( math.sin ) | 6259905aa8ecb033258727fb |
class Analysis(object): <NEW_LINE> <INDENT> def __init__(self, ts_start, config_file_location, test_id=None): <NEW_LINE> <INDENT> self.ts_start = ts_start <NEW_LINE> self.ts_end = None <NEW_LINE> self.test_id = test_id <NEW_LINE> self.config_file_location = config_file_location | Class that saves state for analysis to be conducted | 6259905ad53ae8145f919a46 |
class AverageAcquisition(object): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(AverageAcquisition, self).__init__( *args, **kwargs) <NEW_LINE> cls = 'IviScope' <NEW_LINE> grp = 'AverageAcquisition' <NEW_LINE> ivi.add_group_capability(self, cls+grp) <NEW_LINE> self._acquisition_number_of_averages = 1 <NEW_LINE> ivi.add_property(self, 'acquisition.number_of_averages', self._get_acquisition_number_of_averages, self._set_acquisition_number_of_averages) <NEW_LINE> <DEDENT> def _get_acquisition_number_of_averages(self): <NEW_LINE> <INDENT> return self._acquisition_number_of_averages <NEW_LINE> <DEDENT> def _set_acquisition_number_of_averages(self, value): <NEW_LINE> <INDENT> self._acquisition_number_of_averages = value | Extension IVI methods for oscilloscopes supporting average acquisition | 6259905a009cb60464d02b19 |
class Path(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_project_path(): <NEW_LINE> <INDENT> return PROJECT_DIRECTORY | The server class is responsible for exchanging encryption keys with the client,
sending communications ports, and creating the thread for each client that connects. | 6259905a7cff6e4e811b7028 |
class CheckRestrictionsResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'field_restrictions': {'readonly': True}, 'content_evaluation_result': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'field_restrictions': {'key': 'fieldRestrictions', 'type': '[FieldRestrictions]'}, 'content_evaluation_result': {'key': 'contentEvaluationResult', 'type': 'CheckRestrictionsResultContentEvaluationResult'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(CheckRestrictionsResult, self).__init__(**kwargs) <NEW_LINE> self.field_restrictions = None <NEW_LINE> self.content_evaluation_result = None | The result of a check policy restrictions evaluation on a resource.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar field_restrictions: The restrictions that will be placed on various fields in the
resource by policy.
:vartype field_restrictions: list[~azure.mgmt.policyinsights.models.FieldRestrictions]
:ivar content_evaluation_result: Evaluation results for the provided partial resource content.
:vartype content_evaluation_result:
~azure.mgmt.policyinsights.models.CheckRestrictionsResultContentEvaluationResult | 6259905a507cdc57c63a638a |
class PrivateField(serializers.ReadOnlyField): <NEW_LINE> <INDENT> def get_attribute(self, instance): <NEW_LINE> <INDENT> if self.context.get('request').user is not None: <NEW_LINE> <INDENT> if instance.id == self.context.get('request').user.id or self.context.get('request').user.is_superuser: <NEW_LINE> <INDENT> return super(PrivateField, self).get_attribute(instance) <NEW_LINE> <DEDENT> <DEDENT> return None | A Serializer Field class that can be used to hide sensitive User data in the JSON output | 6259905a30dc7b76659a0d72 |
class TestPortfolioPerformanceWriter(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.pp_writer = PortfolioPerformanceWriter() <NEW_LINE> self.pp_writer.init_output() <NEW_LINE> <DEDENT> def test_init_output(self): <NEW_LINE> <INDENT> self.assertEqual(",".join(PP_FIELDNAMES), self.pp_writer.out_string_stream.getvalue().strip()) <NEW_LINE> <DEDENT> def test_update_output(self): <NEW_LINE> <INDENT> test_entry = { PP_FIELDNAMES[0]: "date", PP_FIELDNAMES[1]: 0, PP_FIELDNAMES[2]: "currency", PP_FIELDNAMES[3]: "category", PP_FIELDNAMES[4]: "note", } <NEW_LINE> self.pp_writer.update_output(test_entry) <NEW_LINE> self.assertEqual( 'Datum,Wert,Buchungswährung,Typ,Notiz\r\ndate,"0,00000000",currency,category,note', self.pp_writer.out_string_stream.getvalue().strip(), ) <NEW_LINE> <DEDENT> def test_update_output_umlaut(self): <NEW_LINE> <INDENT> test_entry = { PP_FIELDNAMES[0]: "date", PP_FIELDNAMES[1]: 0, PP_FIELDNAMES[2]: "currency", PP_FIELDNAMES[3]: "category", PP_FIELDNAMES[4]: "Laiamäe Pärnaõie Užutekio", } <NEW_LINE> self.pp_writer.update_output(test_entry) <NEW_LINE> self.assertEqual( 'Datum,Wert,Buchungswährung,Typ,Notiz\r\ndate,"0,00000000",currency,category,Laiamäe Pärnaõie Užutekio', self.pp_writer.out_string_stream.getvalue().strip(), ) <NEW_LINE> <DEDENT> def test_write_pp_csv_file(self): <NEW_LINE> <INDENT> with tempfile.TemporaryDirectory() as tmpdirname: <NEW_LINE> <INDENT> fname = os.path.join(tmpdirname, "output") <NEW_LINE> self.pp_writer.write_pp_csv_file(fname) <NEW_LINE> with codecs.open(fname, "r", encoding="utf-8") as testfile: <NEW_LINE> <INDENT> self.assertEqual(",".join(PP_FIELDNAMES), testfile.read().strip()) | Test case implementation for PortfolioPerformanceWriter | 6259905a009cb60464d02b1a |
class MasterPostModel(PostModel): <NEW_LINE> <INDENT> title = ndb.StringProperty(verbose_name=_("Title")) <NEW_LINE> slug = ndb.StringProperty() <NEW_LINE> slave_count = ndb.IntegerProperty(default=0) <NEW_LINE> content = model.FilteredHtmlProperty(verbose_name=_("Content")) <NEW_LINE> """Pagination for slaves.""" <NEW_LINE> def default_pagination(self): <NEW_LINE> <INDENT> raise Exception("") <NEW_LINE> <DEDENT> def _validation(self): <NEW_LINE> <INDENT> return { "title": { "max_length": (120,), "required": (), }, } <NEW_LINE> <DEDENT> def make_slug(self): <NEW_LINE> <INDENT> self.slug = utils.slugify(self.title) <NEW_LINE> count = 1; slug = self.slug; num = 2 <NEW_LINE> while count > 0: <NEW_LINE> <INDENT> count = self.__class__.query(self.__class__.slug == slug).count() <NEW_LINE> if count <= 0: break <NEW_LINE> slug = "{}-{}".format(self.slug, num) <NEW_LINE> num += 1 <NEW_LINE> <DEDENT> self.slug = slug | Base class for posts that make a new "topic", such as blog entries, and the forum posts that starts a thread. | 6259905a0fa83653e46f64cb |
class ConfirmExtractionForm(forms.Form): <NEW_LINE> <INDENT> pass | Empty form, used for confirming that the detection worked correctly
| 6259905a45492302aabfdabd |
class ClassifierMixin(object): <NEW_LINE> <INDENT> def score(self, X, y): <NEW_LINE> <INDENT> return np.mean(self.predict(X) == y) | Mixin class for all classifiers in scikit-learn | 6259905a004d5f362081fae0 |
class RendezvousError(Exception): <NEW_LINE> <INDENT> pass | Represents the base type for rendezvous errors. | 6259905a16aa5153ce401ac8 |
class NotModeratorError(Error): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> self.message = message | Exception raised when user is not a moderator of a subreddit they
are trying to post to.
Attributes:
message: Explanation of the error | 6259905a1b99ca400229002a |
class Generator: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def generate_user() -> dict[str, str]: <NEW_LINE> <INDENT> user = { 'username': Generator.generate_user_name(), 'password': Generator.generate_password(), 'email': Generator.generate_mail() } <NEW_LINE> return user <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def generate_user_name() -> str: <NEW_LINE> <INDENT> username = "".join(random.choice(string.ascii_lowercase) for _ in range(2)) <NEW_LINE> username = username + "".join(random.choice(string.digits) for _ in range(4)) <NEW_LINE> username = username + "".join(random.choice(string.ascii_uppercase) for _ in range(5)) <NEW_LINE> return username <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def generate_password() -> str: <NEW_LINE> <INDENT> password = "".join(random.choice(string.ascii_lowercase) for _ in range(2)) <NEW_LINE> password = password + "".join(random.choice(string.digits) for _ in range(4)) <NEW_LINE> password = password + "".join(random.choice(string.ascii_uppercase) for _ in range(5)) <NEW_LINE> return password <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def generate_mail() -> str: <NEW_LINE> <INDENT> mails = ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]'] <NEW_LINE> return random.choice(mails) | Generator class to generate data. | 6259905a4428ac0f6e659b21 |
class LoginManagerHelper(): <NEW_LINE> <INDENT> headers = {"Content-Type": "application/json"} <NEW_LINE> login_url = get_config("hackathon-api.endpoint") + "/api/user/login" <NEW_LINE> def load_user(self, id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> req = requests.get(self.login_url, {"id": id}) <NEW_LINE> login_user = User(json.loads(req.content)) <NEW_LINE> return login_user <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> log.error(e) <NEW_LINE> return None <NEW_LINE> <DEDENT> <DEDENT> def logout(self, token): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> requests.delete(self.login_url, headers={"token": token}) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> log.error(e) <NEW_LINE> <DEDENT> session.pop("token", "") <NEW_LINE> logout_user() <NEW_LINE> <DEDENT> def login(self, provider): <NEW_LINE> <INDENT> if provider == LOGIN_PROVIDER.DB: <NEW_LINE> <INDENT> return self.__mysql_login() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.__oauth_login(provider) <NEW_LINE> <DEDENT> <DEDENT> def __oauth_login(self, provider): <NEW_LINE> <INDENT> code = request.args.get('code') <NEW_LINE> oauth_resp = login_providers[provider].login({ "code": code }) <NEW_LINE> return self.__remote_login(oauth_resp) <NEW_LINE> <DEDENT> def __mysql_login(self): <NEW_LINE> <INDENT> data = { "provider": LOGIN_PROVIDER.DB, "openid": request.form['username'], "username": request.form['username'], "password": encode(request.form['password']) } <NEW_LINE> return self.__remote_login(data) <NEW_LINE> <DEDENT> def __remote_login(self, data): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> req = requests.post(self.login_url, json=data, headers=self.headers) <NEW_LINE> resp = req.json() <NEW_LINE> if "error" in resp: <NEW_LINE> <INDENT> log.debug("login failed: %r" % resp) <NEW_LINE> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> login_user = User(resp["user"]) <NEW_LINE> token = resp["token"] <NEW_LINE> return { "user": login_user, "token": token["token"] } <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> log.error(e) <NEW_LINE> return None | Helper class for flask-login.LoginManager | 6259905a07f4c71912bb0a21 |
class OBOTerm(CVTerm): <NEW_LINE> <INDENT> dot_graph_name = "ontology_part" <NEW_LINE> def __init__(self, term_id, namespace, name, ontology, url_fmt=None, relationships=None, **kwargs): <NEW_LINE> <INDENT> super(OBOTerm, self).__init__(term_id, namespace, name, url_fmt) <NEW_LINE> self.relationships = relationships if relationships is not None else [] <NEW_LINE> self.ontology = ontology <NEW_LINE> self.__dict__.update(kwargs) <NEW_LINE> self._key = ontology.term2index[self.term_id] <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<OBOTerm %s>' % self.term_id <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '%s(%s)' % (self.term_id, self.name) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self._key == other._key <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return self._key != other._key <NEW_LINE> <DEDENT> def __lt__(self, other): <NEW_LINE> <INDENT> return self._key < other._key <NEW_LINE> <DEDENT> def __le__(self, other): <NEW_LINE> <INDENT> return self._key <= other._key <NEW_LINE> <DEDENT> def __gt__(self, other): <NEW_LINE> <INDENT> return self._key > other._key <NEW_LINE> <DEDENT> def __ge__(self, other): <NEW_LINE> <INDENT> return self._key >= other._key <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self._key) <NEW_LINE> <DEDENT> def compare_to(self, other, cache=None): <NEW_LINE> <INDENT> if self == other: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> a, b = (self, other) <NEW_LINE> if cache is not None and (a,b) in cache: <NEW_LINE> <INDENT> return cache[(a, b)] <NEW_LINE> <DEDENT> parents, _ = self.ontology.transitive_closure([a.term_id]) <NEW_LINE> if b.term_id in parents: <NEW_LINE> <INDENT> retval = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parents, _ = self.ontology.transitive_closure([b.term_id]) <NEW_LINE> if a.term_id in parents: <NEW_LINE> <INDENT> retval = -1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> retval = None <NEW_LINE> <DEDENT> <DEDENT> if cache is not None: <NEW_LINE> <INDENT> cache[(a,b)] = retval <NEW_LINE> <DEDENT> return retval | Open Biomedical Ontologies term. | 6259905a76e4537e8c3f0b72 |
@public <NEW_LINE> @implementer(IBounceDetector) <NEW_LINE> class LLNL: <NEW_LINE> <INDENT> def process(self, msg): <NEW_LINE> <INDENT> for line in body_line_iterator(msg): <NEW_LINE> <INDENT> mo = acre.search(line) <NEW_LINE> if mo: <NEW_LINE> <INDENT> address = mo.group('addr').encode('us-ascii') <NEW_LINE> return NoTemporaryFailures, set([address]) <NEW_LINE> <DEDENT> <DEDENT> return NoFailures | LLNL's custom Sendmail bounce message. | 6259905a462c4b4f79dbcfeb |
class ConnectionError(TransportError): <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return 'ConnectionError(%s) caused by: %s(%s)' % ( self.error, self.info.__class__.__name__, self.info) | Error raised when there was an exception while talking to ES. | 6259905a8e7ae83300eea673 |
class TestBlockDeviceAPIAttachDetach(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.mock_client = MagicMock() <NEW_LINE> self.mock_client.con_info = CONF_INFO_MOCK <NEW_LINE> self.mock_client.backend_type = messages.SCBE_STRING <NEW_LINE> self.mock_client.map_volume = MagicMock() <NEW_LINE> self.mock_client.unmap_volume = MagicMock() <NEW_LINE> self.driver_obj = driver.IBMStorageBlockDeviceAPI( UUID1, self.mock_client, DRIVER_BASIC_CONF) <NEW_LINE> self.driver_obj._host_ops.rescan_scsi = MagicMock() <NEW_LINE> self.expacted_blockdevicevolume = BlockDeviceVolume( blockdevice_id=unicode('999'), size=10, attached_to=None, dataset_id=UUID(UUID1_STR), ) <NEW_LINE> <DEDENT> def test_attach_volume_already_attached(self): <NEW_LINE> <INDENT> self.expacted_blockdevicevolume = self.expacted_blockdevicevolume.set(attached_to=u'fake-host') <NEW_LINE> self.driver_obj._get_volume = MagicMock(return_value=self.expacted_blockdevicevolume) <NEW_LINE> self.assertRaises( AlreadyAttachedVolume, self.driver_obj.attach_volume, unicode(UUID1_STR), 'fake-host') <NEW_LINE> <DEDENT> def test_attach_volume_succeed(self): <NEW_LINE> <INDENT> self.expacted_blockdevicevolume = self.expacted_blockdevicevolume.set(attached_to=None) <NEW_LINE> self.driver_obj._get_volume = MagicMock(return_value=self.expacted_blockdevicevolume) <NEW_LINE> attached_to = self.driver_obj.attach_volume( unicode(UUID1_STR), u'fake-host').attached_to <NEW_LINE> self.assertEqual(attached_to, 'fake-host') <NEW_LINE> <DEDENT> def test_attach_volume_already_detached(self): <NEW_LINE> <INDENT> self.expacted_blockdevicevolume = self.expacted_blockdevicevolume.set(attached_to=None) <NEW_LINE> self.driver_obj._get_volume = MagicMock(return_value=self.expacted_blockdevicevolume) <NEW_LINE> self.assertRaises( UnattachedVolume, self.driver_obj.detach_volume, unicode(UUID1_STR)) <NEW_LINE> <DEDENT> def test_detach_volume_succeed(self): <NEW_LINE> <INDENT> self.expacted_blockdevicevolume = self.expacted_blockdevicevolume.set(attached_to=u'fake-host') <NEW_LINE> self.driver_obj._get_volume = MagicMock(return_value=self.expacted_blockdevicevolume) <NEW_LINE> self.driver_obj._clean_up_device_before_unmap = Mock() <NEW_LINE> self.assertEqual( None, self.driver_obj.detach_volume(unicode(UUID1_STR))) | Unit testing for IBMStorageBlockDeviceAPI Class attach detach methods | 6259905a460517430c432b45 |
class Scrape(object): <NEW_LINE> <INDENT> def __init__(self, soup): <NEW_LINE> <INDENT> self.soup = soup <NEW_LINE> <DEDENT> def links(self): <NEW_LINE> <INDENT> homepage_url = "http://www.agriculture.gov.au" <NEW_LINE> atags = self.soup.find('ul', class_="flex-container").find_all('a') <NEW_LINE> links = [homepage_url+atag['href'] for atag in atags if atag['href'].startswith('/')] <NEW_LINE> return links <NEW_LINE> <DEDENT> def image(self): <NEW_LINE> <INDENT> homepage_url = "http://www.agriculture.gov.au" <NEW_LINE> try: <NEW_LINE> <INDENT> image_url= homepage_url + self.soup.find('div', class_="pest-header-image").find('img')['src'] <NEW_LINE> urllib.request.urlretrieve(image_url, image_url.split('/')[-1]) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> image_url = homepage_url + self.soup.find('div', id="content_div_2393636").find('img')['src'] <NEW_LINE> urllib.request.urlretrieve(image_url, image_url.split('/')[-1]) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> image_url = '/no image' <NEW_LINE> <DEDENT> <DEDENT> return os.getcwd()+'/'+image_url.split('/')[-1],image_url <NEW_LINE> <DEDENT> def origin(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> origin = [strong.next_sibling for strong in self.soup.find('div', class_="pest-header-content").find_all('strong') if 'Origin' in strong.text] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> origin = [''] <NEW_LINE> <DEDENT> return origin[0] <NEW_LINE> <DEDENT> def disease_name(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> disease_name = self.soup.find('div', class_="pest-header-content").find('h2').text <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> disease_name = self.soup.find('div', class_="page-content full-width").find('h1').text <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> disease_name = 'no data' <NEW_LINE> <DEDENT> <DEDENT> return disease_name <NEW_LINE> <DEDENT> def identify_the_pest(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ptags = self.soup.find_all('h3',class_="trigger")[0].find_next('div', class_="hide").find_all('p') <NEW_LINE> para = '' <NEW_LINE> for p in ptags: <NEW_LINE> <INDENT> para +=p.text.strip().replace('\r\n','') <NEW_LINE> <DEDENT> print(para) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> para = 'no data' <NEW_LINE> <DEDENT> return para <NEW_LINE> <DEDENT> def legally_come_into_australia(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ptags = self.soup.find_all('h3',class_="trigger")[1].find_next('div', class_="hide").find_all('p') <NEW_LINE> para = '' <NEW_LINE> for p in ptags: <NEW_LINE> <INDENT> para +=p.text.strip().replace('\r\n','') <NEW_LINE> <DEDENT> print(para) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> para = 'no data' <NEW_LINE> <DEDENT> return para <NEW_LINE> <DEDENT> def suspect_specimens(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ptags = self.soup.find_all('h3',class_="trigger")[2].find_next('div', class_="hide").find_all('p') <NEW_LINE> para = '' <NEW_LINE> for p in ptags: <NEW_LINE> <INDENT> para +=p.text.strip().replace('\r\n','') <NEW_LINE> <DEDENT> print(para) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> para = '' <NEW_LINE> <DEDENT> return para | fethes every field | 6259905add821e528d6da473 |
class UtilCCHelper(object): <NEW_LINE> <INDENT> def __init__(self, type_manager): <NEW_LINE> <INDENT> self._type_manager = type_manager <NEW_LINE> <DEDENT> def PopulateArrayFromDictionary(self, array_prop, src, name, dst): <NEW_LINE> <INDENT> prop = array_prop.item_type <NEW_LINE> sub = { 'namespace': _API_UTIL_NAMESPACE, 'name': name, 'src': src, 'dst': dst, } <NEW_LINE> sub['type'] = self._type_manager.GetCppType(prop), <NEW_LINE> if array_prop.optional: <NEW_LINE> <INDENT> val = ('%(namespace)s::PopulateOptionalArrayFromDictionary' '(*%(src)s, "%(name)s", &%(dst)s)') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> val = ('%(namespace)s::PopulateArrayFromDictionary' '(*%(src)s, "%(name)s", &%(dst)s)') <NEW_LINE> <DEDENT> return val % sub <NEW_LINE> <DEDENT> def PopulateArrayFromList(self, src, dst, optional): <NEW_LINE> <INDENT> if optional: <NEW_LINE> <INDENT> val = '%(namespace)s::PopulateOptionalArrayFromList(*%(src)s, &%(dst)s)' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> val = '%(namespace)s::PopulateArrayFromList(*%(src)s, &%(dst)s)' <NEW_LINE> <DEDENT> return val % { 'namespace': _API_UTIL_NAMESPACE, 'src': src, 'dst': dst } <NEW_LINE> <DEDENT> def CreateValueFromArray(self, src, optional): <NEW_LINE> <INDENT> if optional: <NEW_LINE> <INDENT> name = 'CreateValueFromOptionalArray' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = 'CreateValueFromArray' <NEW_LINE> <DEDENT> return '%s::%s(%s)' % (_API_UTIL_NAMESPACE, name, src) <NEW_LINE> <DEDENT> def GetIncludePath(self): <NEW_LINE> <INDENT> return '#include "tools/json_schema_compiler/util.h"' <NEW_LINE> <DEDENT> def GetValueTypeString(self, value, is_ptr=False): <NEW_LINE> <INDENT> call = '.GetType()' <NEW_LINE> if is_ptr: <NEW_LINE> <INDENT> call = '->GetType()' <NEW_LINE> <DEDENT> return 'json_schema_compiler::util::ValueTypeToString(%s%s)' % (value, call) | A util class that generates code that uses
tools/json_schema_compiler/util.cc. | 6259905a435de62698e9d3ea |
class Queue: <NEW_LINE> <INDENT> def __init__(self, queue_dict, parent_name='root'): <NEW_LINE> <INDENT> self.absolute_capacity_used = queue_dict['absoluteUsedCapacity'] <NEW_LINE> self.applications = queue_dict['numApplications'] <NEW_LINE> self.capacity_used = queue_dict['usedCapacity'] <NEW_LINE> self.name = '.'.join([parent_name, queue_dict['queueName']]) <NEW_LINE> self.resources_used_memory_mb = queue_dict['resourcesUsed']['memory'] <NEW_LINE> self.resources_used_vcpus = queue_dict['resourcesUsed']['vCores'] <NEW_LINE> if 'numContainers' in queue_dict: <NEW_LINE> <INDENT> self.containers = queue_dict['numContainers'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.containers = 0 | REST representation of a queue
Has these properties:
* absolute_capacity_used - amount of cluster's max capacity it is using
* applications - number of applications currently running
* capacity_used - amount of this queue's max capacity it is using
* containers - Number of containers used. Only leaf queues can have
non-zero values
* name - fully qualified name of the queue
* resources_used_vcpus - Number of virtual CPUs in use
* resources_used_memory_mb - Amount of memory (in MB) in use | 6259905a627d3e7fe0e08472 |
class IndexTypeGoodsBanner(BaseModel): <NEW_LINE> <INDENT> DISPLAY_TYPE_CHOICES = ( (0, "标题"), (1, "图片") ) <NEW_LINE> type = models.ForeignKey( 'GoodsType', verbose_name='商品类型', on_delete=models.CASCADE) <NEW_LINE> sku = models.ForeignKey( 'GoodsSKU', verbose_name='商品SKU', on_delete=models.CASCADE) <NEW_LINE> display_type = models.SmallIntegerField( default=1, choices=DISPLAY_TYPE_CHOICES, verbose_name='展示类型') <NEW_LINE> index = models.SmallIntegerField(default=0, verbose_name='展示顺序') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> db_table = 'df_index_type_goods' <NEW_LINE> verbose_name = "分类展示商品" <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.sku.name | 首页分类商品展示模型类 | 6259905ae64d504609df9ec2 |
class __NonDiffusionTerm(_NonDiffusionTerm): <NEW_LINE> <INDENT> pass | Dummy subclass for tests | 6259905a99cbb53fe68324c6 |
class PercentileMetric(Model): <NEW_LINE> <INDENT> _validation = { 'start_time': {'readonly': True}, 'end_time': {'readonly': True}, 'time_grain': {'readonly': True}, 'name': {'readonly': True}, 'metric_values': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'start_time': {'key': 'startTime', 'type': 'iso-8601'}, 'end_time': {'key': 'endTime', 'type': 'iso-8601'}, 'time_grain': {'key': 'timeGrain', 'type': 'str'}, 'unit': {'key': 'unit', 'type': 'str'}, 'name': {'key': 'name', 'type': 'MetricName'}, 'metric_values': {'key': 'metricValues', 'type': '[PercentileMetricValue]'}, } <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(PercentileMetric, self).__init__(**kwargs) <NEW_LINE> self.start_time = None <NEW_LINE> self.end_time = None <NEW_LINE> self.time_grain = None <NEW_LINE> self.unit = kwargs.get('unit', None) <NEW_LINE> self.name = None <NEW_LINE> self.metric_values = None | Percentile Metric data.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar start_time: The start time for the metric (ISO-8601 format).
:vartype start_time: datetime
:ivar end_time: The end time for the metric (ISO-8601 format).
:vartype end_time: datetime
:ivar time_grain: The time grain to be used to summarize the metric
values.
:vartype time_grain: str
:param unit: The unit of the metric. Possible values include: 'Count',
'Bytes', 'Seconds', 'Percent', 'CountPerSecond', 'BytesPerSecond',
'Milliseconds'
:type unit: str or ~azure.mgmt.cosmosdb.models.UnitType
:ivar name: The name information for the metric.
:vartype name: ~azure.mgmt.cosmosdb.models.MetricName
:ivar metric_values: The percentile metric values for the specified time
window and timestep.
:vartype metric_values:
list[~azure.mgmt.cosmosdb.models.PercentileMetricValue] | 6259905aa17c0f6771d5d695 |
class _Bucket: <NEW_LINE> <INDENT> pass | Anonymous attribute-bucket class. | 6259905a8a43f66fc4bf3774 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.