code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class ProgressBar(object): <NEW_LINE> <INDENT> def __init__(self, task_num=0, bar_width=50, start=True, file=sys.stdout): <NEW_LINE> <INDENT> self.task_num = task_num <NEW_LINE> max_bar_width = self._get_max_bar_width() <NEW_LINE> self.bar_width = ( bar_width if bar_width <= max_bar_width else max_bar_width) <NEW_LINE> self.completed = 0 <NEW_LINE> self.file = file <NEW_LINE> if start: <NEW_LINE> <INDENT> self.start() <NEW_LINE> <DEDENT> <DEDENT> def _get_max_bar_width(self): <NEW_LINE> <INDENT> if sys.version_info > (3, 3): <NEW_LINE> <INDENT> from shutil import get_terminal_size <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> from backports.shutil_get_terminal_size import get_terminal_size <NEW_LINE> <DEDENT> terminal_width, _ = get_terminal_size() <NEW_LINE> max_bar_width = min(int(terminal_width * 0.6), terminal_width - 50) <NEW_LINE> if max_bar_width < 10: <NEW_LINE> <INDENT> print('terminal width is too small ({}), please consider ' 'widen the terminal for better progressbar ' 'visualization'.format(terminal_width)) <NEW_LINE> max_bar_width = 10 <NEW_LINE> <DEDENT> return max_bar_width <NEW_LINE> <DEDENT> def start(self): <NEW_LINE> <INDENT> if self.task_num > 0: <NEW_LINE> <INDENT> self.file.write('[{}] 0/{}, elapsed: 0s, ETA:'.format( ' ' * self.bar_width, self.task_num)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.file.write('completed: 0, elapsed: 0s') <NEW_LINE> <DEDENT> self.file.flush() <NEW_LINE> self.timer = Timer() <NEW_LINE> <DEDENT> def update(self): <NEW_LINE> <INDENT> self.completed += 1 <NEW_LINE> elapsed = self.timer.since_start() <NEW_LINE> fps = self.completed / elapsed <NEW_LINE> if self.task_num > 0: <NEW_LINE> <INDENT> percentage = self.completed / float(self.task_num) <NEW_LINE> eta = int(elapsed * (1 - percentage) / percentage + 0.5) <NEW_LINE> mark_width = int(self.bar_width * percentage) <NEW_LINE> bar_chars = '>' * mark_width + ' ' * (self.bar_width - mark_width) <NEW_LINE> self.file.write( '\r[{}] {}/{}, {:.1f} task/s, elapsed: {}s, ETA: {:5}s'.format( bar_chars, self.completed, self.task_num, fps, int(elapsed + 0.5), eta)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.file.write( 'completed: {}, elapsed: {}s, {:.1f} tasks/s'.format( self.completed, int(elapsed + 0.5), fps)) <NEW_LINE> <DEDENT> self.file.flush() | A progress bar which can print the progress | 62598fc6ff9c53063f51a954 |
class StatelessServiceSpec(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.placement = PlacementSpec() <NEW_LINE> self.name = "" <NEW_LINE> self.count = 1 <NEW_LINE> self.extended = {} | Details of stateless service creation.
This is *not* supposed to contain all the configuration
of the services: it's just supposed to be enough information to
execute the binaries. | 62598fc626068e7796d4cc64 |
class abstractModel(QtGui.QFrame): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> QtGui.QFrame.__init__(self) <NEW_LINE> self.setupUi() <NEW_LINE> <DEDENT> def setupUi(self): <NEW_LINE> <INDENT> QtCore.QObject.connect(self.bAdd, QtCore.SIGNAL("clicked()"), self.ladd) <NEW_LINE> QtCore.QObject.connect(self.bRemove, QtCore.SIGNAL("clicked()"), self.lremove) <NEW_LINE> QtCore.QObject.connect(self.lWords, QtCore.SIGNAL("currentRowChanged(int)"), self.changed) <NEW_LINE> <DEDENT> def ladd(self): <NEW_LINE> <INDENT> if self.selected: <NEW_LINE> <INDENT> new1=self.selected <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new1=self.defClass(self.defText.text().__str__()) <NEW_LINE> self.model[new1.name]=new1 <NEW_LINE> self.items[new1.name]=[QtGui.QListWidgetItem(new1.name,self.lWords)] <NEW_LINE> <DEDENT> if new1.syl!=self.defSyl.value(): <NEW_LINE> <INDENT> new1.syllables=self.defSyl.value() <NEW_LINE> <DEDENT> return new1 <NEW_LINE> <DEDENT> def lremove(self): <NEW_LINE> <INDENT> item=self.lWords.currentItem() <NEW_LINE> if (item == None): <NEW_LINE> <INDENT> print("no item") <NEW_LINE> return <NEW_LINE> <DEDENT> self.items[item.text().__str__()]=None <NEW_LINE> self.lWords.takeItem(self.lWords.currentRow()) <NEW_LINE> for key in self.dict[:]: <NEW_LINE> <INDENT> if key.name==item.text().__str__(): <NEW_LINE> <INDENT> self.dict.remove(key) <NEW_LINE> break; <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def changed(self, int): <NEW_LINE> <INDENT> if int==-1: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> self.selected=self.model[self.lWords.currentItem().text().__str__()] <NEW_LINE> self.defText.setText(self.selected.name) <NEW_LINE> return self.selected <NEW_LINE> <DEDENT> def populate(self, dict): <NEW_LINE> <INDENT> for i in xrange(self.lWords.count()-1, -1, -1): <NEW_LINE> <INDENT> self.lWords.takeItem(i) <NEW_LINE> <DEDENT> self.items={} <NEW_LINE> self.model={} <NEW_LINE> for word in dict: <NEW_LINE> <INDENT> self.model[word.name]=word <NEW_LINE> self.items[word.name]=QtGui.QListWidgetItem(word.name, self.lWords) <NEW_LINE> <DEDENT> self.dict=dict <NEW_LINE> <DEDENT> def process(self, str): <NEW_LINE> <INDENT> str=str.__str__() <NEW_LINE> if str == "": <NEW_LINE> <INDENT> self.defSyl.setValue(0); <NEW_LINE> self.selected=None <NEW_LINE> self.lWords.setCurrentRow(-1) <NEW_LINE> return None <NEW_LINE> <DEDENT> if self.model.has_key(str): <NEW_LINE> <INDENT> self.selected=self.model[str] <NEW_LINE> word=self.selected <NEW_LINE> if self.lWords.currentRow()==-1: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.lWords.setCurrentItem(self.items[word.name][0]) <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.lWords.setCurrentItem(self.items[word.name]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.selected=None <NEW_LINE> word=self.defClass(str) <NEW_LINE> self.lWords.setCurrentRow(-1) <NEW_LINE> <DEDENT> self.defSyl.setValue(spruceData.determineSyllables(str)) <NEW_LINE> return word <NEW_LINE> <DEDENT> def openRelative(self): <NEW_LINE> <INDENT> self.relativeModel=RelativeModel() <NEW_LINE> self.relativeModel.setupUi() | Base class for the tabs, does most of the work | 62598fc67047854f4633f6db |
class PhysicalExpansionFilter(DirectFilter): <NEW_LINE> <INDENT> types = ('PhysicalCard',) <NEW_LINE> def __init__(self, sExpansion): <NEW_LINE> <INDENT> if sExpansion is not None: <NEW_LINE> <INDENT> self._iId = IExpansion(sExpansion).id <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._iId = None <NEW_LINE> <DEDENT> <DEDENT> def _get_expression(self): <NEW_LINE> <INDENT> oTable = Table('physical_card') <NEW_LINE> return oTable.expansion_id == self._iId | Filter PhysicalCard based on the PhysicalCard expansion | 62598fc63617ad0b5ee06450 |
class MultFactory(OperationFactory): <NEW_LINE> <INDENT> def create_operation(self): <NEW_LINE> <INDENT> return OperationMult() | Factory for OperationMult. | 62598fc6099cdd3c63675566 |
class Form0(QWidget, Ui_Form): <NEW_LINE> <INDENT> def __init__(self, parent=None): <NEW_LINE> <INDENT> super(Form0, self).__init__(parent) <NEW_LINE> self.setupUi(self) <NEW_LINE> self.cam = cv2.VideoCapture(0) <NEW_LINE> self.image = QtGui.QImage(0, 0, QtGui.QImage.Format_RGB888) <NEW_LINE> self.timer = QtCore.QTimer(self) <NEW_LINE> self.timer.timeout.connect(self.tick) <NEW_LINE> self.timer.start(33) <NEW_LINE> self.time_last = 0 <NEW_LINE> <DEDENT> def closeEvent(self, event): <NEW_LINE> <INDENT> self.cam.release() <NEW_LINE> <DEDENT> def paintEvent(self, event): <NEW_LINE> <INDENT> painter = QtGui.QPainter(self) <NEW_LINE> painter.drawImage(QtCore.QPoint(0, 0), self.image) <NEW_LINE> <DEDENT> @pyqtSlot() <NEW_LINE> def on_pushButton_clicked(self): <NEW_LINE> <INDENT> self.timer.stop() <NEW_LINE> self.cam.release() <NEW_LINE> <DEDENT> def tick(self): <NEW_LINE> <INDENT> frame = self.cam.read() <NEW_LINE> if frame[0]: <NEW_LINE> <INDENT> frame = frame[1] <NEW_LINE> frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) <NEW_LINE> Z = frame.reshape((-1,3)) <NEW_LINE> Z = np.float32(Z) <NEW_LINE> criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) <NEW_LINE> K = 3 <NEW_LINE> ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS) <NEW_LINE> center = np.uint8(center) <NEW_LINE> res = center[label.flatten()] <NEW_LINE> frame = res.reshape((frame.shape)) <NEW_LINE> self.image = QtGui.QImage(frame.tobytes(), frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888) <NEW_LINE> if frame.shape[0]/frame.shape[1]>self.width()/self.height(): <NEW_LINE> <INDENT> self.image = self.image.scaledToWidth(self.width()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.image = self.image.scaledToHeight(self.height()) <NEW_LINE> <DEDENT> <DEDENT> t = time.time() <NEW_LINE> self.pushButton.setText("{:.2f}".format(1/(t - self.time_last)) + 'fps') <NEW_LINE> self.time_last = t <NEW_LINE> self.update() | Class documentation goes here. | 62598fc6656771135c489978 |
class ChatMember(Result): <NEW_LINE> <INDENT> def __init__(self, user, status): <NEW_LINE> <INDENT> super(ChatMember, self).__init__() <NEW_LINE> assert(user is not None) <NEW_LINE> assert(isinstance(user, User)) <NEW_LINE> self.user = user <NEW_LINE> assert(status is not None) <NEW_LINE> assert(isinstance(status, str)) <NEW_LINE> self.status = status <NEW_LINE> <DEDENT> def to_array(self): <NEW_LINE> <INDENT> array = super(ChatMember, self).to_array() <NEW_LINE> array['user'] = self.user.to_array() <NEW_LINE> array['status'] = str(self.status) <NEW_LINE> return array <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_array(array): <NEW_LINE> <INDENT> if array is None or not array: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> assert(isinstance(array, dict)) <NEW_LINE> data = {} <NEW_LINE> data['user'] = User.from_array(array.get('user')) <NEW_LINE> data['status'] = str(array.get('status')) <NEW_LINE> return ChatMember(**data) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "ChatMember(user={self.user!r}, status={self.status!r})".format(self=self) <NEW_LINE> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> return key in ["user", "status"] | This object contains information about one member of the chat.
https://core.telegram.org/bots/api#chatmember | 62598fc67b180e01f3e491d4 |
class CreateDistanceEvaluator(object): <NEW_LINE> <INDENT> def __init__(self, data, distance_calculator): <NEW_LINE> <INDENT> self._data = data <NEW_LINE> self._distances = distance_calculator <NEW_LINE> <DEDENT> def distance_evaluator(self, from_node, to_node): <NEW_LINE> <INDENT> from_node_str = str(self._data.locations[from_node]).replace(r', ', '_').strip('[]').strip('()') <NEW_LINE> to_node_str = str(self._data.locations[to_node]).replace(r', ', '_').strip('[]').strip('()') <NEW_LINE> return self._distances[from_node_str][to_node_str]['distance'] | Creates callback to return distance between points. | 62598fc6aad79263cf42eade |
class Planet(): <NEW_LINE> <INDENT> def __init__(self,root): <NEW_LINE> <INDENT> self.Uranium=0 <NEW_LINE> self.Titanium=0 <NEW_LINE> self.Hydrocarbons=0 <NEW_LINE> self.Water=0 <NEW_LINE> self.Silicon=0 <NEW_LINE> self.Inhabitable=0 <NEW_LINE> self.Size=random.randint(1,1000) <NEW_LINE> self.Dilithium=0 <NEW_LINE> self.Model = os.path.join(root,'models/planets/planet.egg') <NEW_LINE> <DEDENT> def SetPlanetSize(self,PlanetSize): <NEW_LINE> <INDENT> self.Size=PlanetSize <NEW_LINE> <DEDENT> def SetResource(self,resource): <NEW_LINE> <INDENT> if self.Size >= 100: <NEW_LINE> <INDENT> self.Type = 'Gas Giant' <NEW_LINE> <DEDENT> if self.Size <= 10 and random.randint(1,10) <= 7: <NEW_LINE> <INDENT> self.Inhabitable = 1 <NEW_LINE> self.Type = 'Class M' <NEW_LINE> return(1) <NEW_LINE> <DEDENT> if resource == 'Hydrocarbons': <NEW_LINE> <INDENT> self.Hydrocarbons = (random.randint(50,200)) <NEW_LINE> <DEDENT> elif resource == 'Titanium': <NEW_LINE> <INDENT> self.Titanium = (random.randint(10,50)) <NEW_LINE> <DEDENT> elif resource == 'Uranium': <NEW_LINE> <INDENT> self.Uranium = (random.randint(1,10)) <NEW_LINE> <DEDENT> elif resource == 'Water': <NEW_LINE> <INDENT> self.Water = (random.randint(100,1000)) <NEW_LINE> <DEDENT> elif resource == 'Silicon': <NEW_LINE> <INDENT> self.Silicon = (random.randint(10,150)) <NEW_LINE> <DEDENT> elif resource == 'Inhabitable': <NEW_LINE> <INDENT> self.Inhabitable = 1 <NEW_LINE> <DEDENT> elif resource == 'Dilithium': <NEW_LINE> <INDENT> self.Dilithium = (random.randint(1,10)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return(0) <NEW_LINE> <DEDENT> def GetResourceList(self): <NEW_LINE> <INDENT> return([['Uranium',self.Uranium],['Titanium',self.Titanium],['Water',self.Water],['Hydrocarbons',self.Hydrocarbons],['Silicon',self.Silicon],['Dilithium',self.Dilithium],['Inhabitable', self.Inhabitable]]) | Planet represents a single planet member of a solar system. | 62598fc6091ae35668704f33 |
class seqtune(TestCase): <NEW_LINE> <INDENT> _multiprocess_can_split_ = True <NEW_LINE> name = "mp_seqtune" <NEW_LINE> description = "mp_seqtune tool tests" <NEW_LINE> cmd = [os.path.join(BASEPATH, "targets", "generic", "tools", "mp_seqtune.py")] <NEW_LINE> target = os.path.join(BASEPATH, "targets") <NEW_LINE> trials = 3 <NEW_LINE> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def tearDownClass(cls): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def setUp(self): <NEW_LINE> <INDENT> self.tdirname = mkdtemp(prefix="microprobe_%s_" % self.name, suffix=".seqtune") <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> shutil.rmtree(self.tdirname, True) <NEW_LINE> <DEDENT> def test_001(self): <NEW_LINE> <INDENT> self._wrapper( "riscv_v22-riscv_generic-riscv64_test_p", extra="-B 1024 -re ADD_V0:XOR_V0:1-2 -p " + "-me 1-2:2048:1:144:1:0:1:0 " + "-seq ADD_V0,ADDI_V0,FMUL.S_V0,MULW_V0,LD_V0,SD_V0" ) <NEW_LINE> <DEDENT> def test_002(self): <NEW_LINE> <INDENT> self._wrapper( "riscv_v22-riscv_generic-riscv64_linux_gcc", extra="-B 1024 -re ADD_V0:XOR_V0:1-2 -p " + "-me 1-2:2048:1:144:1:0:1:0 " + "-seq ADD_V0,ADDI_V0,FMUL.S_V0,MULW_V0,LD_V0,SD_V0" ) <NEW_LINE> <DEDENT> def _wrapper(self, target, extra=None): <NEW_LINE> <INDENT> test_cmd = self.cmd[:] <NEW_LINE> test_cmd.extend(["-T", target]) <NEW_LINE> test_cmd.extend(["-P", self.target]) <NEW_LINE> test_cmd.extend(["-D", self.tdirname]) <NEW_LINE> if extra is not None: <NEW_LINE> <INDENT> extra = extra.strip() <NEW_LINE> test_cmd.extend(extra.split(' ')) <NEW_LINE> <DEDENT> print(" ".join(test_cmd)) <NEW_LINE> for trial in range(0, self.trials): <NEW_LINE> <INDENT> print("Trial %s" % trial) <NEW_LINE> tfile = SpooledTemporaryFile() <NEW_LINE> error_code = subprocess.call( test_cmd, stdout=tfile, stderr=subprocess.STDOUT ) <NEW_LINE> if error_code == 0: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> if error_code != 0: <NEW_LINE> <INDENT> tfile.seek(0) <NEW_LINE> print(tfile.read()) <NEW_LINE> <DEDENT> self.assertEqual(error_code, 0) | seqtune Test Class. | 62598fc6cc40096d6161a35d |
class Onlinelog(object): <NEW_LINE> <INDENT> def select(self): <NEW_LINE> <INDENT> sql = """select * from v$logfile""" <NEW_LINE> results = Oracle().select(sql) <NEW_LINE> return results <NEW_LINE> <DEDENT> def create(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def drop(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def alter(self): <NEW_LINE> <INDENT> pass | docstring for Onlinelogs | 62598fc67b180e01f3e491d5 |
class Event(db.Model): <NEW_LINE> <INDENT> id = db.Column(db.Integer, primary_key=True) <NEW_LINE> title = db.Column(db.String(35), index=True) <NEW_LINE> description = db.Column(db.String(256), index=True) <NEW_LINE> date = db.Column(db.String(256), index=True) <NEW_LINE> startTime = db.Column(db.String(256), index=True) <NEW_LINE> endTime = db.Column(db.String(256), index=True) <NEW_LINE> user_id = db.Column(db.Integer, db.ForeignKey('user.id')) <NEW_LINE> def __repr__(self): <NEW_LINE> <INDENT> return '{}'.format(self.title) | This model contains information that is needed to create an event.
All of the variables for this class are listed below. | 62598fc6283ffb24f3cf3b90 |
class BitAndOpExpr(BinaryOpExpr): <NEW_LINE> <INDENT> def is_bit_and_op(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return '{} & {}'.format(self.lhs, self.rhs) | A bit-and operator (``&``). | 62598fc6bf627c535bcb17b3 |
class KML(object): <NEW_LINE> <INDENT> _features = [] <NEW_LINE> ns = None <NEW_LINE> def __init__(self, ns=None): <NEW_LINE> <INDENT> self._features = [] <NEW_LINE> if ns is None: <NEW_LINE> <INDENT> self.ns = config.NS <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.ns = ns <NEW_LINE> <DEDENT> <DEDENT> def from_string(self, xml_string): <NEW_LINE> <INDENT> if config.LXML: <NEW_LINE> <INDENT> element = etree.fromstring( xml_string, parser=etree.XMLParser(huge_tree=True) ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> element = etree.XML(xml_string) <NEW_LINE> <DEDENT> if element.tag.endswith('kml'): <NEW_LINE> <INDENT> ns = element.tag.rstrip('kml') <NEW_LINE> documents = element.findall('%sDocument' % ns) <NEW_LINE> for document in documents: <NEW_LINE> <INDENT> feature = Document(ns) <NEW_LINE> feature.from_element(document) <NEW_LINE> self.append(feature) <NEW_LINE> <DEDENT> folders = element.findall('%sFolder' % ns) <NEW_LINE> for folder in folders: <NEW_LINE> <INDENT> feature = Folder(ns) <NEW_LINE> feature.from_element(folder) <NEW_LINE> self.append(feature) <NEW_LINE> <DEDENT> placemarks = element.findall('%sPlacemark' % ns) <NEW_LINE> for placemark in placemarks: <NEW_LINE> <INDENT> feature = Placemark(ns) <NEW_LINE> feature.from_element(placemark) <NEW_LINE> self.append(feature) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError <NEW_LINE> <DEDENT> <DEDENT> def etree_element(self): <NEW_LINE> <INDENT> if not self.ns: <NEW_LINE> <INDENT> root = etree.Element('%skml' % self.ns) <NEW_LINE> root.set('xmlns', config.NS[1:-1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if config.LXML: <NEW_LINE> <INDENT> root = etree.Element( '%skml' % self.ns, nsmap={None: self.ns[1:-1]} ) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> root = etree.Element('%skml' % self.ns) <NEW_LINE> <DEDENT> <DEDENT> for feature in self.features(): <NEW_LINE> <INDENT> root.append(feature.etree_element()) <NEW_LINE> <DEDENT> return root <NEW_LINE> <DEDENT> def to_string(self, prettyprint=False): <NEW_LINE> <INDENT> if config.LXML and prettyprint: <NEW_LINE> <INDENT> return etree.tostring( self.etree_element(), encoding='utf-8', pretty_print=True).decode('UTF-8') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return etree.tostring( self.etree_element(), encoding='utf-8').decode('UTF-8') <NEW_LINE> <DEDENT> <DEDENT> def features(self): <NEW_LINE> <INDENT> for feature in self._features: <NEW_LINE> <INDENT> if isinstance(feature, (Document, Folder, Placemark)): <NEW_LINE> <INDENT> yield feature <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError( "Features must be instances of " "(Document, Folder, Placemark)" ) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def append(self, kmlobj): <NEW_LINE> <INDENT> if isinstance(kmlobj, (Document, Folder, Placemark)): <NEW_LINE> <INDENT> self._features.append(kmlobj) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError( "Features must be instances of (Document, Folder, Placemark)") | represents a KML File | 62598fc64a966d76dd5ef1e0 |
class SmartCrop(object): <NEW_LINE> <INDENT> def __init__(self, width=None, height=None): <NEW_LINE> <INDENT> self.width = width <NEW_LINE> self.height = height <NEW_LINE> <DEDENT> def compare_entropy(self, start_slice, end_slice, slice, difference): <NEW_LINE> <INDENT> start_entropy = histogram_entropy(start_slice) <NEW_LINE> end_entropy = histogram_entropy(end_slice) <NEW_LINE> if end_entropy and abs(start_entropy / end_entropy - 1) < 0.01: <NEW_LINE> <INDENT> if difference >= slice * 2: <NEW_LINE> <INDENT> return slice, slice <NEW_LINE> <DEDENT> half_slice = slice // 2 <NEW_LINE> return half_slice, slice - half_slice <NEW_LINE> <DEDENT> if start_entropy > end_entropy: <NEW_LINE> <INDENT> return 0, slice <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return slice, 0 <NEW_LINE> <DEDENT> <DEDENT> def process(self, img): <NEW_LINE> <INDENT> source_x, source_y = img.size <NEW_LINE> diff_x = int(source_x - min(source_x, self.width)) <NEW_LINE> diff_y = int(source_y - min(source_y, self.height)) <NEW_LINE> left = top = 0 <NEW_LINE> right, bottom = source_x, source_y <NEW_LINE> while diff_x: <NEW_LINE> <INDENT> slice = min(diff_x, max(diff_x // 5, 10)) <NEW_LINE> start = img.crop((left, 0, left + slice, source_y)) <NEW_LINE> end = img.crop((right - slice, 0, right, source_y)) <NEW_LINE> add, remove = self.compare_entropy(start, end, slice, diff_x) <NEW_LINE> left += add <NEW_LINE> right -= remove <NEW_LINE> diff_x = diff_x - add - remove <NEW_LINE> <DEDENT> while diff_y: <NEW_LINE> <INDENT> slice = min(diff_y, max(diff_y // 5, 10)) <NEW_LINE> start = img.crop((0, top, source_x, top + slice)) <NEW_LINE> end = img.crop((0, bottom - slice, source_x, bottom)) <NEW_LINE> add, remove = self.compare_entropy(start, end, slice, diff_y) <NEW_LINE> top += add <NEW_LINE> bottom -= remove <NEW_LINE> diff_y = diff_y - add - remove <NEW_LINE> <DEDENT> box = (left, top, right, bottom) <NEW_LINE> img = img.crop(box) <NEW_LINE> return img | Crop an image 'smartly' -- based on smart crop implementation from easy-thumbnails:
https://github.com/SmileyChris/easy-thumbnails/blob/master/easy_thumbnails/processors.py#L193
Smart cropping whittles away the parts of the image with the least entropy. | 62598fc6f548e778e596b8a8 |
class itkNumericTraitsVD1(object): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> __swig_destroy__ = _itkNumericTraitsPython.delete_itkNumericTraitsVD1 <NEW_LINE> def __init__(self, *args): <NEW_LINE> <INDENT> _itkNumericTraitsPython.itkNumericTraitsVD1_swiginit(self,_itkNumericTraitsPython.new_itkNumericTraitsVD1(*args)) <NEW_LINE> <DEDENT> def max(): <NEW_LINE> <INDENT> return _itkNumericTraitsPython.itkNumericTraitsVD1_max() <NEW_LINE> <DEDENT> max = staticmethod(max) <NEW_LINE> def min(): <NEW_LINE> <INDENT> return _itkNumericTraitsPython.itkNumericTraitsVD1_min() <NEW_LINE> <DEDENT> min = staticmethod(min) <NEW_LINE> def NonpositiveMin(): <NEW_LINE> <INDENT> return _itkNumericTraitsPython.itkNumericTraitsVD1_NonpositiveMin() <NEW_LINE> <DEDENT> NonpositiveMin = staticmethod(NonpositiveMin) <NEW_LINE> def ZeroValue(): <NEW_LINE> <INDENT> return _itkNumericTraitsPython.itkNumericTraitsVD1_ZeroValue() <NEW_LINE> <DEDENT> ZeroValue = staticmethod(ZeroValue) <NEW_LINE> def OneValue(): <NEW_LINE> <INDENT> return _itkNumericTraitsPython.itkNumericTraitsVD1_OneValue() <NEW_LINE> <DEDENT> OneValue = staticmethod(OneValue) | Proxy of C++ itkNumericTraitsVD1 class | 62598fc65fdd1c0f98e5e29a |
class two_level_weight_vector_generator_TestCase(unittest.TestCase): <NEW_LINE> <INDENT> def test1(self): <NEW_LINE> <INDENT> self.assertTrue(len(two_level_weight_vector_generator([3, 2], 8)) == 156) <NEW_LINE> <DEDENT> def test2(self): <NEW_LINE> <INDENT> self.assertTrue(len(two_level_weight_vector_generator([3, 2], 10)) == 275) <NEW_LINE> <DEDENT> def test3(self): <NEW_LINE> <INDENT> self.assertTrue(len(two_level_weight_vector_generator([2, 1], 15)) == 135) | Tests for `primes.py`. | 62598fc6ec188e330fdf8ba0 |
class RootItem(BaseItem): <NEW_LINE> <INDENT> def __init__(self, include_revision_types=False): <NEW_LINE> <INDENT> super(RootItem, self).__init__() <NEW_LINE> self.obj = None <NEW_LINE> self.children = [ContainerMetaItem(self)] <NEW_LINE> if include_revision_types: <NEW_LINE> <INDENT> self.children.append(RevisionMetaItem(self)) <NEW_LINE> <DEDENT> self.children.extend(sorted([EntityTypeItem(entity, link_fields, self) for entity, link_fields in (("Sequence", []), ("Shot", ["sg_sequence", "assets"]), ("Asset", []))])) | The root of the Shotgun entity tree | 62598fc6be7bc26dc9251fe1 |
class GroupViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet): <NEW_LINE> <INDENT> queryset = Group.objects.all() <NEW_LINE> serializer_class = serializers.GroupSerializer <NEW_LINE> def list(self, request, *args, **kwargs): <NEW_LINE> <INDENT> ret = OrderedDict() <NEW_LINE> for each in Group.objects.order_by('-grade', 'major', 'class_num'): <NEW_LINE> <INDENT> grade = str(each.grade) <NEW_LINE> major = each.major <NEW_LINE> if grade not in ret.keys(): <NEW_LINE> <INDENT> ret[grade] = OrderedDict() <NEW_LINE> <DEDENT> if major not in ret[grade]: <NEW_LINE> <INDENT> ret[grade][major] = [] <NEW_LINE> <DEDENT> ret[grade][major].append( serializers.GroupSerializer( each, context={'request': request}).data ) <NEW_LINE> <DEDENT> return Response(ret) <NEW_LINE> <DEDENT> def retrieve(self, request, *args, **kwargs): <NEW_LINE> <INDENT> return Response(super().retrieve(request, *args, **kwargs)) | Group view set. | 62598fc60fa83653e46f51f2 |
class History(models.Model): <NEW_LINE> <INDENT> task = models.ForeignKey(Task) <NEW_LINE> acknowledge_date = models.DateTimeField(default=timezone.now) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> month = self.acknowledge_date.month <NEW_LINE> if month < 10: <NEW_LINE> <INDENT> month = '0{}'.format(month) <NEW_LINE> <DEDENT> day = self.acknowledge_date.day <NEW_LINE> if day < 10: <NEW_LINE> <INDENT> day = '0{}'.format(day) <NEW_LINE> <DEDENT> hour = self.acknowledge_date.hour <NEW_LINE> if hour < 10: <NEW_LINE> <INDENT> hour = '0{}'.format(hour) <NEW_LINE> <DEDENT> minute = self.acknowledge_date.minute <NEW_LINE> if minute < 10: <NEW_LINE> <INDENT> minute = '0{}'.format(minute) <NEW_LINE> <DEDENT> return '{}{}{}_{}{}'.format(self.acknowledge_date.year, month, day, hour, minute) | Task Acknowledge History | 62598fc6167d2b6e312b7283 |
class MakeSetupCommand(Command): <NEW_LINE> <INDENT> def handle(self): <NEW_LINE> <INDENT> poet = self.poet <NEW_LINE> builder = Builder() <NEW_LINE> setup = builder._setup(poet) <NEW_LINE> builder._write_setup(setup, os.path.join(os.path.dirname(self.poet_file), 'setup.py')) | Renders a setup.py for testing purposes.
make:setup | 62598fc666673b3332c306e2 |
class IncorrectEndpointException(Exception): <NEW_LINE> <INDENT> pass | Raise exception on wrong or No endpoint provided | 62598fc6dc8b845886d538c8 |
class Gradient: <NEW_LINE> <INDENT> def __init__(self, uid, type_, stops=None): <NEW_LINE> <INDENT> self.uid = uid <NEW_LINE> self.type = type_ <NEW_LINE> self.stops = stops if stops is not None else [] <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return str.format("Gradient(uid={}, type={} stops={})", repr(self.uid), repr(self.type), repr(self.stops)) | Represents a gradient.
===Attributes===
uid - The unique id of this Gradient.
type - The type of this Gradient.
stops - The list of stops in this Gradient.
===Operations=== | 62598fc65fcc89381b2662d3 |
class MinimaxAgent(RandomAgent): <NEW_LINE> <INDENT> def __init__(self, evaluate_function, alpha_beta_pruning=False, max_depth=5): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.evaluate = evaluate_function <NEW_LINE> self.alpha_beta_pruning = alpha_beta_pruning <NEW_LINE> self.max_depth = max_depth <NEW_LINE> <DEDENT> def decide(self, state): <NEW_LINE> <INDENT> if not self.alpha_beta_pruning: <NEW_LINE> <INDENT> return self.minimax(state, state.current_player) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.minimax_with_ab_pruning(state, state.current_player) <NEW_LINE> <DEDENT> <DEDENT> def minimax(self, state, player, depth=1): <NEW_LINE> <INDENT> return super().decide(state) <NEW_LINE> <DEDENT> def minimax_with_ab_pruning(self, state, player, depth=1, alpha=float('inf'), beta=-float('inf')): <NEW_LINE> <INDENT> return super().decide(state) <NEW_LINE> <DEDENT> def learn(self, states, player_id): <NEW_LINE> <INDENT> pass | An agent that makes decisions using the Minimax algorithm, using a
evaluation function to approximately guess how good certain states
are when looking far into the future.
:param evaluation_function: The function used to make evaluate a
GameState. Should have the parameters (state, player_id) where
`state` is the GameState and `player_id` is the ID of the
player to calculate the expected payoff for.
:param alpha_beta_pruning: True if you would like to use
alpha-beta pruning.
:param max_depth: The maximum depth to search using the minimax
algorithm, before using estimates generated by the evaluation
function. | 62598fc6099cdd3c63675568 |
class NetworkInterfaceDnsSettings(Model): <NEW_LINE> <INDENT> _attribute_map = { 'dns_servers': {'key': 'dnsServers', 'type': '[str]'}, 'applied_dns_servers': {'key': 'appliedDnsServers', 'type': '[str]'}, 'internal_dns_name_label': {'key': 'internalDnsNameLabel', 'type': 'str'}, 'internal_fqdn': {'key': 'internalFqdn', 'type': 'str'}, 'internal_domain_name_suffix': {'key': 'internalDomainNameSuffix', 'type': 'str'}, } <NEW_LINE> def __init__(self, dns_servers=None, applied_dns_servers=None, internal_dns_name_label=None, internal_fqdn=None, internal_domain_name_suffix=None): <NEW_LINE> <INDENT> super(NetworkInterfaceDnsSettings, self).__init__() <NEW_LINE> self.dns_servers = dns_servers <NEW_LINE> self.applied_dns_servers = applied_dns_servers <NEW_LINE> self.internal_dns_name_label = internal_dns_name_label <NEW_LINE> self.internal_fqdn = internal_fqdn <NEW_LINE> self.internal_domain_name_suffix = internal_domain_name_suffix | DNS settings of a network interface.
:param dns_servers: List of DNS servers IP addresses. Use
'AzureProvidedDNS' to switch to azure provided DNS resolution.
'AzureProvidedDNS' value cannot be combined with other IPs, it must be the
only value in dnsServers collection.
:type dns_servers: list[str]
:param applied_dns_servers: If the VM that uses this NIC is part of an
Availability Set, then this list will have the union of all DNS servers
from all NICs that are part of the Availability Set. This property is what
is configured on each of those VMs.
:type applied_dns_servers: list[str]
:param internal_dns_name_label: Relative DNS name for this NIC used for
internal communications between VMs in the same virtual network.
:type internal_dns_name_label: str
:param internal_fqdn: Fully qualified DNS name supporting internal
communications between VMs in the same virtual network.
:type internal_fqdn: str
:param internal_domain_name_suffix: Even if internalDnsNameLabel is not
specified, a DNS entry is created for the primary NIC of the VM. This DNS
name can be constructed by concatenating the VM name with the value of
internalDomainNameSuffix.
:type internal_domain_name_suffix: str | 62598fc655399d3f05626825 |
class StandardRobot(Robot): <NEW_LINE> <INDENT> def updatePositionAndClean(self): <NEW_LINE> <INDENT> potential_new_position = self.position.getNewPosition(self.direction, self.speed) <NEW_LINE> if self.room.isPositionInRoom(potential_new_position) == True: <NEW_LINE> <INDENT> self.position = potential_new_position <NEW_LINE> self.room.cleanTileAtPosition(self.position) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.direction = random.randint(0, 360) | A StandardRobot is a Robot with the standard movement strategy.
At each time-step, a StandardRobot attempts to move in its current
direction; when it would hit a wall, it *instead* chooses a new direction
randomly. | 62598fc6bf627c535bcb17b5 |
class TemplateHelper(Bcfg2.Server.Plugin.Plugin, Bcfg2.Server.Plugin.Connector, Bcfg2.Server.Plugin.DirectoryBacked): <NEW_LINE> <INDENT> __author__ = 'chris.a.st.pierre@gmail.com' <NEW_LINE> ignore = re.compile(r'^(\.#.*|.*~|\..*\.(sw[px])|.*\.py[co])$') <NEW_LINE> patterns = MODULE_RE <NEW_LINE> __child__ = HelperModule <NEW_LINE> def __init__(self, core, datastore): <NEW_LINE> <INDENT> Bcfg2.Server.Plugin.Plugin.__init__(self, core, datastore) <NEW_LINE> Bcfg2.Server.Plugin.Connector.__init__(self) <NEW_LINE> Bcfg2.Server.Plugin.DirectoryBacked.__init__(self, self.data, core.fam) <NEW_LINE> <DEDENT> def get_additional_data(self, _): <NEW_LINE> <INDENT> return dict([(h._module_name, h) for h in self.entries.values()]) | A plugin to provide helper classes and functions to templates | 62598fc63d592f4c4edbb1bf |
class EulerGamma(NumberSymbol, metaclass=Singleton): <NEW_LINE> <INDENT> is_real = True <NEW_LINE> is_positive = True <NEW_LINE> is_negative = False <NEW_LINE> is_irrational = None <NEW_LINE> is_number = True <NEW_LINE> __slots__ = () <NEW_LINE> def _latex(self, printer): <NEW_LINE> <INDENT> return r"\gamma" <NEW_LINE> <DEDENT> def __int__(self): <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> def _as_mpf_val(self, prec): <NEW_LINE> <INDENT> v = mlib.libhyper.euler_fixed(prec + 10) <NEW_LINE> rv = mlib.from_man_exp(v, -prec - 10) <NEW_LINE> return mpf_norm(rv, prec) <NEW_LINE> <DEDENT> def approximation_interval(self, number_cls): <NEW_LINE> <INDENT> if issubclass(number_cls, Integer): <NEW_LINE> <INDENT> return (S.Zero, S.One) <NEW_LINE> <DEDENT> elif issubclass(number_cls, Rational): <NEW_LINE> <INDENT> return (S.Half, Rational(3, 5, 1)) <NEW_LINE> <DEDENT> <DEDENT> def _sage_(self): <NEW_LINE> <INDENT> import sage.all as sage <NEW_LINE> return sage.euler_gamma | The Euler-Mascheroni constant.
Explanation
===========
`\gamma = 0.5772157\ldots` (also called Euler's constant) is a mathematical
constant recurring in analysis and number theory. It is defined as the
limiting difference between the harmonic series and the
natural logarithm:
.. math:: \gamma = \lim\limits_{n\to\infty}
\left(\sum\limits_{k=1}^n\frac{1}{k} - \ln n\right)
EulerGamma is a singleton, and can be accessed by ``S.EulerGamma``.
Examples
========
>>> from sympy import S
>>> S.EulerGamma.is_irrational
>>> S.EulerGamma > 0
True
>>> S.EulerGamma > 1
False
References
==========
.. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant | 62598fc6ec188e330fdf8ba2 |
class UpdateRoleConsoleLoginRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.ConsoleLogin = None <NEW_LINE> self.RoleId = None <NEW_LINE> self.RoleName = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.ConsoleLogin = params.get("ConsoleLogin") <NEW_LINE> self.RoleId = params.get("RoleId") <NEW_LINE> self.RoleName = params.get("RoleName") <NEW_LINE> memeber_set = set(params.keys()) <NEW_LINE> for name, value in vars(self).items(): <NEW_LINE> <INDENT> if name in memeber_set: <NEW_LINE> <INDENT> memeber_set.remove(name) <NEW_LINE> <DEDENT> <DEDENT> if len(memeber_set) > 0: <NEW_LINE> <INDENT> warnings.warn("%s fileds are useless." % ",".join(memeber_set)) | UpdateRoleConsoleLogin请求参数结构体
| 62598fc63346ee7daa3377cf |
class RequestJoin(M2MPacket): <NEW_LINE> <INDENT> type = PacketType.request_join | Client requests joining the server. | 62598fc663b5f9789fe85482 |
class ConstExpr(Expr): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> Expr.__init__(self) <NEW_LINE> self._is_const = True <NEW_LINE> self._value = value <NEW_LINE> <DEDENT> def code(self): <NEW_LINE> <INDENT> return str(self._value) | Constant expression
| 62598fc626068e7796d4cc6a |
class Model(interfaces.ParticleFiltering): <NEW_LINE> <INDENT> def __init__(self, P0, Q, R): <NEW_LINE> <INDENT> self.P0 = numpy.copy(P0) <NEW_LINE> self.Q = numpy.copy(Q) <NEW_LINE> self.R = numpy.copy(R) <NEW_LINE> <DEDENT> def create_initial_estimate(self, N): <NEW_LINE> <INDENT> return numpy.random.normal(0.0, self.P0, (N,)).reshape((-1, 1)) <NEW_LINE> <DEDENT> def sample_process_noise(self, particles, u, t): <NEW_LINE> <INDENT> N = len(particles) <NEW_LINE> return numpy.random.normal(0.0, self.Q, (N,)).reshape((-1, 1)) <NEW_LINE> <DEDENT> def update(self, particles, u, t, noise): <NEW_LINE> <INDENT> particles += noise <NEW_LINE> <DEDENT> def measure(self, particles, y, t): <NEW_LINE> <INDENT> logyprob = numpy.empty(len(particles), dtype=float) <NEW_LINE> for k in range(len(particles)): <NEW_LINE> <INDENT> logyprob[k] = kalman.lognormpdf(particles[k].reshape(-1, 1) - y, self.R) <NEW_LINE> <DEDENT> return logyprob <NEW_LINE> <DEDENT> def eval_1st_stage_weights(self, particles, u, y, t): <NEW_LINE> <INDENT> return self.measure(particles, y, t + 1) | x_{k+1} = x_k + v_k, v_k ~ N(0,Q)
y_k = x_k + e_k, e_k ~ N(0,R),
x(0) ~ N(0,P0) | 62598fc671ff763f4b5e7a8d |
class ReduceImageDimensions(ScaledImageMixin, MinibufferAction): <NEW_LINE> <INDENT> name = "Reduce Dimensions by Integer" <NEW_LINE> default_menu = ("Tools", 301) <NEW_LINE> minibuffer_label = "Reduce Dimensions by Integer Factor:" <NEW_LINE> def processMinibuffer(self, minibuffer, mode, scale): <NEW_LINE> <INDENT> self.setLastValue(scale) <NEW_LINE> cube = self.mode.cube <NEW_LINE> view = self.mode.cubeview <NEW_LINE> planes = view.getCurrentPlanes() <NEW_LINE> name = self.getTempName() <NEW_LINE> fh = vfs.make_file(name) <NEW_LINE> newcube = createCubeLike(cube, samples=planes[0].shape[1] / scale, lines=planes[0].shape[0] / scale, bands=len(planes), interleave='bsq') <NEW_LINE> data = newcube.getNumpyArray() <NEW_LINE> dprint("%d,%d,%d: %s" % (newcube.lines, newcube.samples, newcube.bands, data.shape)) <NEW_LINE> band = 0 <NEW_LINE> for plane in planes: <NEW_LINE> <INDENT> data[band,:,:] = bandReduceSampling(plane, scale) <NEW_LINE> band += 1 <NEW_LINE> <DEDENT> fh.setCube(newcube) <NEW_LINE> fh.close() <NEW_LINE> self.frame.open(name) | Create a new image by reducing the size of the current view by an
integer scale factor.
Uses the current CubeView image to create a new image that is scaled in
pixel dimensions. Note that the CubeView image that is used is after all
the filters are applied. | 62598fc65fcc89381b2662d4 |
class SubmissionTestThread(Thread): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> Thread.__init__(self) <NEW_LINE> self._shutdown_flag = False <NEW_LINE> self.start() <NEW_LINE> <DEDENT> def shutdown(self): <NEW_LINE> <INDENT> self._shutdown_flag = True <NEW_LINE> self.join() <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> while not self._shutdown_flag: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> submission = new_submission_queue.get(block=True, timeout=0.1) <NEW_LINE> submission.run_tests() <NEW_LINE> scan_args = (submission.faculty_username, submission.class_name, submission.assignment_name, submission.student.username) <NEW_LINE> info_updater.enqueue_submission_scan(*scan_args) <NEW_LINE> <DEDENT> <DEDENT> except Empty: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logger.log_error('Error while running tests: {0}'.format(e)) | A Thread for running tests on student submissions.
Gets new submissions from the global new_submission_queue. | 62598fc65fdd1c0f98e5e29c |
class _Touch: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.filez = _File() <NEW_LINE> <DEDENT> def pid(self, prefix): <NEW_LINE> <INDENT> timestamp = int(time.time()) <NEW_LINE> filename = self.filez.pid(prefix) <NEW_LINE> os.utime(filename, (timestamp, timestamp)) | A class for updating modifed times for hidden files. | 62598fc6a05bb46b3848ab7a |
class OutputCapture(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.writes = [] <NEW_LINE> <DEDENT> def write(self, what): <NEW_LINE> <INDENT> self.writes.append(what) <NEW_LINE> <DEDENT> def as_result(self): <NEW_LINE> <INDENT> if len(self.writes) == 1: <NEW_LINE> <INDENT> return repr(self.writes[0]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.writes <NEW_LINE> <DEDENT> <DEDENT> def isatty(self): <NEW_LINE> <INDENT> return False | File-like object used to trap output sent through a shell context's
::out() method | 62598fc6ec188e330fdf8ba4 |
class Term: <NEW_LINE> <INDENT> def __init__(self, name, ling, f): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.ling = ling <NEW_LINE> self.f = f <NEW_LINE> <DEDENT> def __call__(self, x): <NEW_LINE> <INDENT> return self.f(x) <NEW_LINE> <DEDENT> def cut(self, cut): <NEW_LINE> <INDENT> return self.f.clip(cut) | Atomic fuzzy set term
[name] is correspondent (type) name of this term.
[ling] is fuzzy linguistic category of this (type) name.
[f] is membership functions | 62598fc660cbc95b0636464d |
class BanABC(ABC): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> @staticmethod <NEW_LINE> def parse(obj: dict) -> 'BanABC': <NEW_LINE> <INDENT> if obj['banned'] == "0": <NEW_LINE> <INDENT> return NoBan(obj['user_id']) <NEW_LINE> <DEDENT> return Ban(obj['user_id'], obj['reason'], obj['case_id'], obj['proof']) <NEW_LINE> <DEDENT> @abstractproperty <NEW_LINE> def user_id(self) -> int: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractproperty <NEW_LINE> def banned(self) -> bool: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractproperty <NEW_LINE> def reason(self) -> Optional[str]: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractproperty <NEW_LINE> def case_id(self) -> Optional[int]: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractproperty <NEW_LINE> def proof(self) -> Optional[str]: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abstractmethod <NEW_LINE> def __eq__(self, other): <NEW_LINE> <INDENT> pass | Base class for bans. Don't use this. Use :class:`Ban` or :class:`NoBan`. | 62598fc663b5f9789fe85484 |
class Storage(object): <NEW_LINE> <INDENT> def open(self, handle=None): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def write(self, resource): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def error(self, message): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def warning(self, resource_full_name, message): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def commit(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def rollback(self): <NEW_LINE> <INDENT> raise NotImplementedError() | The inventory storage interface | 62598fc60fa83653e46f51f6 |
class AgePredict(object): <NEW_LINE> <INDENT> def __init__(self, age_tags, app_dict): <NEW_LINE> <INDENT> self.app_data = {} <NEW_LINE> for pkg_index in app_dict: <NEW_LINE> <INDENT> result = defaultdict(int) <NEW_LINE> keywords = ",".join(app_dict[pkg_index][:2]) <NEW_LINE> for age, words_list in age_tags.items(): <NEW_LINE> <INDENT> for word in words_list: <NEW_LINE> <INDENT> if keywords.find(word) >= 0: <NEW_LINE> <INDENT> result[age] += 1 <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if len(result) > 0: <NEW_LINE> <INDENT> self.app_data[pkg_index] = result <NEW_LINE> <DEDENT> <DEDENT> sys.stderr.write("init AgePredict: " + str(len(self.app_data)) + "\n") <NEW_LINE> for pkg_index in self.app_data: <NEW_LINE> <INDENT> sys.stderr.write("\t%s, %s, %s\n" % (pkg_index, app_dict[pkg_index][0], dict(self.app_data[pkg_index]))) <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def check_user(self, user_pkg_index_list): <NEW_LINE> <INDENT> result = defaultdict(int) <NEW_LINE> for pkg_index in filter(lambda x: x in self.app_data, user_pkg_index_list): <NEW_LINE> <INDENT> for _type in self.app_data[pkg_index]: <NEW_LINE> <INDENT> result[_type] += self.app_data[pkg_index][_type] <NEW_LINE> <DEDENT> <DEDENT> age = config_default_value <NEW_LINE> if len(result) > 0: <NEW_LINE> <INDENT> temp = sorted(result.items(), key=lambda x: x[1], reverse=True) <NEW_LINE> age = temp[0][0] if (len(temp) == 1) or (len(temp) > 1 and temp[0][1] > temp[1][1]) else config_default_value <NEW_LINE> <DEDENT> return {"age": age, "rate": 1.0} | 年龄预测 | 62598fc626068e7796d4cc6c |
class RadialBinnedStatistic(BinnedStatistic1D): <NEW_LINE> <INDENT> def __init__(self, shape, bins=10, range=None, origin=None, mask=None, r_map=None, statistic='mean'): <NEW_LINE> <INDENT> if origin is None: <NEW_LINE> <INDENT> origin = (shape[0] - 1) / 2, (shape[1] - 1) / 2 <NEW_LINE> <DEDENT> if r_map is None: <NEW_LINE> <INDENT> r_map = radial_grid(origin, shape) <NEW_LINE> <DEDENT> self.expected_shape = tuple(shape) <NEW_LINE> if mask is not None: <NEW_LINE> <INDENT> if mask.shape != self.expected_shape: <NEW_LINE> <INDENT> raise ValueError('"mask" has incorrect shape. ' ' Expected: ' + str(self.expected_shape) + ' Received: ' + str(mask.shape)) <NEW_LINE> <DEDENT> mask = mask.reshape(-1) <NEW_LINE> <DEDENT> super(RadialBinnedStatistic, self).__init__(r_map.reshape(-1), statistic, bins=bins, mask=mask, range=range) <NEW_LINE> <DEDENT> def __call__(self, values, statistic=None): <NEW_LINE> <INDENT> if values.shape != self.expected_shape: <NEW_LINE> <INDENT> raise ValueError('"values" has incorrect shape.' ' Expected: ' + str(self.expected_shape) + ' Received: ' + str(values.shape)) <NEW_LINE> <DEDENT> return super(RadialBinnedStatistic, self).__call__(values.reshape(-1), statistic) | Create a 1-dimensional histogram by binning a 2-dimensional
image in radius. | 62598fc6167d2b6e312b7287 |
class Sink(object): <NEW_LINE> <INDENT> def __init__(self, sink_id): <NEW_LINE> <INDENT> self.data = StringIO() <NEW_LINE> self.sink_id = sink_id <NEW_LINE> self.struct = TidyOutputSink() <NEW_LINE> self.struct.sinkData = ctypes.cast( ctypes.pointer(ctypes.c_int(sink_id)), ctypes.c_void_p) <NEW_LINE> write_func = self.data.write <NEW_LINE> def put_byte(sink_id, byte): <NEW_LINE> <INDENT> write_func(byte.decode('utf-8')) <NEW_LINE> <DEDENT> self.struct.putByte = PutByteType(put_byte) <NEW_LINE> self._as_parameter_ = ctypes.byref(self.struct) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.data.getvalue() | Represent a buffer to which Tidy writes errors with a callback function | 62598fc666673b3332c306e6 |
class Padding(object): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def size(length, alignment): <NEW_LINE> <INDENT> overlap = length % alignment <NEW_LINE> if overlap: <NEW_LINE> <INDENT> return alignment - overlap <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def pad(payload, alignment): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def remove(payload): <NEW_LINE> <INDENT> pad_count = payload[-1] <NEW_LINE> return payload[:-pad_count] | Padding base class. | 62598fc6fff4ab517ebcdaf8 |
class MeasureType(IntEnum): <NEW_LINE> <INDENT> UNKNOWN = -999999 <NEW_LINE> WEIGHT = 1 <NEW_LINE> HEIGHT = 4 <NEW_LINE> FAT_FREE_MASS = 5 <NEW_LINE> FAT_RATIO = 6 <NEW_LINE> FAT_MASS_WEIGHT = 8 <NEW_LINE> DIASTOLIC_BLOOD_PRESSURE = 9 <NEW_LINE> SYSTOLIC_BLOOD_PRESSURE = 10 <NEW_LINE> HEART_RATE = 11 <NEW_LINE> TEMPERATURE = 12 <NEW_LINE> SP02 = 54 <NEW_LINE> BODY_TEMPERATURE = 71 <NEW_LINE> SKIN_TEMPERATURE = 73 <NEW_LINE> MUSCLE_MASS = 76 <NEW_LINE> HYDRATION = 77 <NEW_LINE> BONE_MASS = 88 <NEW_LINE> PULSE_WAVE_VELOCITY = 91 | Measure types. | 62598fc6656771135c489980 |
class UpdatePw(webapp2.RequestHandler): <NEW_LINE> <INDENT> def post(self): <NEW_LINE> <INDENT> runningclub_name = self.request.get('runningclub') <NEW_LINE> username = self.request.get('username') <NEW_LINE> encrypteddbpassword = self.request.get('encrypteddbpassword') <NEW_LINE> user = getuserpw(runningclub_name,username) <NEW_LINE> if user: <NEW_LINE> <INDENT> user.encrypteddbpassword = encrypteddbpassword <NEW_LINE> user.put() <NEW_LINE> self.response.out.write(json.dumps({'status':'OK'})) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.response.out.write(json.dumps({'status':'unknownUser'})) | update a userpw in the database, updating encrypteddbpassword attribute | 62598fc6d486a94d0ba2c2e2 |
class DromaeoJslibAttrPrototype(_DromaeoBenchmark): <NEW_LINE> <INDENT> tag = 'jslibattrprototype' <NEW_LINE> query_param = 'jslib-attr-prototype' | Dromaeo JSLib attr prototype JavaScript benchmark | 62598fc6956e5f7376df5806 |
class GatewaySensor(GatewayGenericDevice, SensorEntity): <NEW_LINE> <INDENT> def __init__( self, gateway, device, attr, ): <NEW_LINE> <INDENT> self._state = False <NEW_LINE> self.is_metric = False <NEW_LINE> self.with_attr = bool(device['type'] not in ( 'gateway', 'zigbee')) and bool(attr not in ( 'key_id', 'battery', 'power', 'consumption')) <NEW_LINE> if self.with_attr: <NEW_LINE> <INDENT> self._battery = None <NEW_LINE> self._chip_temperature = None <NEW_LINE> self._lqi = None <NEW_LINE> self._voltage = None <NEW_LINE> <DEDENT> if attr == 'consumption': <NEW_LINE> <INDENT> self._attr_state_class = 'total_increasing' <NEW_LINE> <DEDENT> elif attr in UNITS: <NEW_LINE> <INDENT> self._attr_state_class = 'measurement' <NEW_LINE> <DEDENT> super().__init__(gateway, device, attr) <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self._state <NEW_LINE> <DEDENT> @property <NEW_LINE> def device_class(self): <NEW_LINE> <INDENT> if "consumption" == self._attr: <NEW_LINE> <INDENT> return "energy" <NEW_LINE> <DEDENT> return self._attr <NEW_LINE> <DEDENT> @property <NEW_LINE> def unit_of_measurement(self): <NEW_LINE> <INDENT> return UNITS.get(self._attr) <NEW_LINE> <DEDENT> @property <NEW_LINE> def icon(self): <NEW_LINE> <INDENT> return ICONS.get(self._attr) <NEW_LINE> <DEDENT> @property <NEW_LINE> def extra_state_attributes(self): <NEW_LINE> <INDENT> if self.with_attr: <NEW_LINE> <INDENT> attrs = { ATTR_BATTERY_LEVEL: self._battery, ATTR_LQI: self._lqi, ATTR_VOLTAGE: self._voltage, ATTR_CHIP_TEMPERATURE: self._chip_temperature, } <NEW_LINE> return attrs <NEW_LINE> <DEDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def entity_category(self) -> str: <NEW_LINE> <INDENT> return "config" <NEW_LINE> <DEDENT> def update(self, data: dict = None): <NEW_LINE> <INDENT> for key, value in data.items(): <NEW_LINE> <INDENT> if self.with_attr: <NEW_LINE> <INDENT> if key == BATTERY: <NEW_LINE> <INDENT> self._battery = value <NEW_LINE> <DEDENT> if key == CHIP_TEMPERATURE: <NEW_LINE> <INDENT> if self.is_metric: <NEW_LINE> <INDENT> self._chip_temperature = format( (int(value) - 32) * 5 / 9, '.2f') if isinstance( value, (int, float)) else None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._chip_temperature = value <NEW_LINE> <DEDENT> <DEDENT> if key == LQI: <NEW_LINE> <INDENT> self._lqi = value <NEW_LINE> <DEDENT> if key == VOLTAGE: <NEW_LINE> <INDENT> self._voltage = format( float(value) / 1000, '.3f') if isinstance( value, (int, float)) else None <NEW_LINE> <DEDENT> <DEDENT> if self._attr == POWER and LOAD_POWER in data: <NEW_LINE> <INDENT> self._state = data[LOAD_POWER] <NEW_LINE> <DEDENT> if self._attr == key: <NEW_LINE> <INDENT> self._state = data[key] <NEW_LINE> <DEDENT> <DEDENT> self.async_write_ha_state() | Xiaomi/Aqara Sensors | 62598fc65fdd1c0f98e5e29e |
class TimingHook(TrainingHook): <NEW_LINE> <INDENT> def __init__(self, trainer): <NEW_LINE> <INDENT> super(TimingHook, self).__init__(trainer) <NEW_LINE> self._epoch_times = [] <NEW_LINE> <DEDENT> @property <NEW_LINE> def epoch_times(self): <NEW_LINE> <INDENT> return self._epoch_times <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def time_format(elapsed_seconds): <NEW_LINE> <INDENT> return str(timedelta(seconds=elapsed_seconds)) <NEW_LINE> <DEDENT> def mean_error(self): <NEW_LINE> <INDENT> return sum(self._epoch_times)/len(self._epoch_times) <NEW_LINE> <DEDENT> def pre_epoch(self): <NEW_LINE> <INDENT> self.start_time = time.time() <NEW_LINE> <DEDENT> def post_epoch(self): <NEW_LINE> <INDENT> self.end_time = time.time() <NEW_LINE> elapsed_seconds = self.end_time - self.start_time <NEW_LINE> self._epoch_times.append(elapsed_seconds) <NEW_LINE> eta = self.mean_error() * self._trainer._remaining_epochs <NEW_LINE> print("Epoch {} training time: {}".format(self._trainer.epoch, self.time_format(elapsed_seconds))) <NEW_LINE> print("ETA: {}".format(self.time_format(eta))) | Training Hook for log the training time between epochs
| 62598fc6ec188e330fdf8ba6 |
class Breakcom(Platform): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.platformName = "Breakcom" <NEW_LINE> self.tags = ["video"] <NEW_LINE> self.isValidMode = {} <NEW_LINE> self.isValidMode["phonefy"] = False <NEW_LINE> self.isValidMode["usufy"] = True <NEW_LINE> self.isValidMode["searchfy"] = False <NEW_LINE> self.url = {} <NEW_LINE> self.url["usufy"] = "http://www.break.com/user/" + "<usufy>" <NEW_LINE> self.needsCredentials = {} <NEW_LINE> self.needsCredentials["usufy"] = False <NEW_LINE> self.validQuery = {} <NEW_LINE> self.validQuery["usufy"] = ".+" <NEW_LINE> self.notFoundText = {} <NEW_LINE> self.notFoundText["usufy"] = ["Break.com</title>"] <NEW_LINE> self.fieldsRegExp = {} <NEW_LINE> self.fieldsRegExp["usufy"] = {} <NEW_LINE> self.foundFields = {} | A <Platform> object for Breakcom. | 62598fc676e4537e8c3ef8b6 |
class MonitoredResourceDescriptor(_messages.Message): <NEW_LINE> <INDENT> description = _messages.StringField(1) <NEW_LINE> displayName = _messages.StringField(2) <NEW_LINE> labels = _messages.MessageField('LabelDescriptor', 3, repeated=True) <NEW_LINE> name = _messages.StringField(4) <NEW_LINE> type = _messages.StringField(5) | An object that describes the schema of a MonitoredResource object using
a type name and a set of labels. For example, the monitored resource
descriptor for Google Compute Engine VM instances has a type of
`"gce_instance"` and specifies the use of the labels `"instance_id"` and
`"zone"` to identify particular VM instances. Different APIs can support
different monitored resource types. APIs generally provide a `list` method
that returns the monitored resource descriptors used by the API.
Fields:
description: Optional. A detailed description of the monitored resource
type that might be used in documentation.
displayName: Optional. A concise name for the monitored resource type
that might be displayed in user interfaces. It should be a Title Cased
Noun Phrase, without any article or other determiners. For example,
`"Google Cloud SQL Database"`.
labels: Required. A set of labels used to describe instances of this
monitored resource type. For example, an individual Google Cloud SQL
database is identified by values for the labels `"database_id"` and
`"zone"`.
name: Optional. The resource name of the monitored resource descriptor:
`"projects/{project_id}/monitoredResourceDescriptors/{type}"` where
{type} is the value of the `type` field in this object and
{project_id} is a project ID that provides API-specific context for
accessing the type. APIs that do not use project information can use
the resource name format `"monitoredResourceDescriptors/{type}"`.
type: Required. The monitored resource type. For example, the type
`"cloudsql_database"` represents databases in Google Cloud SQL. The
maximum length of this value is 256 characters. | 62598fc6adb09d7d5dc0a88d |
class Logger(object): <NEW_LINE> <INDENT> use_external_configuration = False <NEW_LINE> @staticmethod <NEW_LINE> def configure_by_file(filename): <NEW_LINE> <INDENT> logging.config.fileConfig(filename) <NEW_LINE> Logger.use_external_configuration = True <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def configure_default(logging_format, level): <NEW_LINE> <INDENT> logging.basicConfig(format=logging_format, level=level) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def get_logger(name): <NEW_LINE> <INDENT> if name is None: <NEW_LINE> <INDENT> return NoLogger() <NEW_LINE> <DEDENT> logger = logging.getLogger(name) <NEW_LINE> if Logger.use_external_configuration: <NEW_LINE> <INDENT> logger.propagate = False <NEW_LINE> <DEDENT> return logger | Wrapper for logging calls. | 62598fc60fa83653e46f51f8 |
class TemplateRenderer(Application): <NEW_LINE> <INDENT> VERSION = __version__ <NEW_LINE> overwrite = Flag( ['f', 'force'], help="Overwrite any existing destination file" ) <NEW_LINE> def main(self, template_file: ExistingFile, *var_files: ExistingFile): <NEW_LINE> <INDENT> warn_shebangs(template_file) <NEW_LINE> data = {} <NEW_LINE> var_mentions = defaultdict(list) <NEW_LINE> for vfile in var_files: <NEW_LINE> <INDENT> loader = jloads if vfile.suffix.lower() == '.json' else yloads <NEW_LINE> new_data = loader(vfile.read()) <NEW_LINE> for v in new_data: <NEW_LINE> <INDENT> var_mentions[v].append(vfile) <NEW_LINE> <DEDENT> data.update(new_data) <NEW_LINE> <DEDENT> warn_overrides(var_mentions) <NEW_LINE> rstr = Template(filename=str(template_file), data=data)() <NEW_LINE> dest = template_file.with_suffix('') <NEW_LINE> if not self.overwrite: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> NonexistentPath(dest) <NEW_LINE> <DEDENT> except ValueError as e: <NEW_LINE> <INDENT> err(f"{type(e)}: {e}") <NEW_LINE> err("Use -f/--force to overwrite") <NEW_LINE> sys.exit(1) <NEW_LINE> <DEDENT> <DEDENT> dest.write(rstr) | Use json or yaml var_files to render template_file to an adjacent
file with the same name but the extension stripped | 62598fc6fff4ab517ebcdafa |
class Perceptron(object): <NEW_LINE> <INDENT> def __init__(self, eta=0.01, n_iter=10): <NEW_LINE> <INDENT> self.eta = eta <NEW_LINE> self.n_iter = n_iter <NEW_LINE> <DEDENT> def fit(self, X, y): <NEW_LINE> <INDENT> self.w_ = np.zeros(1 + X.shape[1]) <NEW_LINE> self.errors_ = [] <NEW_LINE> for _ in range(self.n_iter): <NEW_LINE> <INDENT> errors = 0 <NEW_LINE> for xi, target in zip(X, y): <NEW_LINE> <INDENT> update = self.eta * (target - self.predict(xi)) <NEW_LINE> self.w_[1:] += update * xi <NEW_LINE> self.w_[0] += update <NEW_LINE> errors += int(update != 0.0) <NEW_LINE> <DEDENT> self.errors_.append(errors) <NEW_LINE> <DEDENT> return self <NEW_LINE> <DEDENT> def net_input(self, X): <NEW_LINE> <INDENT> return np.dot(X, self.w_[1:]) + self.w_[0] <NEW_LINE> <DEDENT> def predict(self, X): <NEW_LINE> <INDENT> return np.where(self.net_input(X) >= 0.0, 1, -1) | Perceptron classifier.
Parameters
-------------
eta : float
Learing rate (between 0.0 and 1.0)
n_iter : int
Passes over the training dataset.
Attributes
-------------
w_ : 1d-array
Weights after fitting.
errors_ : list
Number of misclassifications in every epoch. | 62598fc6ad47b63b2c5a7b6b |
class DescribeDDoSDefendStatusResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.DefendStatus = None <NEW_LINE> self.UndefendExpire = None <NEW_LINE> self.ShowFlag = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.DefendStatus = params.get("DefendStatus") <NEW_LINE> self.UndefendExpire = params.get("UndefendExpire") <NEW_LINE> self.ShowFlag = params.get("ShowFlag") <NEW_LINE> self.RequestId = params.get("RequestId") | DescribeDDoSDefendStatus返回参数结构体
| 62598fc67c178a314d78d7b2 |
class BaseConfig(object): <NEW_LINE> <INDENT> TESTING = False <NEW_LINE> DEBUG = False <NEW_LINE> SECRET_KEY = "awesome nakatudde" | Common configurations | 62598fc6bf627c535bcb17bb |
class FixedMonitor(MonitorInterface): <NEW_LINE> <INDENT> def __call__(self): <NEW_LINE> <INDENT> constraint = self.newConstraint() <NEW_LINE> constraint['count'] = _FixedValue <NEW_LINE> return [constraint] | _FixedMonitor_
Every time this plugin is polled, return the same value | 62598fc6ff9c53063f51a960 |
class BaseUnit(Unit): <NEW_LINE> <INDENT> named = {} <NEW_LINE> index_order = [None] * len(Unit._measureable) <NEW_LINE> def __init__(self, name, abbreviation, quantifies, display_order): <NEW_LINE> <INDENT> unit_index = self._measureable[quantifies] <NEW_LINE> super().__init__(name, abbreviation, quantifies, display_order) <NEW_LINE> self.unit_index = unit_index <NEW_LINE> self.named[name] = self <NEW_LINE> self.index_order[Unit._measureable[self.quantifies]] = self <NEW_LINE> self._dimension = Dimension(**{self.name:1}) <NEW_LINE> <DEDENT> def reprvals(self): <NEW_LINE> <INDENT> return ', '.join([repr(x) for x in [self.name, self.abbreviation, self.quantifies, self.display_order]]) <NEW_LINE> <DEDENT> @property <NEW_LINE> def dimension(self): <NEW_LINE> <INDENT> return self._dimension <NEW_LINE> <DEDENT> def gloss(self): <NEW_LINE> <INDENT> return [self.name, self.abbreviation, self.quantifies, 'SI base unit'] | Defines an SI base unit.
:param name: Full name of the unit.
:param abbreviation: The official unit abbreviation. Used for display
and parsing.
:param quantifies: A string (no white space allowed) that describes the
quantity measured by the unit.
:param display_order: A integer that controls the print-out order
for this unit for the __str__ method.. Lower display_order units
print first. | 62598fc6a8370b77170f06ee |
class LearningProcessStaticVisualizer(AbstractStaticVisualizer): <NEW_LINE> <INDENT> METRICS = { "mean": np.mean, "median": np.median, } <NEW_LINE> def __init__(self, reward_set, axis=None, conf=68, bounds=False, metric="median", minimum=15e3): <NEW_LINE> <INDENT> self._rs = reward_set <NEW_LINE> super(LearningProcessStaticVisualizer, self).__init__(axis, conf=conf, bounds=bounds, metric=metric, minimum=minimum) <NEW_LINE> <DEDENT> def _key(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def _plot(self, conf, bounds, metric, minimum): <NEW_LINE> <INDENT> assert_in(metric, self.METRICS) <NEW_LINE> rewards = self._rs.get_training_rewards() <NEW_LINE> x_vector = np.arange(rewards.shape[1]) + 1 <NEW_LINE> if bounds: <NEW_LINE> <INDENT> self._axis.plot( x_vector, rewards.min(axis=0), color="tomato", linestyle="--", label="Min" ) <NEW_LINE> self._axis.plot( x_vector, rewards.max(axis=0), color="tomato", linestyle="--", label="Max" ) <NEW_LINE> <DEDENT> self._axis.plot( x_vector, self.METRICS[metric](rewards, axis=0), color="k", linestyle="-", linewidth=1.5, label="Median" ) <NEW_LINE> self._axis.fill_between( x_vector, np.percentile(rewards, 100 - conf, axis=0), np.percentile(rewards, conf, axis=0), facecolor="dodgerblue", alpha=0.5, lw=0, label=r"1$\sigma$ conf." ) <NEW_LINE> self._axis.set_ylabel("Cumulative reward per episode [-]") <NEW_LINE> self._axis.set_xlabel("Training episode number [-]") <NEW_LINE> self._axis.set_xlim(x_vector[0], x_vector[-1]) <NEW_LINE> self._axis.set_ylim(-minimum, 0) <NEW_LINE> plt.legend(loc="lower right") <NEW_LINE> self._name = "{:s}-{:d}-{:d}".format( self._rs.__class__.__name__, self._rs.get_id(), len(self._rs) ) | Visualizer class to plot the learning process of a set of RL controllers. Requires a RewardSet object to
instantiate. | 62598fc63346ee7daa3377d2 |
class ZhThTranslator: <NEW_LINE> <INDENT> def __init__(self, pretrained: str = "Lalita/marianmt-zh_cn-th") -> None: <NEW_LINE> <INDENT> self.tokenizer_zhth = AutoTokenizer.from_pretrained(pretrained) <NEW_LINE> self.model_zhth = AutoModelForSeq2SeqLM.from_pretrained(pretrained) <NEW_LINE> <DEDENT> def translate(self, text: str) -> str: <NEW_LINE> <INDENT> self.translated = self.model_zhth.generate( **self.tokenizer_zhth(text, return_tensors="pt", padding=True) ) <NEW_LINE> return [ self.tokenizer_zhth.decode( t, skip_special_tokens=True ) for t in self.translated ][0] | Chinese-Thai Machine Translation
from Lalita @ AI builder
- GitHub: https://github.com/LalitaDeelert/lalita-mt-zhth
- Facebook post https://web.facebook.com/aibuildersx/posts/166736255494822 | 62598fc60fa83653e46f51fa |
class normalbandit(Bandit): <NEW_LINE> <INDENT> def __init__(self, arms=1, shock=False, murange=(-1, 1), varmax=(1)): <NEW_LINE> <INDENT> Bandit.__init__(self, arms, shock) <NEW_LINE> self._armsmu = np.random.uniform(min(murange), max(murange), self.k) <NEW_LINE> self._armsvar = np.random.uniform(0, varmax, self.k) <NEW_LINE> self._bestarm = np.argmax(self._armsmu) <NEW_LINE> <DEDENT> def pull(self, i): <NEW_LINE> <INDENT> return np.random.normal(self._armsmu[i], self._armsvar[i]) | Bandit class with rewards drawn from the normal distribution
parameters:
k: number of bandits to initialize. Takes integers > 1
mu range: range in which means are drawn: min to max
var range: range in which variance is drawn: 0 to max
methods:
pull:generates reward from bandit i in k
| 62598fc623849d37ff8513c6 |
@python_2_unicode_compatible <NEW_LINE> class Category(MP_Node): <NEW_LINE> <INDENT> name = models.CharField('分类名', max_length=255, db_index=True) <NEW_LINE> description = models.TextField('分类描述', blank=True) <NEW_LINE> image = models.ImageField('图片', upload_to='images/categories', blank=True, null=True, max_length=255) <NEW_LINE> slug = models.SlugField('简单描述', max_length=255, db_index=True) <NEW_LINE> _slug_separator = '/' <NEW_LINE> _full_name_separator = ' > ' <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.full_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def full_name(self): <NEW_LINE> <INDENT> names = [category.name for category in self.get_ancestors_and_self()] <NEW_LINE> return self._full_name_separator.join(names) <NEW_LINE> <DEDENT> @property <NEW_LINE> def full_slug(self): <NEW_LINE> <INDENT> slugs = [category.slug for category in self.get_ancestors_and_self()] <NEW_LINE> return self._slug_separator.join(slugs) <NEW_LINE> <DEDENT> def generate_slug(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def ensure_slug_uniqueness(self): <NEW_LINE> <INDENT> unique_slug = self.slug <NEW_LINE> siblings = self.get_siblings().exclude(pk=self.pk) <NEW_LINE> next_num = 2 <NEW_LINE> while siblings.filter(slug=unique_slug).exists(): <NEW_LINE> <INDENT> unique_slug = '{slug}_{end}'.format(slug=self.slug, end=next_num) <NEW_LINE> next_num += 1 <NEW_LINE> <DEDENT> if unique_slug != self.slug: <NEW_LINE> <INDENT> self.slug = unique_slug <NEW_LINE> self.save() <NEW_LINE> <DEDENT> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if self.slug: <NEW_LINE> <INDENT> super(Category, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.slug = self.generate_slug() <NEW_LINE> super(Category, self).save(*args, **kwargs) <NEW_LINE> self.ensure_slug_uniqueness() <NEW_LINE> <DEDENT> <DEDENT> def get_ancestors_and_self(self): <NEW_LINE> <INDENT> return list(self.get_ancestors()) + [self] <NEW_LINE> <DEDENT> def get_descendants_and_self(self): <NEW_LINE> <INDENT> return list(self.get_descendants()) + [self] <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> app_label = 'category' <NEW_LINE> ordering = ['path'] <NEW_LINE> verbose_name = '产品目录' <NEW_LINE> verbose_name_plural = verbose_name <NEW_LINE> <DEDENT> @property <NEW_LINE> def has_children(self): <NEW_LINE> <INDENT> return self.get_num_children() > 0 <NEW_LINE> <DEDENT> def get_num_children(self): <NEW_LINE> <INDENT> return self.get_children().count() | A product category. Merely used for navigational purposes; has no
effects on business logic.
Uses django-treebeard. | 62598fc6f9cc0f698b1c545c |
class UserLabel(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=128) <NEW_LINE> user = models.ForeignKey(User, default=None, null=True) | Individual user labels (a filled out ballot that "votes" for a label associated with an image) | 62598fc7cc40096d6161a362 |
class ComponentMaker: <NEW_LINE> <INDENT> colors = ['#FF0000','#00FF00','#0000FF', '#009999','#990099','#999900', '#996666','#669966','#666699', '#0066CC','#6600CC','#66CC00', '#00CC66','#CC0066','#CC6600'] <NEW_LINE> def __init__(self, graph, animator, forbidden_colors=None): <NEW_LINE> <INDENT> self.G = graph <NEW_LINE> self.A = animator <NEW_LINE> self.lastColor = 0 <NEW_LINE> self.firstCall = True <NEW_LINE> self.colors = copy.copy(self.colors) <NEW_LINE> if forbidden_colors: <NEW_LINE> <INDENT> for color in forbidden_colors: <NEW_LINE> <INDENT> if color in self.colors: <NEW_LINE> <INDENT> self.colors.remove(color) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def NewComponent(self): <NEW_LINE> <INDENT> self.firstCall = False <NEW_LINE> comp = AnimatedSubGraph(self.G, self.A, self.colors[self.lastColor]) <NEW_LINE> self.lastColor = self.lastColor + 1 <NEW_LINE> if self.lastColor == len(self.colors): <NEW_LINE> <INDENT> self.lastColor = 0 <NEW_LINE> <DEDENT> return comp <NEW_LINE> <DEDENT> def LastComponentColor(self): <NEW_LINE> <INDENT> if self.firstCall: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> if self.lastColor > 0: <NEW_LINE> <INDENT> return self.colors[self.lastColor -1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.colors[-1] | Subsequent calls of method NewComponent() will return differently
colored subgraphs of G | 62598fc74527f215b58ea1e4 |
class Bishop: <NEW_LINE> <INDENT> def __init__(self, color): <NEW_LINE> <INDENT> self.color = color <NEW_LINE> <DEDENT> def get_color(self): <NEW_LINE> <INDENT> return self.color <NEW_LINE> <DEDENT> def char(self): <NEW_LINE> <INDENT> return 'B' <NEW_LINE> <DEDENT> def can_move(self, board, row, col, row1, col1): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def can_attack(self, board, row, col, row1, col1): <NEW_LINE> <INDENT> return self.can_move(board, row, col, row1, col1) | Класс слона | 62598fc75fcc89381b2662d7 |
class rice_gen(rv_continuous): <NEW_LINE> <INDENT> def _argcheck(self, b): <NEW_LINE> <INDENT> return b >= 0 <NEW_LINE> <DEDENT> def _rvs(self, b): <NEW_LINE> <INDENT> t = b/np.sqrt(2) + self._random_state.standard_normal(size=(2,) + self._size) <NEW_LINE> return np.sqrt((t*t).sum(axis=0)) <NEW_LINE> <DEDENT> def _cdf(self, x, b): <NEW_LINE> <INDENT> return sc.chndtr(np.square(x), 2, np.square(b)) <NEW_LINE> <DEDENT> def _ppf(self, q, b): <NEW_LINE> <INDENT> return np.sqrt(sc.chndtrix(q, 2, np.square(b))) <NEW_LINE> <DEDENT> def _pdf(self, x, b): <NEW_LINE> <INDENT> return x * np.exp(-(x-b)*(x-b)/2.0) * sc.i0e(x*b) <NEW_LINE> <DEDENT> def _munp(self, n, b): <NEW_LINE> <INDENT> nd2 = n/2.0 <NEW_LINE> n1 = 1 + nd2 <NEW_LINE> b2 = b*b/2.0 <NEW_LINE> return (2.0**(nd2) * np.exp(-b2) * sc.gamma(n1) * sc.hyp1f1(n1, 1, b2)) | A Rice continuous random variable.
%(before_notes)s
Notes
-----
The probability density function for `rice` is::
rice.pdf(x, b) = x * exp(-(x**2+b**2)/2) * I[0](x*b)
for ``x > 0``, ``b > 0``.
`rice` takes ``b`` as a shape parameter.
%(after_notes)s
The Rice distribution describes the length, ``r``, of a 2-D vector
with components ``(U+u, V+v)``, where ``U, V`` are constant, ``u, v``
are independent Gaussian random variables with standard deviation
``s``. Let ``R = (U**2 + V**2)**0.5``. Then the pdf of ``r`` is
``rice.pdf(x, R/s, scale=s)``.
%(example)s | 62598fc7656771135c489984 |
class FileIdentificationBlock: <NEW_LINE> <INDENT> __slots__ = ( "address", "file_identification", "version_str", "program_identification", "reserved0", "mdf_version", "reserved1", "unfinalized_standard_flags", "unfinalized_custom_flags", ) <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.address = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> stream = kwargs["stream"] <NEW_LINE> stream.seek(self.address) <NEW_LINE> ( self.file_identification, self.version_str, self.program_identification, self.reserved0, self.mdf_version, self.reserved1, self.unfinalized_standard_flags, self.unfinalized_custom_flags, ) = unpack( v4c.FMT_IDENTIFICATION_BLOCK, stream.read(v4c.IDENTIFICATION_BLOCK_SIZE) ) <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> version = kwargs.get("version", "4.00") <NEW_LINE> self.file_identification = "MDF ".encode("utf-8") <NEW_LINE> self.version_str = "{} ".format(version).encode("utf-8") <NEW_LINE> self.program_identification = "amdf{}".format( __version__.replace(".", "") ).encode("utf-8") <NEW_LINE> self.reserved0 = b"\0" * 4 <NEW_LINE> self.mdf_version = int(version.replace(".", "")) <NEW_LINE> self.reserved1 = b"\0" * 30 <NEW_LINE> self.unfinalized_standard_flags = 0 <NEW_LINE> self.unfinalized_custom_flags = 0 <NEW_LINE> <DEDENT> <DEDENT> def __getitem__(self, item): <NEW_LINE> <INDENT> return self.__getattribute__(item) <NEW_LINE> <DEDENT> def __setitem__(self, item, value): <NEW_LINE> <INDENT> self.__setattr__(item, value) <NEW_LINE> <DEDENT> def __bytes__(self): <NEW_LINE> <INDENT> result = pack( v4c.FMT_IDENTIFICATION_BLOCK, *[self[key] for key in v4c.KEYS_IDENTIFICATION_BLOCK], ) <NEW_LINE> return result | *FileIdentificationBlock* has the following attributes, that are also available as
dict like key-value pairs
IDBLOCK fields
* ``file_identification`` - bytes : file identifier
* ``version_str`` - bytes : format identifier
* ``program_identification`` - bytes : creator program identifier
* ``reserved0`` - bytes : reserved bytes
* ``mdf_version`` - int : version number of MDF format
* ``reserved1`` - bytes : reserved bytes
* ``unfinalized_standard_flags`` - int : standard flags for unfinalized MDF
* ``unfinalized_custom_flags`` - int : custom flags for unfinalized MDF
Other attributes
* ``address`` - int : should always be 0 | 62598fc7ad47b63b2c5a7b6d |
class MsgReply(Message): <NEW_LINE> <INDENT> def __init__(self, request_message=None, **kwargs): <NEW_LINE> <INDENT> if request_message and hasattr(request_message, "routing_key"): <NEW_LINE> <INDENT> if request_message.routing_key.endswith(".request"): <NEW_LINE> <INDENT> self.routing_key = request_message.routing_key.replace(".request", ".reply") <NEW_LINE> <DEDENT> if not hasattr(self, "_msg_data_template"): <NEW_LINE> <INDENT> self._msg_data_template = { "ok": True, } <NEW_LINE> <DEDENT> elif 'ok' not in self._msg_data_template: <NEW_LINE> <INDENT> self._msg_data_template.update({ "ok": True, }) <NEW_LINE> <DEDENT> super(MsgReply, self).__init__(**kwargs) <NEW_LINE> self._properties["correlation_id"] = request_message.correlation_id <NEW_LINE> self.correlation_id = request_message.correlation_id <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> super(MsgReply, self).__init__(**kwargs) <NEW_LINE> logger.info( '[messages] lazy message reply generated. Do not expect correlation between request and reply amqp' 'properties %s' % repr(self)[:70] ) <NEW_LINE> <DEDENT> <DEDENT> def correlate_to(self, request_message): <NEW_LINE> <INDENT> self._properties["correlation_id"] = request_message.correlation_id <NEW_LINE> self.correlation_id = request_message.correlation_id | Auxiliary class which creates replies messages with fields based on the request.
Routing key, corr_id are generated based on the request message
When not passing request_message as argument | 62598fc7a219f33f346c6b1c |
class Sento(namedtuple('Sento', ['id', 'name', 'address', 'access', 'holidays', 'has_laundry', 'office_hours'])): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return '\t'.join(self[:5]) + '\t' + str(self.has_laundry) + '\t' + self[-1] | TODO: docstring | 62598fc7a8370b77170f06f0 |
class UnitTest(unittest.TestCase, metaclass=abc.ABCMeta): <NEW_LINE> <INDENT> unittest = True | A base IntegrationTesting class | 62598fc750812a4eaa620d6f |
class Last(Semigroup): <NEW_LINE> <INDENT> def __str__(self) -> str: <NEW_LINE> <INDENT> return 'Last[value={}]'.format(self.value) <NEW_LINE> <DEDENT> def concat(self, semigroup): <NEW_LINE> <INDENT> return Last(semigroup.value) | Last is a Monoid that will always return the lastest, value when 2 Last instances are combined. | 62598fc7d8ef3951e32c7fe6 |
class FITSReader(Reader): <NEW_LINE> <INDENT> def __init__(self, filename, verbose = False): <NEW_LINE> <INDENT> super(FITSReader, self).__init__(filename, verbose = verbose) <NEW_LINE> from astropy.io import fits <NEW_LINE> self.hdul = fits.open(filename, memmap = True) <NEW_LINE> hdr = self.hdul[0].header <NEW_LINE> assert ((hdr['BITPIX'] == 16) and (hdr['bscale'] == 1) and (hdr['bzero'] == 32768)), "Only 16 bit pseudo-unsigned FITS format is currently supported!" <NEW_LINE> self.image_height = hdr['naxis2'] <NEW_LINE> self.image_width = hdr['naxis1'] <NEW_LINE> if (hdr['naxis'] == 3): <NEW_LINE> <INDENT> self.number_frames = hdr['naxis3'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.number_frames = 1 <NEW_LINE> <DEDENT> self.hdu0 = self.hdul[0] <NEW_LINE> self.hdu0._do_not_scale_image_data = True <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def loadAFrame(self, frame_number): <NEW_LINE> <INDENT> super(FITSReader, self).loadAFrame(frame_number) <NEW_LINE> frame = self.hdu0.data[frame_number,:,:].astype(numpy.uint16) <NEW_LINE> frame -= 32768 <NEW_LINE> return frame | FITS file reader class.
FIXME: This depends on internals of astropy.io.fits that I'm sure
we are not supposed to be messing with. The problem is that
astropy.io.fits does not support memmap'd images when the
image is scaled (which is pretty much always the case?). To
get around this we set _ImageBaseHDU._do_not_scale_image_data
to True, then do the image scaling ourselves.
We want memmap = True as generally it won't make sense to
load the entire movie into memory.
Another consequence of this is that we only support
'pseudo unsigned' 16 bit FITS format files. | 62598fc73d592f4c4edbb1c8 |
class time_mock(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._now = time.time() <NEW_LINE> <DEDENT> def do_tick(self): <NEW_LINE> <INDENT> self._now += 1.0 <NEW_LINE> <DEDENT> def time(self): <NEW_LINE> <INDENT> return self._now | Mock class for the time module.
Use this to quickly skip forward in time. It starts with the time at which it is instantiated and then increases
with one second every time do_tick is called. | 62598fc78a349b6b43686555 |
class CaliperLogTest(unittest.TestCase): <NEW_LINE> <INDENT> def test_log_verbose(self): <NEW_LINE> <INDENT> target_cmd = [ './ci_test_basic' ] <NEW_LINE> env = { 'CALI_LOG_VERBOSITY' : '3', 'CALI_LOG_LOGFILE' : 'stdout' } <NEW_LINE> log_targets = [ 'CALI_LOG_VERBOSITY=3', '== CALIPER: default: snapshot scopes: process thread', '== CALIPER: Releasing channel default', '== CALIPER: Releasing Caliper thread data', 'Blackboard', 'Metadata tree', 'Metadata memory pool' ] <NEW_LINE> report_out,_ = cat.run_test(target_cmd, env) <NEW_LINE> lines = report_out.decode().splitlines() <NEW_LINE> for target in log_targets: <NEW_LINE> <INDENT> for line in lines: <NEW_LINE> <INDENT> if target in line: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.fail('%s not found in log' % target) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_scope_parse_error_msgs(self): <NEW_LINE> <INDENT> target_cmd = [ './ci_test_basic' ] <NEW_LINE> env = { 'CALI_LOG_VERBOSITY' : '0', 'CALI_LOG_LOGFILE' : 'stdout', 'CALI_CHANNEL_SNAPSHOT_SCOPES' : 'foo', 'CALI_CALIPER_ATTRIBUTE_DEFAULT_SCOPE' : 'bar' } <NEW_LINE> log_targets = [ 'Invalid value "foo" for CALI_CHANNEL_SNAPSHOT_SCOPES', 'Invalid value "bar" for CALI_CALIPER_ATTRIBUTE_DEFAULT_SCOPE' ] <NEW_LINE> report_out,_ = cat.run_test(target_cmd, env) <NEW_LINE> lines = report_out.decode().splitlines() <NEW_LINE> for target in log_targets: <NEW_LINE> <INDENT> for line in lines: <NEW_LINE> <INDENT> if target in line: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.fail('%s not found in log' % target) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_log_silent(self): <NEW_LINE> <INDENT> target_cmd = [ './ci_test_basic' ] <NEW_LINE> env = { 'CALI_LOG_VERBOSITY' : '0', 'CALI_LOG_LOGFILE' : 'stdout' } <NEW_LINE> report_out,_ = cat.run_test(target_cmd, env) <NEW_LINE> lines = report_out.decode().splitlines() <NEW_LINE> self.assertTrue(len(lines) == 0) | Caliper Log test cases | 62598fc70fa83653e46f51fc |
class Date(Column): <NEW_LINE> <INDENT> def __init__(self, name, frmt='%Y-%m-%d'): <NEW_LINE> <INDENT> super().__init__(name) <NEW_LINE> self.frmt = frmt <NEW_LINE> <DEDENT> def parse(self, value): <NEW_LINE> <INDENT> return datetime.datetime.strptime(value.strip(), self.frmt).date() | Specialized Column descriptor for date fields.
Parse strings into datetime.date objects accordingly to the
provided format specification. The format specification is the
same understood by datetime.datetime.strptime().
Args:
name: Column name or index.
frmt: Date format specification. | 62598fc723849d37ff8513c8 |
class TrackingLatticeGridTestHarness(TrackingTestHarness): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(TrackingLatticeGridTestHarness, self).__init__() <NEW_LINE> self.input_set = LatticeGridInput() <NEW_LINE> <DEDENT> def _setup(self): <NEW_LINE> <INDENT> super(TrackingLatticeGridTestHarness, self)._create_geometry() <NEW_LINE> self.tracks['Diagonal Track'] = openmoc.Track() <NEW_LINE> self.tracks['Nudged Diagonal Track'] = openmoc.Track() <NEW_LINE> self.tracks['Horizontal Track'] = openmoc.Track() <NEW_LINE> self.tracks['Vertical Track'] = openmoc.Track() <NEW_LINE> self.tracks['Reverse Diagonal Track'] = openmoc.Track() <NEW_LINE> self.tracks['Diagonal Track'].setValues(-3, -3, 0, 3, 3, 0, math.atan(1)) <NEW_LINE> nudge = 1e-5 <NEW_LINE> self.tracks['Nudged Diagonal Track'].setValues(-3+nudge, -3, 0, 3, 3-nudge, 0, math.atan(1)) <NEW_LINE> self.tracks['Horizontal Track'].setValues(-3, 0, 0, 3, 0, 0, 0) <NEW_LINE> self.tracks['Vertical Track'].setValues(0, -3, 0, 0, 3, 0, math.pi/2) <NEW_LINE> self.tracks['Reverse Diagonal Track'].setValues(3, 3, 0, -3, -3, 0, math.pi + math.atan(1)) | Tests tracking over a lattice geometry. | 62598fc755399d3f0562682f |
class ParseJobList(ApiList): <NEW_LINE> <INDENT> API_NAME = "parse_jobs" <NEW_LINE> API_NAME_SRC = "parse_job_list" <NEW_LINE> API_SIMPLE = {} <NEW_LINE> API_COMPLEX = {} <NEW_LINE> API_CONSTANTS = {} <NEW_LINE> API_STR_ADD = [] <NEW_LINE> API_ITEM_ATTR = "parse_job" <NEW_LINE> API_ITEM_CLS = "ParseJob" | Automagically generated API array object. | 62598fc74527f215b58ea1e6 |
class word(object): <NEW_LINE> <INDENT> instances=weakref.WeakValueDictionary() <NEW_LINE> iCount=0 <NEW_LINE> def __init__(self,txtGrp=None,text=None,group=None,coordinate=None,dir=None): <NEW_LINE> <INDENT> if txtGrp is not None: <NEW_LINE> <INDENT> text=txtGrp[0] <NEW_LINE> group=txtGrp[1:] <NEW_LINE> <DEDENT> self.inRange = None <NEW_LINE> self.text=text <NEW_LINE> self.group = group <NEW_LINE> self.groupIndex = group[3] <NEW_LINE> self.dir = dir <NEW_LINE> self.coordinate = coordinate <NEW_LINE> self.len = len(text) <NEW_LINE> x,y = coordinate <NEW_LINE> tx,ty = dir <NEW_LINE> tx,ty = tx*(self.len-1),ty *(self.len-1) <NEW_LINE> self.absStart = y*ySize+x <NEW_LINE> self.absEnd=ty*ySize+tx <NEW_LINE> self.inRange = ((x+tx)<xSize) and ((y+ty)<ySize) <NEW_LINE> self.updateGrid() <NEW_LINE> word.track(self) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def fromRandom(cls,txtGrp=None,text=None,group=None,coordinate=None,dir=None): <NEW_LINE> <INDENT> if txtGrp is not None: <NEW_LINE> <INDENT> text=txtGrp[0] <NEW_LINE> group=txtGrp[1:] <NEW_LINE> <DEDENT> if dir is None: <NEW_LINE> <INDENT> dir = random.choice([direction.LEFT]) <NEW_LINE> <DEDENT> if coordinate is None: <NEW_LINE> <INDENT> coordinate = [random.randrange(xSize-((len(text)-1)*dir[0])),random.randrange(ySize-((len(text)-1)*dir[1]))] <NEW_LINE> <DEDENT> return cls(None,text,group,coordinate,dir) <NEW_LINE> <DEDENT> def cloneTest(self): <NEW_LINE> <INDENT> return word.fromRandom("SSSSS") <NEW_LINE> <DEDENT> def updateGrid(self): <NEW_LINE> <INDENT> self.grid =dict() <NEW_LINE> _pos = self.coordinate <NEW_LINE> for c in self.text: <NEW_LINE> <INDENT> k=str(_pos) <NEW_LINE> self.grid[k]=c <NEW_LINE> _pos = list(map(add,_pos,self.dir)) <NEW_LINE> <DEDENT> <DEDENT> def getGrid(): <NEW_LINE> <INDENT> return self.grid <NEW_LINE> <DEDENT> def __repr__(s): <NEW_LINE> <INDENT> return "{}({},'{}',{},{},{})".format(s.__class__.__name__,None,s.text,s.group,s.coordinate,s.dir) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def track(c,s): <NEW_LINE> <INDENT> word.iCount += 1 <NEW_LINE> word.instances[word.iCount] = s <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def printTracking(c): <NEW_LINE> <INDENT> for k in word.instances: <NEW_LINE> <INDENT> print(k,word.instances[k]) | description of class | 62598fc7ad47b63b2c5a7b6f |
class Vector4: <NEW_LINE> <INDENT> def as_list(self): <NEW_LINE> <INDENT> return [self.x, self.y, self.z, self.w] <NEW_LINE> <DEDENT> def as_tuple(self): <NEW_LINE> <INDENT> return (self.x, self.y, self.z, self.w) <NEW_LINE> <DEDENT> def get_copy(self): <NEW_LINE> <INDENT> v = NifFormat.Vector4() <NEW_LINE> v.x = self.x <NEW_LINE> v.y = self.y <NEW_LINE> v.z = self.z <NEW_LINE> v.w = self.w <NEW_LINE> return v <NEW_LINE> <DEDENT> def get_vector_3(self): <NEW_LINE> <INDENT> v = NifFormat.Vector3() <NEW_LINE> v.x = self.x <NEW_LINE> v.y = self.y <NEW_LINE> v.z = self.z <NEW_LINE> return v <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "[ %6.3f %6.3f %6.3f %6.3f ]"%(self.x, self.y, self.z, self.w) <NEW_LINE> <DEDENT> def __eq__(self, rhs): <NEW_LINE> <INDENT> if isinstance(rhs, type(None)): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if not isinstance(rhs, NifFormat.Vector4): <NEW_LINE> <INDENT> raise TypeError( "do not know how to compare Vector4 and %s" % rhs.__class__) <NEW_LINE> <DEDENT> if abs(self.x - rhs.x) > NifFormat.EPSILON: return False <NEW_LINE> if abs(self.y - rhs.y) > NifFormat.EPSILON: return False <NEW_LINE> if abs(self.z - rhs.z) > NifFormat.EPSILON: return False <NEW_LINE> if abs(self.w - rhs.w) > NifFormat.EPSILON: return False <NEW_LINE> return True <NEW_LINE> <DEDENT> def __ne__(self, rhs): <NEW_LINE> <INDENT> return not self.__eq__(rhs) | >>> from pyffi.formats.nif import NifFormat
>>> vec = NifFormat.Vector4()
>>> vec.x = 1.0
>>> vec.y = 2.0
>>> vec.z = 3.0
>>> vec.w = 4.0
>>> print(vec)
[ 1.000 2.000 3.000 4.000 ]
>>> vec.as_list()
[1.0, 2.0, 3.0, 4.0]
>>> vec.as_tuple()
(1.0, 2.0, 3.0, 4.0)
>>> print(vec.get_vector_3())
[ 1.000 2.000 3.000 ]
>>> vec2 = NifFormat.Vector4()
>>> vec == vec2
False
>>> vec2.x = 1.0
>>> vec2.y = 2.0
>>> vec2.z = 3.0
>>> vec2.w = 4.0
>>> vec == vec2
True | 62598fc7dc8b845886d538d3 |
class ComputeHealthChecksDeleteRequest(_messages.Message): <NEW_LINE> <INDENT> healthCheck = _messages.StringField(1, required=True) <NEW_LINE> project = _messages.StringField(2, required=True) | A ComputeHealthChecksDeleteRequest object.
Fields:
healthCheck: Name of the HealthCheck resource to delete.
project: Name of the project scoping this request. | 62598fc7bf627c535bcb17bf |
class AddressInfoView(APIView): <NEW_LINE> <INDENT> permission_classes = [permissions.IsAuthenticated] <NEW_LINE> serializer_class = AddressSerializer <NEW_LINE> http_method_names = ['post'] <NEW_LINE> def post(self, request, format=None): <NEW_LINE> <INDENT> data = request.data.copy() <NEW_LINE> data['user'] = request.user.username <NEW_LINE> url = "https://api.bitaps.com/" + str(request.data['coin']) + "/v1/blockchain/" + "address/transactions/" + str(request.data['address']) <NEW_LINE> data['url'] = url <NEW_LINE> req_stat = requests.get(url).status_code <NEW_LINE> if req_stat == 200: <NEW_LINE> <INDENT> data['request_status'] = 'Valid' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data['request_status'] = 'Invalid' <NEW_LINE> <DEDENT> serializer = AddressSerializer(data=data) <NEW_LINE> if serializer.is_valid(): <NEW_LINE> <INDENT> serializer.save() <NEW_LINE> return Response(serializer.data, status=status.HTTP_201_CREATED) <NEW_LINE> <DEDENT> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) | API endpoint that shows all the transactions related to the specific address. | 62598fc77cff6e4e811b5d3d |
class DescribeApplicationTriggerPersonalResponse(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Data = None <NEW_LINE> self.RequestId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> if params.get("Data") is not None: <NEW_LINE> <INDENT> self.Data = DescribeApplicationTriggerPersonalResp() <NEW_LINE> self.Data._deserialize(params.get("Data")) <NEW_LINE> <DEDENT> self.RequestId = params.get("RequestId") | DescribeApplicationTriggerPersonal返回参数结构体
| 62598fc72c8b7c6e89bd3ada |
class Detector: <NEW_LINE> <INDENT> def __init__(self, detector): <NEW_LINE> <INDENT> self.detector = detector <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return type(self).__name__ <NEW_LINE> <DEDENT> def detect_and_compute(self, img): <NEW_LINE> <INDENT> kp, des = self.detector.detectAndCompute(img, None) <NEW_LINE> return kp, des | Base class for detector wrappers | 62598fc760cbc95b06364655 |
class Info(enum.IntFlag): <NEW_LINE> <INDENT> NONE = 0 <NEW_LINE> BASIC = 1 <NEW_LINE> SCORE = 2 <NEW_LINE> PV = 4 <NEW_LINE> REFUTATION = 8 <NEW_LINE> CURRLINE = 16 <NEW_LINE> ALL = BASIC | SCORE | PV | REFUTATION | CURRLINE | Used to filter information sent by the chess engine. | 62598fc7377c676e912f6f01 |
class TestPaverNodeInstall(PaverTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super().setUp() <NEW_LINE> os.environ['NO_PREREQ_INSTALL'] = 'false' <NEW_LINE> <DEDENT> def test_npm_install_with_subprocess_error(self): <NEW_LINE> <INDENT> with patch('subprocess.Popen') as _mock_popen: <NEW_LINE> <INDENT> _mock_subprocess = mock.Mock() <NEW_LINE> attrs = {'wait': fail_on_npm_install} <NEW_LINE> _mock_subprocess.configure_mock(**attrs) <NEW_LINE> _mock_popen.return_value = _mock_subprocess <NEW_LINE> with self.assertRaises(Exception): <NEW_LINE> <INDENT> pavelib.prereqs.node_prereqs_installation() <NEW_LINE> <DEDENT> <DEDENT> self.assertEqual(_mock_popen.call_count, 2) <NEW_LINE> <DEDENT> def test_npm_install_called_once_when_successful(self): <NEW_LINE> <INDENT> with patch('subprocess.Popen') as _mock_popen: <NEW_LINE> <INDENT> pavelib.prereqs.node_prereqs_installation() <NEW_LINE> <DEDENT> self.assertEqual(_mock_popen.call_count, 1) <NEW_LINE> <DEDENT> def test_npm_install_with_unexpected_subprocess_error(self): <NEW_LINE> <INDENT> with patch('subprocess.Popen') as _mock_popen: <NEW_LINE> <INDENT> _mock_popen.side_effect = unexpected_fail_on_npm_install <NEW_LINE> with self.assertRaises(BuildFailure): <NEW_LINE> <INDENT> pavelib.prereqs.node_prereqs_installation() <NEW_LINE> <DEDENT> <DEDENT> self.assertEqual(_mock_popen.call_count, 1) | Test node install logic | 62598fc7167d2b6e312b728f |
class AuthManager(): <NEW_LINE> <INDENT> def __init__(self, app): <NEW_LINE> <INDENT> self.user_datastore = PeeweeUserDatastore(db, User, Role, UserRoles) <NEW_LINE> self.security = Security(app, self.user_datastore, register_blueprint=True) | Manager of security
Include
- Registration without email confirmation
- Login
- Forgot password
- Change Password | 62598fc7091ae35668704f41 |
class AlexaPowerController(AlexaCapibility): <NEW_LINE> <INDENT> def name(self): <NEW_LINE> <INDENT> return "Alexa.PowerController" <NEW_LINE> <DEDENT> def properties_supported(self): <NEW_LINE> <INDENT> return [{"name": "powerState"}] <NEW_LINE> <DEDENT> def properties_proactively_reported(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def properties_retrievable(self): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> def get_property(self, name): <NEW_LINE> <INDENT> if name != "powerState": <NEW_LINE> <INDENT> raise UnsupportedProperty(name) <NEW_LINE> <DEDENT> if self.entity.domain == climate.DOMAIN: <NEW_LINE> <INDENT> is_on = self.entity.state != climate.HVAC_MODE_OFF <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> is_on = self.entity.state != STATE_OFF <NEW_LINE> <DEDENT> return "ON" if is_on else "OFF" | Implements Alexa.PowerController.
https://developer.amazon.com/docs/device-apis/alexa-powercontroller.html | 62598fc79f28863672818a08 |
class TransientPopup(STT.SuperToolTip): <NEW_LINE> <INDENT> def __init__(self, grid_window, comment, position): <NEW_LINE> <INDENT> STT.SuperToolTip.__init__(self, grid_window) <NEW_LINE> xls_comment = comment.comment <NEW_LINE> split = xls_comment.split(":") <NEW_LINE> header, rest = split[0], split[1:] <NEW_LINE> rest = ":".join(rest) <NEW_LINE> dc = wx.ClientDC(grid_window) <NEW_LINE> rest = wordwrap(rest, 400, dc) <NEW_LINE> self.SetHeader(header) <NEW_LINE> self.SetMessage(rest) <NEW_LINE> self.SetTarget(grid_window) <NEW_LINE> self.SetDrawHeaderLine(True) <NEW_LINE> self.SetStartDelay(100000) <NEW_LINE> self.SetEndDelay(100000) <NEW_LINE> self.ApplyStyle("Office 2007 Blue") <NEW_LINE> self.SetDropShadow(True) <NEW_LINE> self.DoShowNow() <NEW_LINE> grid_window.SetFocus() | This is a sublass of L{SuperToolTip} and it is used to display a
"comment-window" on the cells containing a comment (a note).
:note: If Mark Hammonds' `pywin32` package is not available, this class is
never invoked. | 62598fc7656771135c489988 |
class FastRandom(object): <NEW_LINE> <INDENT> def __init__(self, min, max, len=255): <NEW_LINE> <INDENT> self.randoms = [random.randint(min, max) for i in range(len)] <NEW_LINE> self.index = 0 <NEW_LINE> self.len = len <NEW_LINE> <DEDENT> def rand(self): <NEW_LINE> <INDENT> value = self.randoms[self.index] <NEW_LINE> if self.index < self.len - 1: <NEW_LINE> <INDENT> self.index += 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.index = 0 <NEW_LINE> <DEDENT> return value | random itself is too slow for our purposes, so we use random to populate
a small list of randomly generated numbers that can be used in each call
to randint()
A call to randint() just returns the a number from our list and increments
the list index.
This is faster and good enough for a "random" filler | 62598fc73617ad0b5ee06460 |
class TempFunctionCallCounter(TempValueSetter): <NEW_LINE> <INDENT> def __init__(self, function): <NEW_LINE> <INDENT> if cute_iter_tools.is_iterable(function): <NEW_LINE> <INDENT> first, second = function <NEW_LINE> if isinstance(second, basestring): <NEW_LINE> <INDENT> actual_function = getattr(first, second) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> assert callable(first) and callable(second) <NEW_LINE> actual_function = first() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> assert callable(function) <NEW_LINE> actual_function = function <NEW_LINE> try: <NEW_LINE> <INDENT> address = address_tools.object_to_string.get_address(function) <NEW_LINE> parent_object_address, function_name = address.rsplit('.', 1) <NEW_LINE> parent_object = address_tools.resolve(parent_object_address) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise Exception("Couldn't obtain parent/name pair from " "function; supply one manually or " "alternatively supply a getter/setter pair.") <NEW_LINE> <DEDENT> first, second = parent_object, function_name <NEW_LINE> <DEDENT> self.call_counting_function = count_calls(actual_function) <NEW_LINE> TempValueSetter.__init__( self, (first, second), value=self.call_counting_function ) <NEW_LINE> <DEDENT> call_count = property( lambda self: getattr(self.call_counting_function, 'call_count', 0) ) | Temporarily counts the number of calls made to a function.
Example:
f()
with TempFunctionCallCounter(f) as counter:
f()
f()
assert counter.call_count == 2
| 62598fc77cff6e4e811b5d3f |
class Predictor(Registrable): <NEW_LINE> <INDENT> def __init__(self, model: Model, dataset_reader: DatasetReader) -> None: <NEW_LINE> <INDENT> self._model = model <NEW_LINE> self._dataset_reader = dataset_reader <NEW_LINE> <DEDENT> def load_line(self, line: str) -> JsonDict: <NEW_LINE> <INDENT> return json.loads(line) <NEW_LINE> <DEDENT> def dump_line(self, outputs: JsonDict) -> str: <NEW_LINE> <INDENT> return json.dumps(outputs) + "\n" <NEW_LINE> <DEDENT> def predict_json(self, inputs: JsonDict) -> JsonDict: <NEW_LINE> <INDENT> instance = self._json_to_instance(inputs) <NEW_LINE> return self.predict_instance(instance) <NEW_LINE> <DEDENT> def predict_instance(self, instance: Instance) -> JsonDict: <NEW_LINE> <INDENT> outputs = self._model.forward_on_instance(instance) <NEW_LINE> return sanitize(outputs) <NEW_LINE> <DEDENT> def _json_to_instance(self, json_dict: JsonDict) -> Instance: <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def predict_batch_json(self, inputs: List[JsonDict]) -> List[JsonDict]: <NEW_LINE> <INDENT> instances = self._batch_json_to_instances(inputs) <NEW_LINE> return self.predict_batch_instance(instances) <NEW_LINE> <DEDENT> def predict_batch_instance(self, instances: List[Instance]) -> List[JsonDict]: <NEW_LINE> <INDENT> outputs = self._model.forward_on_instances(instances) <NEW_LINE> return sanitize(outputs) <NEW_LINE> <DEDENT> def _batch_json_to_instances(self, json_dicts: List[JsonDict]) -> List[Instance]: <NEW_LINE> <INDENT> instances = [] <NEW_LINE> for json_dict in json_dicts: <NEW_LINE> <INDENT> instances.append(self._json_to_instance(json_dict)) <NEW_LINE> <DEDENT> return instances <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_path(cls, archive_path: str, predictor_name: str = None) -> 'Predictor': <NEW_LINE> <INDENT> return Predictor.from_archive(load_archive(archive_path), predictor_name) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_archive(cls, archive: Archive, predictor_name: str = None) -> 'Predictor': <NEW_LINE> <INDENT> config = archive.config.duplicate() <NEW_LINE> if not predictor_name: <NEW_LINE> <INDENT> model_type = config.get("model").get("type") <NEW_LINE> if not model_type in DEFAULT_PREDICTORS: <NEW_LINE> <INDENT> raise ConfigurationError(f"No default predictor for model type {model_type}.\n" f"Please specify a predictor explicitly.") <NEW_LINE> <DEDENT> predictor_name = DEFAULT_PREDICTORS[model_type] <NEW_LINE> <DEDENT> dataset_reader_params = config["dataset_reader"] <NEW_LINE> dataset_reader = DatasetReader.from_params(dataset_reader_params) <NEW_LINE> model = archive.model <NEW_LINE> model.eval() <NEW_LINE> return Predictor.by_name(predictor_name)(model, dataset_reader) | a ``Predictor`` is a thin wrapper around an AllenNLP model that handles JSON -> JSON predictions
that can be used for serving models through the web API or making predictions in bulk. | 62598fc75fdd1c0f98e5e2a6 |
class API: <NEW_LINE> <INDENT> def __init__(self, modules = None): <NEW_LINE> <INDENT> self.modules = [] <NEW_LINE> if modules is not None: <NEW_LINE> <INDENT> self.modules.extend(modules) <NEW_LINE> <DEDENT> <DEDENT> def getAllTypes(self): <NEW_LINE> <INDENT> collector = Collector() <NEW_LINE> for module in self.modules: <NEW_LINE> <INDENT> for function in module.functions: <NEW_LINE> <INDENT> for arg in function.args: <NEW_LINE> <INDENT> collector.visit(arg.type) <NEW_LINE> <DEDENT> collector.visit(function.type) <NEW_LINE> <DEDENT> for interface in module.interfaces: <NEW_LINE> <INDENT> collector.visit(interface) <NEW_LINE> for method in interface.iterMethods(): <NEW_LINE> <INDENT> for arg in method.args: <NEW_LINE> <INDENT> collector.visit(arg.type) <NEW_LINE> <DEDENT> collector.visit(method.type) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return collector.types <NEW_LINE> <DEDENT> def getAllFunctions(self): <NEW_LINE> <INDENT> functions = [] <NEW_LINE> for module in self.modules: <NEW_LINE> <INDENT> functions.extend(module.functions) <NEW_LINE> <DEDENT> return functions <NEW_LINE> <DEDENT> def getAllInterfaces(self): <NEW_LINE> <INDENT> types = self.getAllTypes() <NEW_LINE> interfaces = [type for type in types if isinstance(type, Interface)] <NEW_LINE> for module in self.modules: <NEW_LINE> <INDENT> for interface in module.interfaces: <NEW_LINE> <INDENT> if interface not in interfaces: <NEW_LINE> <INDENT> interfaces.append(interface) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return interfaces <NEW_LINE> <DEDENT> def addModule(self, module): <NEW_LINE> <INDENT> self.modules.append(module) <NEW_LINE> <DEDENT> def getFunctionByName(self, name): <NEW_LINE> <INDENT> for module in self.modules: <NEW_LINE> <INDENT> for function in module.functions: <NEW_LINE> <INDENT> if function.name == name: <NEW_LINE> <INDENT> return function <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return None | API abstraction.
Essentially, a collection of types, functions, and interfaces. | 62598fc760cbc95b06364657 |
class TaskProgress(XMLRemoteModel): <NEW_LINE> <INDENT> class StageProgress(XMLRemoteModel): <NEW_LINE> <INDENT> name = serializers.XMLNodeAttributeField(attr='ID') <NEW_LINE> backup_workers = serializers.XMLNodeField('BackupWorkers', parse_callback=int) <NEW_LINE> terminated_workers = serializers.XMLNodeField('TerminatedWorkers', parse_callback=int) <NEW_LINE> running_workers = serializers.XMLNodeField('RunningWorkers', parse_callback=int) <NEW_LINE> total_workers = serializers.XMLNodeField('TotalWorkers', parse_callback=int) <NEW_LINE> input_records = serializers.XMLNodeField('InputRecords', parse_callback=int) <NEW_LINE> output_records = serializers.XMLNodeField('OutputRecords', parse_callback=int) <NEW_LINE> finished_percentage = serializers.XMLNodeField('FinishedPercentage', parse_callback=int) <NEW_LINE> <DEDENT> stages = serializers.XMLNodesReferencesField(StageProgress, 'Stage') <NEW_LINE> def get_stage_progress_formatted_string(self): <NEW_LINE> <INDENT> buf = six.StringIO() <NEW_LINE> buf.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) <NEW_LINE> buf.write(' ') <NEW_LINE> for stage in self.stages: <NEW_LINE> <INDENT> buf.write('{0}:{1}/{2}/{3}{4}[{5}%]\t'.format( stage.name, stage.running_workers, stage.terminated_workers, stage.total_workers, '(+%s backups)' % stage.backup_workers if stage.backup_workers > 0 else '', stage.finished_percentage )) <NEW_LINE> <DEDENT> return buf.getvalue() | TaskProgress reprents for the progress of a task.
A single TaskProgress may consist of several stages.
:Example:
>>> progress = instance.get_task_progress('task_name')
>>> progress.get_stage_progress_formatted_string()
2015-11-19 16:39:07 M1_Stg1_job0:0/0/1[0%] R2_1_Stg1_job0:0/0/1[0%] | 62598fc78a349b6b43686559 |
class Paster(threading.Thread): <NEW_LINE> <INDENT> def __init__(self, url, **kwargs): <NEW_LINE> <INDENT> self.url = url <NEW_LINE> self.data = kwargs <NEW_LINE> self.error = None <NEW_LINE> self.result = None <NEW_LINE> threading.Thread.__init__(self) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> request = urllib2.Request( self.url, urllib.urlencode(self.data), headers={'User-Agent': 'SublimeText2'}) <NEW_LINE> response = urllib2.urlopen(request, timeout=5) <NEW_LINE> <DEDENT> except urllib2.HTTPError as err: <NEW_LINE> <INDENT> self.error = 'HTTP error {0}.'.format(err.code) <NEW_LINE> <DEDENT> except urllib2.URLError as err: <NEW_LINE> <INDENT> self.error = 'URL error {0}.'.format(err.reason) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.result = response.url | Paste code snippets to ubuntu pastebin. | 62598fc7377c676e912f6f02 |
class CustomSignupForm(SignupForm): <NEW_LINE> <INDENT> birth_day = forms.DateField(label='Birthday') <NEW_LINE> first_name = forms.CharField(max_length=30, label='First Name') <NEW_LINE> last_name = forms.CharField(max_length=30, label='Last Name') <NEW_LINE> class Meta: <NEW_LINE> <INDENT> widgets = {'birth_day': DateInput()} <NEW_LINE> <DEDENT> def custom_signup(self, request, user): <NEW_LINE> <INDENT> super(CustomSignupForm, self).custom_signup(request, user) <NEW_LINE> birth_day = self.cleaned_data.get('birth_day') <NEW_LINE> profile = MyUser.objects.create(user=user, birth_day=birth_day) | Extended SignupForm for MyUser model | 62598fc755399d3f05626833 |
class ListCategoriesByIDInputSet(InputSet): <NEW_LINE> <INDENT> def set_APIKey(self, value): <NEW_LINE> <INDENT> super(ListCategoriesByIDInputSet, self)._set_input('APIKey', value) <NEW_LINE> <DEDENT> def set_AccessToken(self, value): <NEW_LINE> <INDENT> super(ListCategoriesByIDInputSet, self)._set_input('AccessToken', value) <NEW_LINE> <DEDENT> def set_CategoryID(self, value): <NEW_LINE> <INDENT> super(ListCategoriesByIDInputSet, self)._set_input('CategoryID', value) <NEW_LINE> <DEDENT> def set_ClientID(self, value): <NEW_LINE> <INDENT> super(ListCategoriesByIDInputSet, self)._set_input('ClientID', value) <NEW_LINE> <DEDENT> def set_ClientSecret(self, value): <NEW_LINE> <INDENT> super(ListCategoriesByIDInputSet, self)._set_input('ClientSecret', value) <NEW_LINE> <DEDENT> def set_Fields(self, value): <NEW_LINE> <INDENT> super(ListCategoriesByIDInputSet, self)._set_input('Fields', value) <NEW_LINE> <DEDENT> def set_H1(self, value): <NEW_LINE> <INDENT> super(ListCategoriesByIDInputSet, self)._set_input('H1', value) <NEW_LINE> <DEDENT> def set_Part(self, value): <NEW_LINE> <INDENT> super(ListCategoriesByIDInputSet, self)._set_input('Part', value) <NEW_LINE> <DEDENT> def set_RefreshToken(self, value): <NEW_LINE> <INDENT> super(ListCategoriesByIDInputSet, self)._set_input('RefreshToken', value) | An InputSet with methods appropriate for specifying the inputs to the ListCategoriesByID
Choreo. The InputSet object is used to specify input parameters when executing this Choreo. | 62598fc7ad47b63b2c5a7b73 |
class Drain(SewerElement): <NEW_LINE> <INDENT> tag = 'ZB_E' <NEW_LINE> def __init__(self, ref): <NEW_LINE> <INDENT> super(Drain, self).__init__(ref) <NEW_LINE> self.geom = None <NEW_LINE> self.owner = '' <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.ref | A storm drain (`kolk` in Dutch).
| 62598fc77cff6e4e811b5d41 |
class InMageRcmApplyRecoveryPointInput(ApplyRecoveryPointProviderSpecificInput): <NEW_LINE> <INDENT> _validation = { 'instance_type': {'required': True}, 'recovery_point_id': {'required': True}, } <NEW_LINE> _attribute_map = { 'instance_type': {'key': 'instanceType', 'type': 'str'}, 'recovery_point_id': {'key': 'recoveryPointId', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(InMageRcmApplyRecoveryPointInput, self).__init__(**kwargs) <NEW_LINE> self.instance_type = 'InMageRcm' <NEW_LINE> self.recovery_point_id = kwargs['recovery_point_id'] | ApplyRecoveryPoint input specific to InMageRcm provider.
All required parameters must be populated in order to send to Azure.
:param instance_type: Required. The class type.Constant filled by server.
:type instance_type: str
:param recovery_point_id: Required. The recovery point Id.
:type recovery_point_id: str | 62598fc7ec188e330fdf8bb0 |
class OwnerUpdateView(LoginRequiredMixin, UpdateView): <NEW_LINE> <INDENT> def get_queryset(self): <NEW_LINE> <INDENT> print('update get_queryset called') <NEW_LINE> qs = super(OwnerUpdateView, self).get_queryset() <NEW_LINE> return qs.filter(ads=self.request.user) | Sub-class the UpdateView to pass the request to the form and limit the
queryset to the requesting user. | 62598fc7a8370b77170f06f6 |
class rpm(Plugin, RedHatPlugin): <NEW_LINE> <INDENT> optionList = [("rpmq", "queries for package information via rpm -q", "fast", True), ("rpmva", "runs a verify on all packages", "slow", False)] <NEW_LINE> def setup(self): <NEW_LINE> <INDENT> self.addCopySpec("/var/log/rpmpkgs") <NEW_LINE> if self.getOption("rpmq"): <NEW_LINE> <INDENT> self.collectExtOutput("/bin/rpm -qa --qf=\"%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}~~%{INSTALLTIME:date}\t%{INSTALLTIME}\t%{VENDOR}\n\" --nosignature --nodigest|/bin/awk -F ~~ '{printf \"%-60s%s\\n\",$1,$2}'|sort", root_symlink = "installed-rpms") <NEW_LINE> <DEDENT> if self.getOption("rpmva"): <NEW_LINE> <INDENT> self.collectExtOutput("/bin/rpm -Va", root_symlink = "rpm-Va", timeout = 3600) | RPM information
| 62598fc7adb09d7d5dc0a897 |
class DeleteLiveSnapshotTemplateRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.TemplateId = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.TemplateId = params.get("TemplateId") | DeleteLiveSnapshotTemplate请求参数结构体
| 62598fc7be7bc26dc9251fe9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.