code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
class TreeDynamicsSystem(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(TreeDynamicsSystem, self).__init__() <NEW_LINE> self._initInternalData() <NEW_LINE> <DEDENT> def _initInternalData(self): <NEW_LINE> <INDENT> self._nodes = {} <NEW_LINE> self._root_node_name = None <NEW_LINE> self._primitives = {} <NEW_LINE> <DEDENT> def updateNode(self, name, node): <NEW_LINE> <INDENT> assert(type(node) is DynamicsSystemNode) <NEW_LINE> assert(node.name == name) <NEW_LINE> self._nodes[name] = node <NEW_LINE> <DEDENT> def updateRootNodeName(self, name): <NEW_LINE> <INDENT> assert(len({ name } & self._nodes.keys()) == 1) <NEW_LINE> self._root_node_name = name <NEW_LINE> <DEDENT> def updatePrimitive(self, name, primitive): <NEW_LINE> <INDENT> assert(type(primitive) is DynamicsSystemPrimitive) <NEW_LINE> assert(primitive.name == name) <NEW_LINE> assert(len({ primitive.prev_node_name } & self._nodes.keys()) == 1) <NEW_LINE> assert(len(primitive.dynamics_dict.keys() & self._nodes.keys()) == len(primitive.dynamics_dict)) <NEW_LINE> self._primitives[name] = primitive <NEW_LINE> <DEDENT> def _checkStructure(self): <NEW_LINE> <INDENT> assert(self._root_node_name is not None) <NEW_LINE> <DEDENT> def optimizeActionsOnce(self): <NEW_LINE> <INDENT> self._checkStructure() <NEW_LINE> forwardWorkQueue = deque() <NEW_LINE> backwardWorkStack = [] <NEW_LINE> accumulatedActionError = 0 <NEW_LINE> forwardWorkQueue.append(self._root_node_name) <NEW_LINE> while len(forwardWorkQueue) > 0: <NEW_LINE> <INDENT> currentNodeName = forwardWorkQueue.pop() <NEW_LINE> currentNode = self._nodes[currentNodeName] <NEW_LINE> currentPrimitiveName = currentNode.next_primitive_name <NEW_LINE> if currentPrimitiveName is not None: <NEW_LINE> <INDENT> currentPrimitive = self._primitives[currentPrimitiveName] <NEW_LINE> backwardWorkStack.append(currentPrimitiveName) <NEW_LINE> nextNodes = {} <NEW_LINE> for k in currentPrimitive.dynamics_dict: <NEW_LINE> <INDENT> forwardWorkQueue.append(k) <NEW_LINE> nextNodes[k] = self._nodes[k] <NEW_LINE> <DEDENT> currentPrimitive.compute_forward(currentNode, nextNodes) <NEW_LINE> <DEDENT> <DEDENT> while len(backwardWorkStack) > 0: <NEW_LINE> <INDENT> currentPrimitiveName = backwardWorkStack.pop() <NEW_LINE> currentPrimitive = self._primitives[currentPrimitiveName] <NEW_LINE> previousNode = self._nodes[currentPrimitive.prev_node_name] <NEW_LINE> nextNodes = {} <NEW_LINE> for k in currentPrimitive.dynamics_dict: <NEW_LINE> <INDENT> nextNodes[k] = self._nodes[k] <NEW_LINE> <DEDENT> currentPrimitive.compute_backward(previousNode, nextNodes) <NEW_LINE> accumulatedActionError += currentPrimitive.action_error <NEW_LINE> <DEDENT> systemValue = self._nodes[self._root_node_name].value <NEW_LINE> return (systemValue, accumulatedActionError) <NEW_LINE> <DEDENT> def optimizeActions(self, shouldStop, verbose=0): <NEW_LINE> <INDENT> rounds = 0 <NEW_LINE> last_J = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> J, a_err = self.optimizeActionsOnce() <NEW_LINE> if verbose: <NEW_LINE> <INDENT> print('Round: {}, Value: {}, Error: {}'.format(rounds, J, a_err)) <NEW_LINE> <DEDENT> rounds += 1 <NEW_LINE> indicators = { 'rounds': rounds, 'last_value': last_J, 'value': J, 'action_error': a_err } <NEW_LINE> if shouldStop(indicators): <NEW_LINE> <INDENT> return J <NEW_LINE> <DEDENT> last_J = J
Tree-structured dynamics system.
62599055be383301e0254d25
class Display3DImage: <NEW_LINE> <INDENT> def __init__(self,image): <NEW_LINE> <INDENT> self.image = image <NEW_LINE> self.nx = np.shape(self.image)[0] <NEW_LINE> self.ny = np.shape(self.image)[1] <NEW_LINE> self.nz = np.shape(self.image)[2] <NEW_LINE> self.slice_direction = 2 <NEW_LINE> self.slice_number = int(self.nz/2-1) <NEW_LINE> self.fig = plt.figure() <NEW_LINE> self.slice_image = self.image[0:,0:,self.slice_number] <NEW_LINE> plt.imshow(self.slice_image) <NEW_LINE> plt.show() <NEW_LINE> self.cid_p = self.fig.canvas.mpl_connect('scroll_event', self.on_press) <NEW_LINE> <DEDENT> def drawImage(self, slice_direction, slice_number): <NEW_LINE> <INDENT> if (slice_direction == 0): <NEW_LINE> <INDENT> self.slice_image = np.abs(self.image[slice_number,0:,0:]) <NEW_LINE> <DEDENT> if (slice_direction == 1): <NEW_LINE> <INDENT> self.slice_image = np.abs(self.image[0:,slice_number,0:]) <NEW_LINE> <DEDENT> if (slice_direction == 2): <NEW_LINE> <INDENT> self.slice_image = np.abs(self.image[0:,0:,slice_number]) <NEW_LINE> <DEDENT> plt.imshow(self.slice_image) <NEW_LINE> plt.show() <NEW_LINE> <DEDENT> def on_press(self,event): <NEW_LINE> <INDENT> if (self.slice_direction == 0): <NEW_LINE> <INDENT> max_slice_num = self.nx-1 <NEW_LINE> <DEDENT> if (self.slice_direction == 1): <NEW_LINE> <INDENT> max_slice_num = self.ny-1 <NEW_LINE> <DEDENT> if (self.slice_direction == 2): <NEW_LINE> <INDENT> max_slice_num = self.nz-1 <NEW_LINE> <DEDENT> self.slice_number = min(max_slice_num, max(0, self.slice_number + event.step)) <NEW_LINE> self.drawImage(self.slice_direction, self.slice_number)
<Arguments> image : 3D image, nx, ny, nz: dimensions of image
6259905521bff66bcd724196
class MissingRequiredParameterError(FSMException): <NEW_LINE> <INDENT> pass
Exception raised when required parameter is missing.
62599055a17c0f6771d5d63a
class VirtualMachineScaleSetVMExtensionsSummary(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'name': {'readonly': True}, 'statuses_summary': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'statuses_summary': {'key': 'statusesSummary', 'type': '[VirtualMachineStatusCodeCount]'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(VirtualMachineScaleSetVMExtensionsSummary, self).__init__(**kwargs) <NEW_LINE> self.name = None <NEW_LINE> self.statuses_summary = None
Extensions summary for virtual machines of a virtual machine scale set. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: The extension name. :vartype name: str :ivar statuses_summary: The extensions information. :vartype statuses_summary: list[~azure.mgmt.compute.v2015_06_15.models.VirtualMachineStatusCodeCount]
6259905555399d3f05627a51
class Rate: <NEW_LINE> <INDENT> def user_select_rate(self): <NEW_LINE> <INDENT> print ('lets rate something!\n' 'what category would you like to view?\n') <NEW_LINE> i = 0 <NEW_LINE> for each in categories: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> print (i,'=',each) <NEW_LINE> <DEDENT> self.user_input = int(input('\noption: ')) <NEW_LINE> if self.user_input in range(0, len(categories)+1): <NEW_LINE> <INDENT> self.selected = categories[self.user_input-1] <NEW_LINE> r.user_rate(self.selected) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print ('--------------------------\n' 'oops! lets try that again\n') <NEW_LINE> self.user_input = 0 <NEW_LINE> r.user_select_rate() <NEW_LINE> <DEDENT> <DEDENT> def collect_items(self, user_dic, name): <NEW_LINE> <INDENT> print ('you have selected', name, 'which has the characteristics: ', user_dic[name]) <NEW_LINE> print ('please select an items number to rate, or add a new item by typing it in...') <NEW_LINE> print () <NEW_LINE> start = 0 <NEW_LINE> for key in user_dic: <NEW_LINE> <INDENT> if key != name: <NEW_LINE> <INDENT> start += 1 <NEW_LINE> print (start, '=', key) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def user_rate(self, name): <NEW_LINE> <INDENT> self.ratings = [] <NEW_LINE> self.user_dic = json.load(open('rateIT_' + name + '.txt', 'r')) <NEW_LINE> r.collect_items(self.user_dic, name) <NEW_LINE> self.user_input = input('==> ') <NEW_LINE> print ('Great! please rank each characteristic of ', self.user_input, ' from 0-10\n') <NEW_LINE> ranked = 1 <NEW_LINE> for i in self.user_dic[name]: <NEW_LINE> <INDENT> self.user_select = int(input(i + '= ')) <NEW_LINE> self.ratings.append(self.user_select) <NEW_LINE> <DEDENT> self.new_ratings = [self.ratings, ranked] <NEW_LINE> r.update_rate(self.new_ratings, self.user_dic, name, self.user_input) <NEW_LINE> <DEDENT> def update_rate(self, new_ratings, user_dic, category, element): <NEW_LINE> <INDENT> if element not in user_dic: <NEW_LINE> <INDENT> user_dic[element] = new_ratings <NEW_LINE> json.dump(user_dic, open('rateIT_' + category + '.txt', 'w')) <NEW_LINE> <DEDENT> elif element in user_dic: <NEW_LINE> <INDENT> times_ranked = user_dic[element][1] + new_ratings[1] <NEW_LINE> total_ranked = [x + y for x, y in zip(user_dic[element][0], new_ratings[0])] <NEW_LINE> user_dic[element] = [total_ranked, times_ranked] <NEW_LINE> json.dump(user_dic, open('rateIT_' + category + '.txt', 'w'))
Responisble for collection of user input
625990558da39b475be0471d
class FilePaths: <NEW_LINE> <INDENT> fnCharList = '../model/charList.txt' <NEW_LINE> fnSummary = '../model/summary.json' <NEW_LINE> fnInfer = '../data/img3.jpg' <NEW_LINE> fnCorpus = '../data/corpus.txt'
filenames and paths to data
6259905573bcbd0ca4bcb7c3
class CircuitSearchProvider(SearchProvider): <NEW_LINE> <INDENT> name = "Circuits" <NEW_LINE> headers = [ ('Circuit', 'Circuit'), ('Alias', 'Reference') ] <NEW_LINE> link = 'Circuit' <NEW_LINE> def fetch_results(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> results = services.session.query(Circuit).filter( or_(Circuit.Circuit.ilike(u'%{}%'.format(self.query)), Circuit.Reference.ilike(u'%{}%'.format(self.query)), Circuit.Owner.ilike(u'%{}%'.format(self.query)))) <NEW_LINE> for result in results: <NEW_LINE> <INDENT> self.results.append(SearchResult( reverse('circuit-info', kwargs={'circuitid': result.Circuit}), result) ) <NEW_LINE> <DEDENT> <DEDENT> except exc.OperationalError: <NEW_LINE> <INDENT> return None
Searchprovider for circuits
625990557b25080760ed8778
class CLIHandler: <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def out(data_to_print, args): <NEW_LINE> <INDENT> if isinstance(data_to_print, list): <NEW_LINE> <INDENT> for i, list_item in enumerate(data_to_print): <NEW_LINE> <INDENT> if not args.no_numbers: <NEW_LINE> <INDENT> print(f"{Fore.GREEN}{i+1}.{Fore.RESET}") <NEW_LINE> <DEDENT> if isinstance(list_item, list) or isinstance(list_item, tuple): <NEW_LINE> <INDENT> for list_item_sub_item in list_item: <NEW_LINE> <INDENT> if list_item_sub_item: <NEW_LINE> <INDENT> print(list_item_sub_item) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> print(list_item) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> elif isinstance(data_to_print, Exception): <NEW_LINE> <INDENT> print(str(data_to_print)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print(data_to_print) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def confirm_action(text_query: str = "This action is irreversible, are you sure to continue?") -> bool: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> choice = input(f"{text_query} [Y/n] ") or "y" <NEW_LINE> if choice.lower() in ['y', 'yes', 'n', 'no']: <NEW_LINE> <INDENT> return choice.lower() in ['y', 'yes'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> CLIHandler.out("Invalid choice, try again", None)
Common class for printing output to and acquiring input from CLI
62599055009cb60464d02a69
class VppGbpAcl(VppObject): <NEW_LINE> <INDENT> def __init__(self, test): <NEW_LINE> <INDENT> self._test = test <NEW_LINE> self.acl_index = 4294967295 <NEW_LINE> <DEDENT> def create_rule(self, is_ipv6=0, permit_deny=0, proto=-1, s_prefix=0, s_ip='\x00\x00\x00\x00', sport_from=0, sport_to=65535, d_prefix=0, d_ip='\x00\x00\x00\x00', dport_from=0, dport_to=65535): <NEW_LINE> <INDENT> if proto == -1 or proto == 0: <NEW_LINE> <INDENT> sport_to = 0 <NEW_LINE> dport_to = sport_to <NEW_LINE> <DEDENT> elif proto == 1 or proto == 58: <NEW_LINE> <INDENT> sport_to = 255 <NEW_LINE> dport_to = sport_to <NEW_LINE> <DEDENT> rule = ({'is_permit': permit_deny, 'is_ipv6': is_ipv6, 'proto': proto, 'srcport_or_icmptype_first': sport_from, 'srcport_or_icmptype_last': sport_to, 'src_ip_prefix_len': s_prefix, 'src_ip_addr': s_ip, 'dstport_or_icmpcode_first': dport_from, 'dstport_or_icmpcode_last': dport_to, 'dst_ip_prefix_len': d_prefix, 'dst_ip_addr': d_ip}) <NEW_LINE> return rule <NEW_LINE> <DEDENT> def add_vpp_config(self, rules): <NEW_LINE> <INDENT> reply = self._test.vapi.acl_add_replace(self.acl_index, r=rules, tag='GBPTest') <NEW_LINE> self.acl_index = reply.acl_index <NEW_LINE> return self.acl_index <NEW_LINE> <DEDENT> def remove_vpp_config(self): <NEW_LINE> <INDENT> self._test.vapi.acl_del(self.acl_index) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.object_id() <NEW_LINE> <DEDENT> def object_id(self): <NEW_LINE> <INDENT> return "gbp-acl:[%d]" % (self.acl_index) <NEW_LINE> <DEDENT> def query_vpp_config(self): <NEW_LINE> <INDENT> cs = self._test.vapi.acl_dump() <NEW_LINE> for c in cs: <NEW_LINE> <INDENT> if c.acl_index == self.acl_index: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False
GBP Acl
625990558e71fb1e983bcffb
class PermanentRedirectRouteHandler(BaseHandler): <NEW_LINE> <INDENT> def __init__(self, request, route_name, **route_args): <NEW_LINE> <INDENT> self.route_name = route_name <NEW_LINE> self.route_args = route_args <NEW_LINE> super(PermanentRedirectRouteHandler, self).__init__(request) <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> return permanent_redirect( self.absolute_url_for(self.route_name, **self.route_args) ) <NEW_LINE> <DEDENT> def post(self): <NEW_LINE> <INDENT> return permanent_redirect( self.absolute_url_for(self.route_name, **self.route_args) )
Performs permanent redirect (HTTP status code 301) to given route name.
6259905507f4c71912bb096d
class Normalize(object): <NEW_LINE> <INDENT> def __init__(self, mean, std): <NEW_LINE> <INDENT> self.mean = mean <NEW_LINE> self.std = std <NEW_LINE> <DEDENT> def __call__(self, sample): <NEW_LINE> <INDENT> image = sample <NEW_LINE> img = sample <NEW_LINE> sample = {'image': img, 'class1': class1,'class2': class2} <NEW_LINE> return sample
Rescale the image in a sample to a given size. Args: output_size (tuple or tuple): Desired output size. If tuple, output is matched to output_size. If int, smaller of image edges is matched to output_size keeping aspect ratio the same.
62599055a219f33f346c7d37
class PathReader(object): <NEW_LINE> <INDENT> field_names = ['x_position', 'y_position', 'speed', 'marker'] <NEW_LINE> def __init__(self, filename: str): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> <DEDENT> def write_path(self, waypoints: List[Waypoint]): <NEW_LINE> <INDENT> with open(self.filename, 'wb+') as csvfile: <NEW_LINE> <INDENT> csvfile.seek(0, 0) <NEW_LINE> csvfile.truncate() <NEW_LINE> writer = csv.DictWriter(csvfile, self.field_names) <NEW_LINE> for wp in waypoints: <NEW_LINE> <INDENT> x = wp.position.x <NEW_LINE> y = wp.position.y <NEW_LINE> writer.writerow({'x_position': x, 'y_position': y, 'speed': wp.speed, 'marker': wp.marker})
classdocs
62599055e76e3b2f99fd9f31
class SentenceEmbeddingRequest(AbstractModel): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Text = None <NEW_LINE> <DEDENT> def _deserialize(self, params): <NEW_LINE> <INDENT> self.Text = params.get("Text")
SentenceEmbedding请求参数结构体
625990553c8af77a43b689d9
class Mean(Moment): <NEW_LINE> <INDENT> name = 'mean' <NEW_LINE> order = 1
Calculates mean.
62599055b57a9660fecd2fae
class S3Uploader(object): <NEW_LINE> <INDENT> def __init__(self, boto3_factory, s3_bucket, default_folder=""): <NEW_LINE> <INDENT> self.s3_client = boto3_factory.get_client("s3") <NEW_LINE> self.s3_bucket = s3_bucket <NEW_LINE> self.default_folder = default_folder <NEW_LINE> if default_folder: <NEW_LINE> <INDENT> self.__create_folder(default_folder) <NEW_LINE> <DEDENT> <DEDENT> def __create_folder(self, folder): <NEW_LINE> <INDENT> if not folder.endswith("/"): <NEW_LINE> <INDENT> folder = folder + "/" <NEW_LINE> <DEDENT> self.s3_client.put_object(Bucket=self.s3_bucket, Key=folder, Body="") <NEW_LINE> <DEDENT> def put_file(self, file_path, key_name, folder=None): <NEW_LINE> <INDENT> s3_folder = folder if folder else self.default_folder <NEW_LINE> self.s3_client.upload_file(file_path, self.s3_bucket, s3_folder + key_name)
S3 uploader.
62599055dd821e528d6da412
class ConfigError(NameError): <NEW_LINE> <INDENT> pass
Invalid name
62599055b5575c28eb713765
class Variable: <NEW_LINE> <INDENT> def __init__(self, name=""): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.domain = OrderedSet() <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return self.name == other.name <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.name) <NEW_LINE> <DEDENT> def addDomain(self, domain): <NEW_LINE> <INDENT> self.domain.add(domain) <NEW_LINE> <DEDENT> def removeDomain(self, domain): <NEW_LINE> <INDENT> self.domain.remove(domain) <NEW_LINE> <DEDENT> def getDomain(self): <NEW_LINE> <INDENT> return self.domain <NEW_LINE> <DEDENT> def setName(self, varName): <NEW_LINE> <INDENT> self.name = varName <NEW_LINE> <DEDENT> def getName(self): <NEW_LINE> <INDENT> return self.name
Represent a variable in a DAG or a CPT. A variable depends almost completly on its name (a string). A variable is equal to another if they have the same name and it is hashable by the hash of its name (a hash of a string).
62599055b830903b9686ef17
class TestApiProject(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testApiProject(self): <NEW_LINE> <INDENT> pass
ApiProject unit test stubs
62599055460517430c432aeb
class Dealer(TimeStampedModel): <NEW_LINE> <INDENT> name = models.CharField(max_length=25) <NEW_LINE> address = models.CharField(max_length=50, blank=True, default='') <NEW_LINE> phone_number = models.CharField(max_length=12) <NEW_LINE> email = models.EmailField() <NEW_LINE> class Meta: <NEW_LINE> <INDENT> ordering = ('name',)
Dealer Model
6259905521bff66bcd724198
class ApiResponse(object): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> for k, v in kwargs.items(): <NEW_LINE> <INDENT> setattr(self, k, v)
Base class for all API responses. .. note:: All keyword arguments become properties.
62599055e5267d203ee6ce22
class KintoChangesListener(ListenerBase): <NEW_LINE> <INDENT> def __init__( self, client, broadcaster_id, included_resources, excluded_resources, resources=None ): <NEW_LINE> <INDENT> self.client = client <NEW_LINE> self.broadcaster_id = broadcaster_id <NEW_LINE> self.included_resources_uris = included_resources <NEW_LINE> self.included_resources = [] <NEW_LINE> self.excluded_resources_uris = excluded_resources <NEW_LINE> self.excluded_resources = [] <NEW_LINE> if resources: <NEW_LINE> <INDENT> self.included_resources = resources <NEW_LINE> <DEDENT> <DEDENT> def _convert_resources(self, event): <NEW_LINE> <INDENT> self.excluded_resources = [ utils.view_lookup_registry(event.app.registry, r) for r in self.excluded_resources_uris ] <NEW_LINE> self.included_resources = [ utils.view_lookup_registry(event.app.registry, r) for r in self.included_resources_uris ] <NEW_LINE> <DEDENT> def filter_records(self, impacted_records): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> for delta in impacted_records: <NEW_LINE> <INDENT> if 'new' not in delta: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> record = delta['new'] <NEW_LINE> bid = record['bucket'] <NEW_LINE> cid = record['collection'] <NEW_LINE> match = ( any(match_resource(r, bid, cid) for r in self.included_resources) and not any(match_resource(r, bid, cid) for r in self.excluded_resources) ) <NEW_LINE> if match: <NEW_LINE> <INDENT> ret.append(record) <NEW_LINE> <DEDENT> <DEDENT> return ret <NEW_LINE> <DEDENT> def __call__(self, event): <NEW_LINE> <INDENT> if event.payload['resource_name'] != 'record': <NEW_LINE> <INDENT> logger.debug("Resource name did not match. Was: {}".format( event.payload['resource_name'])) <NEW_LINE> return <NEW_LINE> <DEDENT> bucket_id = event.payload['bucket_id'] <NEW_LINE> collection_id = event.payload['collection_id'] <NEW_LINE> if bucket_id != MONITOR_BUCKET or collection_id != CHANGES_COLLECTION: <NEW_LINE> <INDENT> logger.debug("Event was not for monitor/changes; discarding") <NEW_LINE> return <NEW_LINE> <DEDENT> matching_records = self.filter_records(event.impacted_records) <NEW_LINE> if not matching_records: <NEW_LINE> <INDENT> logger.debug("No records matched; dropping event") <NEW_LINE> return <NEW_LINE> <DEDENT> timestamp = max(r["last_modified"] for r in matching_records) <NEW_LINE> etag = '"{}"'.format(timestamp) <NEW_LINE> return self.send_notification(bucket_id, collection_id, etag) <NEW_LINE> <DEDENT> def send_notification(self, bucket_id, collection_id, version): <NEW_LINE> <INDENT> service_id = '{}_{}'.format(bucket_id, collection_id) <NEW_LINE> logger.info("Sending version: {}, {}".format(self.broadcaster_id, service_id)) <NEW_LINE> self.client.send_version(self.broadcaster_id, service_id, version)
An event listener that's specialized for handling kinto-changes feeds. We have a plan to allow customizing event listeners to listen for updates on certain buckets, collections, or records. However, we don't have a plan to allow filtering out impacted records from events. This listener understands the structure of the kinto-changes collection and lets us do filtering on records to only push timestamps when certain monitored collections change.
6259905516aa5153ce401a18
class CloudBackupUploaderBarman(CloudBackupUploader): <NEW_LINE> <INDENT> def __init__( self, server_name, cloud_interface, max_archive_size, backup_dir, backup_id, compression=None, ): <NEW_LINE> <INDENT> super(CloudBackupUploaderBarman, self).__init__( server_name, cloud_interface, max_archive_size, compression=compression, ) <NEW_LINE> self.backup_dir = backup_dir <NEW_LINE> self.backup_id = backup_id <NEW_LINE> <DEDENT> def _get_tablespace_location(self, tablespace): <NEW_LINE> <INDENT> return os.path.join(self.backup_dir, str(tablespace.oid)) <NEW_LINE> <DEDENT> def backup(self): <NEW_LINE> <INDENT> backup_info = BackupInfo(self.backup_id) <NEW_LINE> backup_info.load(filename=os.path.join(self.backup_dir, "backup.info")) <NEW_LINE> controller = self._create_upload_controller(self.backup_id) <NEW_LINE> try: <NEW_LINE> <INDENT> self._backup_copy( controller, backup_info, os.path.join(self.backup_dir, "data"), backup_info.pg_major_version(), ) <NEW_LINE> controller.close() <NEW_LINE> self.copy_end_time = datetime.datetime.now() <NEW_LINE> with open( os.path.join(self.backup_dir, "backup.info"), "rb" ) as backup_info_file: <NEW_LINE> <INDENT> self.cloud_interface.upload_fileobj( backup_info_file, key=os.path.join(controller.key_prefix, "backup.info"), ) <NEW_LINE> <DEDENT> <DEDENT> except BaseException as exc: <NEW_LINE> <INDENT> self.handle_backup_errors("uploading data", exc) <NEW_LINE> raise SystemExit(1) <NEW_LINE> <DEDENT> logging.info( "Upload of backup completed (start time: %s, elapsed time: %s)", self.copy_start_time, human_readable_timedelta(datetime.datetime.now() - self.copy_start_time), ) <NEW_LINE> <DEDENT> def handle_backup_errors(self, action, exc): <NEW_LINE> <INDENT> msg_lines = force_str(exc).strip().splitlines() <NEW_LINE> if len(msg_lines) == 0: <NEW_LINE> <INDENT> msg_lines = [type(exc).__name__] <NEW_LINE> <DEDENT> logging.error("Backup upload failed %s (%s)", action, msg_lines[0]) <NEW_LINE> logging.debug("Exception details:", exc_info=exc)
A cloud storage upload client for a pre-existing backup on the Barman server.
62599055d7e4931a7ef3d5b2
class PrivateTopic(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Message privé' <NEW_LINE> verbose_name_plural = 'Messages privés' <NEW_LINE> <DEDENT> title = models.CharField('Titre', max_length=80) <NEW_LINE> subtitle = models.CharField('Sous-titre', max_length=200) <NEW_LINE> author = models.ForeignKey(User, verbose_name='Auteur', related_name='author') <NEW_LINE> participants = models.ManyToManyField(User, verbose_name='Participants', related_name='participants') <NEW_LINE> last_message = models.ForeignKey('PrivatePost', null=True, related_name='last_message', verbose_name='Dernier message') <NEW_LINE> pubdate = models.DateTimeField('Date de création', auto_now_add=True) <NEW_LINE> def __unicode__(self): <NEW_LINE> <INDENT> return self.title <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('zds.mp.views.topic', kwargs={'topic_pk': self.pk, 'topic_slug': slugify(self.title)}) <NEW_LINE> <DEDENT> def get_post_count(self): <NEW_LINE> <INDENT> return PrivatePost.objects.filter(privatetopic__pk=self.pk).count() <NEW_LINE> <DEDENT> def get_last_answer(self): <NEW_LINE> <INDENT> last_post = PrivatePost.objects .filter(privatetopic__pk=self.pk) .order_by('-pubdate') .first() <NEW_LINE> if last_post == self.first_post(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return last_post <NEW_LINE> <DEDENT> <DEDENT> def first_post(self): <NEW_LINE> <INDENT> return PrivatePost.objects .filter(privatetopic=self) .order_by('pubdate') .first() <NEW_LINE> <DEDENT> def last_read_post(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> post = PrivateTopicRead.objects .select_related() .filter(privatetopic=self, user=get_current_user()) <NEW_LINE> if len(post) == 0: <NEW_LINE> <INDENT> return self.first_post() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return post.latest('privatepost__pubdate').privatepost <NEW_LINE> <DEDENT> <DEDENT> except PrivatePost.DoesNotExist: <NEW_LINE> <INDENT> return self.first_post() <NEW_LINE> <DEDENT> <DEDENT> def first_unread_post(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> last_post = PrivateTopicRead.objects .select_related() .filter(privatetopic=self, user=get_current_user()) .latest('post__pubdate').privatepost <NEW_LINE> next_post = PrivatePost.objects.filter( privatetopic__pk=self.pk, pubdate__gt=last_post.pubdate).first() <NEW_LINE> return next_post <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> return self.first_post() <NEW_LINE> <DEDENT> <DEDENT> def alone(self): <NEW_LINE> <INDENT> return self.participants.count() == 0 <NEW_LINE> <DEDENT> def never_read(self): <NEW_LINE> <INDENT> return never_privateread(self)
Topic private, containing private posts.
6259905576d4e153a661dd15
class square(OpenSCADObject): <NEW_LINE> <INDENT> def __init__(self, size=None, center=None): <NEW_LINE> <INDENT> OpenSCADObject.__init__(self, 'square', {'size': size, 'center': center})
Creates a square at the origin of the coordinate system. When center is True the square will be centered on the origin, otherwise it is created in the first quadrant. The argument names are optional if the arguments are given in the same order as specified in the parameters :param size: If a single number is given, the result will be a square with sides of that length. If a 2 value sequence is given, then the values will correspond to the lengths of the X and Y sides. Default value is 1. :type size: number or 2 value sequence :param center: This determines the positioning of the object. If True, object is centered at (0,0). Otherwise, the square is placed in the positive quadrant with one corner at (0,0). Defaults to False. :type center: boolean
625990553eb6a72ae038bb94
class PBClient(object): <NEW_LINE> <INDENT> NAME = 'PB Server' <NEW_LINE> def __init__(self, address): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self.address = address <NEW_LINE> self.name = self.NAME <NEW_LINE> self.connection = None <NEW_LINE> self.factory = None <NEW_LINE> self.service_data = {} <NEW_LINE> self.retry_delay = 5.0 <NEW_LINE> self.retry_count = 0 <NEW_LINE> self.max_retries = 8640 <NEW_LINE> self.retrying = False <NEW_LINE> m = re.match(r'([\w.\-_]+):(\d+)', address) <NEW_LINE> if m: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> addr = socket.gethostbyname(m.group(1)) <NEW_LINE> <DEDENT> except socket.gaierror as err: <NEW_LINE> <INDENT> logger.error(err) <NEW_LINE> addr = m.group(1) <NEW_LINE> <DEDENT> data = { 'name': self.name, 'host': m.group(1), 'address': addr, 'port': int(m.group(2)), } <NEW_LINE> self.setup_service(data) <NEW_LINE> <DEDENT> <DEDENT> def retry(self): <NEW_LINE> <INDENT> self.retrying = True <NEW_LINE> if self.retry_count < self.max_retries and not self.active: <NEW_LINE> <INDENT> logger.debug('Re-trying connection to {} [{host}:{port}]'.format(self.name, **self.service_data)) <NEW_LINE> self.setup_service(self.service_data) <NEW_LINE> self.retry_count += 1 <NEW_LINE> return True <NEW_LINE> <DEDENT> self.retrying = False <NEW_LINE> <DEDENT> def setup_service(self, data): <NEW_LINE> <INDENT> self.service_data = data <NEW_LINE> if not self.active: <NEW_LINE> <INDENT> self.factory = ServerClientFactory() <NEW_LINE> self.factory.getRootObject().addCallback(self.on_connect).addErrback(self.on_failure) <NEW_LINE> reactor.connectTCP(self.service_data['address'], self.service_data['port'], self.factory) <NEW_LINE> <DEDENT> <DEDENT> def on_connect(self, perspective): <NEW_LINE> <INDENT> logger.info('{} {host}:{port} connected.'.format(self.name, **self.service_data)) <NEW_LINE> self.service = perspective <NEW_LINE> self.service.notifyOnDisconnect(self.on_disconnect) <NEW_LINE> self.active=True <NEW_LINE> self.retry_count = 0 <NEW_LINE> <DEDENT> def on_disconnect(self, obj): <NEW_LINE> <INDENT> self.active = False <NEW_LINE> logger.warning('Connection to {} disconnected'.format(self.name)) <NEW_LINE> reactor.callLater(self.retry_delay, self.retry) <NEW_LINE> <DEDENT> def on_failure(self, reason): <NEW_LINE> <INDENT> if not self.retrying: <NEW_LINE> <INDENT> logger.error('Connection to {} failed'.format(self.name)) <NEW_LINE> logger.error(reason) <NEW_LINE> reactor.callLater(self.retry_delay, self.retry)
A Perspective Broker Client :param address: string representing the <address>:<port> of the server
625990558da39b475be0471f
class LastResult(BasePacmanRunner): <NEW_LINE> <INDENT> def pacman_process(self, package_name): <NEW_LINE> <INDENT> result = open('/tmp/pacman.res').read() <NEW_LINE> if len(result) == 0: <NEW_LINE> <INDENT> result = False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result = int(result) == 0 <NEW_LINE> <DEDENT> return result
Since the pacman may block execution for a very long time, this handler provides a method for browser to know the result of the last pacman execution once it has ended, so that it can recover from an HTTP timeout. Returns boolean json
6259905538b623060ffaa2e9
class BadReferalError(Exception): <NEW_LINE> <INDENT> def __init__(self, message): <NEW_LINE> <INDENT> self.message = message
Raised when the information provide is insufficiant to identify a key piece of reference data
62599055097d151d1a2c259f
class TestHzToErb(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.convert = lambda frq: 21.4 * np.log(1 + 0.00437 * frq) <NEW_LINE> <DEDENT> def test_hz_to_erb_number(self): <NEW_LINE> <INDENT> data = np.random.randn(1)[0] <NEW_LINE> expected = self.convert(data) <NEW_LINE> actual = hz_to_erb(data) <NEW_LINE> self.assertEqual(expected, actual) <NEW_LINE> <DEDENT> def test_hz_to_erb_vector(self): <NEW_LINE> <INDENT> data = np.random.randn(100) <NEW_LINE> expected = self.convert(data) <NEW_LINE> actual = hz_to_erb(data) <NEW_LINE> self.assertTrue(np.array_equal(expected, actual)) <NEW_LINE> <DEDENT> def test_hz_to_erb_matrix(self): <NEW_LINE> <INDENT> data = np.random.randn(3, 100) <NEW_LINE> expected = self.convert(data) <NEW_LINE> actual = hz_to_erb(data) <NEW_LINE> self.assertTrue(np.array_equal(expected, actual))
Test the hz_to_erb function.
6259905523849d37ff8525f8
class SearchView(generic.ListView): <NEW_LINE> <INDENT> context_object_name = 'results' <NEW_LINE> template_name = 'blogs/search.html' <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> query = self.request.GET.get('search') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> query = '' <NEW_LINE> <DEDENT> if (query != ''): <NEW_LINE> <INDENT> results = Post.objects.filter(Q(content__icontains=query) | Q(title__icontains=query)).order_by('-create_date') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> results = Post.objects.all() <NEW_LINE> <DEDENT> return results
This will display the search the user has provided from the search bar on any other page.
62599055d99f1b3c44d06bd4
class ProgressBar(): <NEW_LINE> <INDENT> def __init__(self, epoch, total_epochs, data_loader): <NEW_LINE> <INDENT> self.epoch = epoch <NEW_LINE> self.total_epochs = total_epochs <NEW_LINE> self.loss = 0 <NEW_LINE> self.progress = tqdm( iterable=iter(data_loader), leave=False, desc=f'epoch {epoch + 1} / {total_epochs}', total=len(data_loader), miniters=0 ) <NEW_LINE> <DEDENT> def update(self, loss): <NEW_LINE> <INDENT> self.loss = loss <NEW_LINE> self.progress.set_postfix(loss=loss, refresh=False) <NEW_LINE> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> return self.progress.__iter__() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def __exit__(self, *args): <NEW_LINE> <INDENT> self.progress.close() <NEW_LINE> print(f'epoch {self.epoch + 1} / {self.total_epochs}, loss: {self.loss:0.4f}')
Pretty progress bar for training
625990553539df3088ecd7da
class TrainStrategy(_object): <NEW_LINE> <INDENT> __swig_setmethods__ = {} <NEW_LINE> __setattr__ = lambda self, name, value: _swig_setattr(self, TrainStrategy, name, value) <NEW_LINE> __swig_getmethods__ = {} <NEW_LINE> __getattr__ = lambda self, name: _swig_getattr(self, TrainStrategy, name) <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> Gradient = _wavenet.TrainStrategy_Gradient <NEW_LINE> CG = _wavenet.TrainStrategy_CG <NEW_LINE> BFGS = _wavenet.TrainStrategy_BFGS <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> this = _wavenet.new_TrainStrategy() <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> __swig_destroy__ = _wavenet.delete_TrainStrategy <NEW_LINE> __del__ = lambda self : None;
Proxy of C++ TrainStrategy class
625990552ae34c7f260ac61b
class PSF_Interpolator(object): <NEW_LINE> <INDENT> def __init__(self, y_keys=[], x_keys=[], **kwargs): <NEW_LINE> <INDENT> self.y_keys = y_keys <NEW_LINE> self.x_keys = x_keys <NEW_LINE> <DEDENT> def check_data_for_keys(self, data): <NEW_LINE> <INDENT> can_do_x = True <NEW_LINE> for key in self.x_keys: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data[key] <NEW_LINE> <DEDENT> except E: <NEW_LINE> <INDENT> print('Problems with', key, E) <NEW_LINE> can_do_x = False <NEW_LINE> <DEDENT> <DEDENT> can_do_y = True <NEW_LINE> for key in self.y_keys: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> data[key] <NEW_LINE> <DEDENT> except E: <NEW_LINE> <INDENT> print('Problems with', key, E) <NEW_LINE> can_do_y = False <NEW_LINE> <DEDENT> <DEDENT> return can_do_x, can_do_y <NEW_LINE> <DEDENT> def interpolate(self, X, **kwargs): <NEW_LINE> <INDENT> interpolated = {} <NEW_LINE> for key in self.x_keys: <NEW_LINE> <INDENT> interpolated[key] = X[key] <NEW_LINE> <DEDENT> interpolated = DataFrame(interpolated) <NEW_LINE> return interpolated <NEW_LINE> <DEDENT> def __call__(self, X, **kwargs): <NEW_LINE> <INDENT> return self.interpolate(X, **kwargs)
Class that returns some sort of PSF representation. Attributes ---------- x_keys : list of strings Keys that an interpolator takes to create output y_keys : list of strings Names of output keys Methods ------- interpolate Returns the psf at some location.
62599055009cb60464d02a6a
class Link(Button, ClickMixin, TextMixin): <NEW_LINE> <INDENT> pass
The Link implementation **Example Use:** Let's take the following example: .. code-block:: html <a id="someClassId" class="someClass" href="/some/link/path">Click Me</a> If the user wants to make the code above recognizable to the testing framework, they would add the attribute "data-qa-id" with a unique value. .. code-block:: html <a data-qa-id="some.identifier" id="someClassId" class="someClass" href="/some/link/path">Click Me</a> An example on how to interact with the element: .. code-block:: python import selenium from selenium.webdriver.common.by import By from selenium_data_attributes import structures driver = webdriver.FireFox() driver.get('http://www.some-url.com') locator = (By.XPATH, "//a[@data-qa-id="some.identifier"]") l = structures.Link(driver, *locator) # Inherits from Button l.click()
625990558e71fb1e983bcffd
class VariableAssignment(object): <NEW_LINE> <INDENT> openapi_types = { 'type': 'str', 'id': 'Identifier', 'init': 'Expression' } <NEW_LINE> attribute_map = { 'type': 'type', 'id': 'id', 'init': 'init' } <NEW_LINE> def __init__(self, type=None, id=None, init=None): <NEW_LINE> <INDENT> self._type = None <NEW_LINE> self._id = None <NEW_LINE> self._init = None <NEW_LINE> self.discriminator = None <NEW_LINE> if type is not None: <NEW_LINE> <INDENT> self.type = type <NEW_LINE> <DEDENT> if id is not None: <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <DEDENT> if init is not None: <NEW_LINE> <INDENT> self.init = init <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def type(self): <NEW_LINE> <INDENT> return self._type <NEW_LINE> <DEDENT> @type.setter <NEW_LINE> def type(self, type): <NEW_LINE> <INDENT> self._type = type <NEW_LINE> <DEDENT> @property <NEW_LINE> def id(self): <NEW_LINE> <INDENT> return self._id <NEW_LINE> <DEDENT> @id.setter <NEW_LINE> def id(self, id): <NEW_LINE> <INDENT> self._id = id <NEW_LINE> <DEDENT> @property <NEW_LINE> def init(self): <NEW_LINE> <INDENT> return self._init <NEW_LINE> <DEDENT> @init.setter <NEW_LINE> def init(self, init): <NEW_LINE> <INDENT> self._init = init <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in six.iteritems(self.openapi_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pprint.pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, VariableAssignment): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other
NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually.
62599055097d151d1a2c25a0
class FloatSlider(qt.QWidget): <NEW_LINE> <INDENT> sigSettingChanged = qt.pyqtSignal(qt.QObject, object, object) <NEW_LINE> def __init__(self, setting, parent): <NEW_LINE> <INDENT> qt.QWidget.__init__(self, parent) <NEW_LINE> self.setting = setting <NEW_LINE> self.setting.setOnModified(self.onModified) <NEW_LINE> layout = qt.QHBoxLayout() <NEW_LINE> layout.setSpacing(0) <NEW_LINE> layout.setContentsMargins(0, 0, 0, 0) <NEW_LINE> self.setLayout(layout) <NEW_LINE> s = self.slider = qt.QSlider(qt.Qt.Horizontal) <NEW_LINE> s.setMinimum(int(setting.minval/setting.scale)) <NEW_LINE> s.setMaximum(int(setting.maxval/setting.scale)) <NEW_LINE> s.setPageStep(int(setting.step/setting.scale)) <NEW_LINE> s.setTickInterval(int(setting.tick/setting.scale)) <NEW_LINE> s.setTickPosition(qt.QSlider.TicksAbove) <NEW_LINE> layout.addWidget(self.slider) <NEW_LINE> self.edit = qt.QLineEdit() <NEW_LINE> layout.addWidget(self.edit) <NEW_LINE> self.edit.editingFinished.connect(self.validateAndSet) <NEW_LINE> self.slider.valueChanged.connect(self.movedPosition) <NEW_LINE> self.onModified() <NEW_LINE> <DEDENT> def validateAndSet(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> val = self.setting.fromUIText(self.edit.text()) <NEW_LINE> styleClear(self.edit) <NEW_LINE> self.sigSettingChanged.emit(self, self.setting, val) <NEW_LINE> <DEDENT> except utils.InvalidType: <NEW_LINE> <INDENT> styleError(self.edit) <NEW_LINE> <DEDENT> <DEDENT> def movedPosition(self, val): <NEW_LINE> <INDENT> self.sigSettingChanged.emit( self, self.setting, float(val)*self.setting.scale) <NEW_LINE> <DEDENT> @qt.pyqtSlot() <NEW_LINE> def onModified(self): <NEW_LINE> <INDENT> self.edit.setText(self.setting.toUIText()) <NEW_LINE> self.slider.setValue(int(round( self.setting.get()/self.setting.scale)))
A slider control for a numerical value. Note: QSlider is integer only, so dragging slider makes values integers
62599055adb09d7d5dc0ba9e
class AcceptError(Exception): <NEW_LINE> <INDENT> def __init__(self, code, message): <NEW_LINE> <INDENT> self.code = code <NEW_LINE> self.message = message <NEW_LINE> super(AcceptError, self).__init__(code, message)
Exception thrown on incompatiblity with acceptable response characteristics.
62599055a219f33f346c7d39
class MultidropIMAPSSLRetriever(MultidropIMAPRetrieverBase, IMAPSSLinitMixIn): <NEW_LINE> <INDENT> _confitems = ( ConfInstance(name='configparser', required=False), ConfDirectory(name='getmaildir', required=False, default='~/.getmail/'), ConfInt(name='timeout', required=False, default=180), ConfString(name='server'), ConfInt(name='port', required=False, default=imaplib.IMAP4_SSL_PORT), ConfString(name='username'), ConfPassword(name='password', required=False, default=None), ConfTupleOfStrings(name='password_command', required=False, default=()), ConfTupleOfUnicode(name='mailboxes', required=False, default="('INBOX', )", allow_specials=('ALL',)), ConfBool(name='use_peek', required=False, default=True), ConfString(name='move_on_delete', required=False, default=None), ConfBool(name='record_mailbox', required=False, default=True), ConfFile(name='keyfile', required=False, default=None), ConfFile(name='certfile', required=False, default=None), ConfFile(name='ca_certs', required=False, default=None), ConfTupleOfStrings(name='ssl_fingerprints', required=False, default=()), ConfString(name='ssl_version', required=False, default=None), ConfString(name='ssl_ciphers', required=False, default=None), ConfBool(name='use_cram_md5', required=False, default=False), ConfBool(name='use_kerberos', required=False, default=False), ConfBool(name='use_xoauth2', required=False, default=False), ConfString(name='envelope_recipient'), ConfString(name='ssl_cert_hostname', required=False, default=None), ConfString(name='imap_search', required=False, default=None), ConfString(name='imap_on_delete', required=False, default=None), ) <NEW_LINE> received_from = None <NEW_LINE> received_with = 'IMAP4-SSL' <NEW_LINE> received_by = localhostname() <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> self.log.trace() <NEW_LINE> return 'MultidropIMAPSSLRetriever:%s@%s:%s' % ( self.conf.get('username', 'username'), self.conf.get('server', 'server'), self.conf.get('port', 'port') ) <NEW_LINE> <DEDENT> def showconf(self): <NEW_LINE> <INDENT> self.log.trace() <NEW_LINE> self.log.info('MultidropIMAPSSLRetriever(%s)' % self._confstring() + os.linesep)
Retriever class for multi-drop IMAPv4-over-SSL mailboxes.
625990554428ac0f6e659a6e
class ActorCannotTalk(ActorException): <NEW_LINE> <INDENT> pass
When an actor cannot talk. See Also: :class:`Actor` :meth:`Actor.say()`
6259905501c39578d7f141d2
class IndividualViewSet(AccessView): <NEW_LINE> <INDENT> document = IndividualDocument <NEW_LINE> serializer_class = IndividualElasticSerializer <NEW_LINE> lookup_field = 'id' <NEW_LINE> ignore = [404] <NEW_LINE> filter_backends = [FilteringFilterBackend, IdsFilterBackend, OrderingFilterBackend, MultiMatchSearchFilterBackend] <NEW_LINE> pagination_class = CustomPagination <NEW_LINE> search_fields = ( 'characteristica_all_normed.measurement_type.label', 'characteristica_all_normed.choice.label', 'characteristica_all_normed.substance.label', 'name', 'study.name', 'study.sid', 'group.name', ) <NEW_LINE> multi_match_search_fields = {field: {"boost": 1} for field in search_fields} <NEW_LINE> multi_match_options = { 'operator': 'and' } <NEW_LINE> filter_fields = { 'pk': 'pk', 'id': 'id', 'name': 'name.raw', 'group_name': 'group.name.raw', **subject_filter_fields } <NEW_LINE> ordering_fields = { 'id': 'id', 'group': 'group.raw', }
Endpoint to query individuals The individual endpoint gives access to the individual subjects data.
625990550a50d4780f706859
class HelpWidget(RichJupyterWidget): <NEW_LINE> <INDENT> def clean_invalid_var_chars(self, var): <NEW_LINE> <INDENT> return re.sub(r'\W|^(?=\d)', '_', var) <NEW_LINE> <DEDENT> def get_signature(self, content): <NEW_LINE> <INDENT> data = content.get('data', {}) <NEW_LINE> text = data.get('text/plain', '') <NEW_LINE> if text: <NEW_LINE> <INDENT> text = ANSI_OR_SPECIAL_PATTERN.sub('', text) <NEW_LINE> self._control.current_prompt_pos = self._prompt_pos <NEW_LINE> line = self._control.get_current_line_to_cursor() <NEW_LINE> name = line[:-1].split('(')[-1] <NEW_LINE> name = name.split('.')[-1] <NEW_LINE> try: <NEW_LINE> <INDENT> name = self.clean_invalid_var_chars(name).split('_')[-1] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> argspec = getargspecfromtext(text) <NEW_LINE> if argspec: <NEW_LINE> <INDENT> signature = name + argspec <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> signature = getsignaturefromtext(text, name) <NEW_LINE> <DEDENT> return signature <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> <DEDENT> def is_defined(self, objtxt, force_import=False): <NEW_LINE> <INDENT> if self._reading: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> wait_loop = QEventLoop() <NEW_LINE> self.sig_got_reply.connect(wait_loop.quit) <NEW_LINE> self.silent_exec_method( "get_ipython().kernel.is_defined('%s', force_import=%s)" % (objtxt, force_import)) <NEW_LINE> wait_loop.exec_() <NEW_LINE> self.sig_got_reply.disconnect(wait_loop.quit) <NEW_LINE> wait_loop = None <NEW_LINE> return self._kernel_reply <NEW_LINE> <DEDENT> def get_doc(self, objtxt): <NEW_LINE> <INDENT> if self._reading: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> wait_loop = QEventLoop() <NEW_LINE> self.sig_got_reply.connect(wait_loop.quit) <NEW_LINE> self.silent_exec_method("get_ipython().kernel.get_doc('%s')" % objtxt) <NEW_LINE> wait_loop.exec_() <NEW_LINE> self.sig_got_reply.disconnect(wait_loop.quit) <NEW_LINE> wait_loop = None <NEW_LINE> return self._kernel_reply <NEW_LINE> <DEDENT> def get_source(self, objtxt): <NEW_LINE> <INDENT> if self._reading: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> wait_loop = QEventLoop() <NEW_LINE> self.sig_got_reply.connect(wait_loop.quit) <NEW_LINE> self.silent_exec_method("get_ipython().kernel.get_source('%s')" % objtxt) <NEW_LINE> wait_loop.exec_() <NEW_LINE> self.sig_got_reply.disconnect(wait_loop.quit) <NEW_LINE> wait_loop = None <NEW_LINE> return self._kernel_reply <NEW_LINE> <DEDENT> def _handle_inspect_reply(self, rep): <NEW_LINE> <INDENT> cursor = self._get_cursor() <NEW_LINE> info = self._request_info.get('call_tip') <NEW_LINE> if info and info.id == rep['parent_header']['msg_id'] and info.pos == cursor.position(): <NEW_LINE> <INDENT> content = rep['content'] <NEW_LINE> if content.get('status') == 'ok' and content.get('found', False): <NEW_LINE> <INDENT> signature = self.get_signature(content) <NEW_LINE> if signature: <NEW_LINE> <INDENT> self._control.show_calltip(_("Arguments"), signature, signature=True, color='#2D62FF')
Widget with the necessary attributes and methods to handle communications between the IPython Console and the Help plugin
62599055460517430c432aec
class StackedDAE(Model): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(StackedDAE, self).__init__() <NEW_LINE> log.error("StackedDAE not implemented yet!") <NEW_LINE> raise NotImplementedError("StackedDAE not implemented yet!")
A stacked Denoising Autoencoder stacks multiple layers of DAE's
625990558e7ae83300eea5c9
class Location(object): <NEW_LINE> <INDENT> def __init__(self, name, description): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.description = description <NEW_LINE> self.neighbors = {} <NEW_LINE> self.items = {} <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "<Location: %s>" % self.name <NEW_LINE> <DEDENT> def add_neighbor(self, direction, location): <NEW_LINE> <INDENT> raise UnimplementedException <NEW_LINE> <DEDENT> def add_item(self, item): <NEW_LINE> <INDENT> raise UnimplementedException <NEW_LINE> <DEDENT> def get_directions(self): <NEW_LINE> <INDENT> raise UnimplementedException <NEW_LINE> <DEDENT> def go(self, direction): <NEW_LINE> <INDENT> raise UnimplementedException <NEW_LINE> <DEDENT> def get_long_description(self): <NEW_LINE> <INDENT> raise UnimplementedException
The base class for every location in the game. To make a new Location, simply call the constructor: Location(name, description, *items) and a new Location with the specified information will be created. You may subclass Location to create other types of locations, such as DungeonLocation or something.
62599055596a89723612904a
class PI(object): <NEW_LINE> <INDENT> def __init__(self, setPoint, kp=0, ki=0): <NEW_LINE> <INDENT> self._kp = kp <NEW_LINE> self._ki = ki <NEW_LINE> self._setPoint = setPoint <NEW_LINE> self.error = 0.0 <NEW_LINE> self._started = False <NEW_LINE> <DEDENT> def update(self, currentValue): <NEW_LINE> <INDENT> self.error = self.setPoint - currentValue <NEW_LINE> if self.started: <NEW_LINE> <INDENT> self.dError = self.error - self.lastError <NEW_LINE> self.out = self.out - self.kp * self.dError - self.ki * self.error <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.out = - self.kp * self.error <NEW_LINE> self.started = True <NEW_LINE> <DEDENT> self.lastError = self.error <NEW_LINE> return self.out <NEW_LINE> <DEDENT> def restart(self): <NEW_LINE> <INDENT> self.started = False <NEW_LINE> <DEDENT> @property <NEW_LINE> def started(self): <NEW_LINE> <INDENT> return self._started <NEW_LINE> <DEDENT> @started.setter <NEW_LINE> def started(self, value): <NEW_LINE> <INDENT> self._started = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def setPoint(self): <NEW_LINE> <INDENT> return self._setPoint <NEW_LINE> <DEDENT> @setPoint.setter <NEW_LINE> def setPoint(self, value): <NEW_LINE> <INDENT> self._setPoint = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def kp(self): <NEW_LINE> <INDENT> return self._kp <NEW_LINE> <DEDENT> @kp.setter <NEW_LINE> def kp(self, value): <NEW_LINE> <INDENT> self._kp = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def ki(self): <NEW_LINE> <INDENT> return self._ki <NEW_LINE> <DEDENT> @ki.setter <NEW_LINE> def ki(self, value): <NEW_LINE> <INDENT> self._ki = value
Discrete PI control
62599055fff4ab517ebced58
@description("Upgrades given volume") <NEW_LINE> class UpgradeVolumeCommand(Command): <NEW_LINE> <INDENT> def __init__(self, parent): <NEW_LINE> <INDENT> self.parent = parent <NEW_LINE> <DEDENT> def run(self, context, args, kwargs, opargs): <NEW_LINE> <INDENT> tid = context.submit_task('volume.upgrade', self.parent.entity['id']) <NEW_LINE> return TaskPromise(context, tid)
Usage: upgrade Examples: upgrade Upgrades a volume.
6259905510dbd63aa1c72113
class PastDeadline(commands.CommandError): <NEW_LINE> <INDENT> def __init__(self, reschedule_deadline_hours, referees_mentions, match_id): <NEW_LINE> <INDENT> self.reschedule_deadline_hours = reschedule_deadline_hours <NEW_LINE> self.referees_mentions = referees_mentions <NEW_LINE> self.match_id = match_id
Special exception in case the deadline is passed.
62599055d6c5a102081e3653
class ParseError(Exception): <NEW_LINE> <INDENT> def __init__(self, message, lineno=None): <NEW_LINE> <INDENT> Exception.__init__(self) <NEW_LINE> self.message = message <NEW_LINE> self.lineno = lineno
Exception to signal parsing error
62599055baa26c4b54d507d9
class TestBaseModels(object): <NEW_LINE> <INDENT> def test_state(self): <NEW_LINE> <INDENT> state = mixer.blend("base.State") <NEW_LINE> assert state is not None, "Should create a State model" <NEW_LINE> assert type(str(state)) == str, "State should be a str object" <NEW_LINE> <DEDENT> def test_event_type(self): <NEW_LINE> <INDENT> event_type = mixer.blend('base.EventType') <NEW_LINE> assert event_type is not None, 'should create an EventType model' <NEW_LINE> assert type(str(event_type)) == str, 'event_type should be a str object' <NEW_LINE> <DEDENT> def test_endpoint_type(self): <NEW_LINE> <INDENT> endpoint_type = mixer.blend('base.EndpointType') <NEW_LINE> assert endpoint_type is not None, 'should create an EndpointType model' <NEW_LINE> assert type(str(endpoint_type)) == str, 'endpoint_type should be a str object' <NEW_LINE> <DEDENT> def test_notification_type(self): <NEW_LINE> <INDENT> notification_type = mixer.blend("base.NotificationType") <NEW_LINE> assert notification_type is not None, "Should create a NotificationType model" <NEW_LINE> assert type(str(notification_type)) == str, "NotificationType should be a str object" <NEW_LINE> <DEDENT> def test_escalation_level(self): <NEW_LINE> <INDENT> escalation_level = mixer.blend("base.EscalationLevel") <NEW_LINE> assert escalation_level is not None, "Should create an EscalationLevel model" <NEW_LINE> assert type(str(escalation_level)) == str, "EscalationLevel should be a str object" <NEW_LINE> <DEDENT> def test_incident_type(self): <NEW_LINE> <INDENT> incident_type = mixer.blend("base.IncidentType") <NEW_LINE> assert incident_type is not None, "Should create an IncidentType model" <NEW_LINE> assert type(str(incident_type)) == str, "IncidentType should be a str object"
Test class for core models
6259905545492302aabfda0d
class ChromeMiddlewware(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(ChromeMiddlewware, self).__init__() <NEW_LINE> <DEDENT> def process_request(self, request, spider): <NEW_LINE> <INDENT> if spider.name.find("chrome") >= 0: <NEW_LINE> <INDENT> spider.browser.get(url=request.url) <NEW_LINE> print("访问:{}".format(request.url)) <NEW_LINE> time.sleep(5) <NEW_LINE> return HtmlResponse(url=spider.browser.current_url, body=spider.browser.page_source, encoding="utf-8", request=request)
使用chrome去打开网页的中间件 打开网页后获取页面的源码 需要配置在scrapyProject.settings.py的DOWNLOADER_MIDDLEWARES中
625990558a43f66fc4bf36c3
class MenuBorderStyleFactory(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.logger = logging.getLogger(type(self).__name__) <NEW_LINE> <DEDENT> def create_border(self, border_style_type): <NEW_LINE> <INDENT> if border_style_type == MenuBorderStyleType.ASCII_BORDER: <NEW_LINE> <INDENT> return self.create_ascii_border() <NEW_LINE> <DEDENT> elif border_style_type == MenuBorderStyleType.LIGHT_BORDER: <NEW_LINE> <INDENT> return self.create_light_border() <NEW_LINE> <DEDENT> elif border_style_type == MenuBorderStyleType.HEAVY_BORDER: <NEW_LINE> <INDENT> return self.create_heavy_border() <NEW_LINE> <DEDENT> elif border_style_type == MenuBorderStyleType.DOUBLE_LINE_BORDER: <NEW_LINE> <INDENT> return self.create_doubleline_border() <NEW_LINE> <DEDENT> elif border_style_type == MenuBorderStyleType.HEAVY_OUTER_LIGHT_INNER_BORDER: <NEW_LINE> <INDENT> return self.create_heavy_outer_light_inner_border() <NEW_LINE> <DEDENT> elif border_style_type == MenuBorderStyleType.DOUBLE_LINE_OUTER_LIGHT_INNER_BORDER: <NEW_LINE> <INDENT> return self.create_doubleline_outer_light_inner_border() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.logger.info('Unrecognized border style type: {}. Defaulting to ASCII.'.format(border_style_type)) <NEW_LINE> return self.create_ascii_border() <NEW_LINE> <DEDENT> <DEDENT> def create_ascii_border(self): <NEW_LINE> <INDENT> return AsciiBorderStyle() <NEW_LINE> <DEDENT> def create_light_border(self): <NEW_LINE> <INDENT> return LightBorderStyle() <NEW_LINE> <DEDENT> def create_heavy_border(self): <NEW_LINE> <INDENT> if self.is_win_python35_or_earlier(): <NEW_LINE> <INDENT> return DoubleLineBorderStyle() <NEW_LINE> <DEDENT> return HeavyBorderStyle() <NEW_LINE> <DEDENT> def create_heavy_outer_light_inner_border(self): <NEW_LINE> <INDENT> if self.is_win_python35_or_earlier(): <NEW_LINE> <INDENT> return DoubleLineOuterLightInnerBorderStyle() <NEW_LINE> <DEDENT> return HeavyOuterLightInnerBorderStyle() <NEW_LINE> <DEDENT> def create_doubleline_border(self): <NEW_LINE> <INDENT> return DoubleLineBorderStyle() <NEW_LINE> <DEDENT> def create_doubleline_outer_light_inner_border(self): <NEW_LINE> <INDENT> return DoubleLineOuterLightInnerBorderStyle() <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_win_python35_or_earlier(): <NEW_LINE> <INDENT> return sys.platform.startswith("win") and sys.version_info.major < 3 or ( sys.version_info.major == 3 and sys.version_info.minor < 6)
Factory class for creating MenuBorderStyle instances.
6259905594891a1f408ba191
class Chromium(recipe_util.Recipe): <NEW_LINE> <INDENT> @staticmethod <NEW_LINE> def fetch_spec(props): <NEW_LINE> <INDENT> url = 'https://chromium.googlesource.com/chromium/src.git' <NEW_LINE> solution = { 'name' :'src', 'url' : url, 'deps_file': '.DEPS.git', 'managed' : False, 'custom_deps': {}, 'safesync_url': '', } <NEW_LINE> if props.get('webkit_revision', '') == 'ToT': <NEW_LINE> <INDENT> solution['custom_vars'] = {'webkit_revision': ''} <NEW_LINE> <DEDENT> spec = { 'solutions': [solution], } <NEW_LINE> if props.get('target_os'): <NEW_LINE> <INDENT> spec['target_os'] = props['target_os'].split(',') <NEW_LINE> <DEDENT> if props.get('target_os_only'): <NEW_LINE> <INDENT> spec['target_os_only'] = props['target_os_only'] <NEW_LINE> <DEDENT> return { 'type': 'gclient_git', 'gclient_git_spec': spec, } <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def expected_root(_props): <NEW_LINE> <INDENT> return 'src'
Basic Recipe class for Chromium.
62599055d53ae8145f919998
class CsvGenerator(MapReduceBase): <NEW_LINE> <INDENT> WRITER_CLASS = CsvWriter <NEW_LINE> @classmethod <NEW_LINE> def _flatten_json(cls, _dict, prefix=''): <NEW_LINE> <INDENT> for key in _dict.keys(): <NEW_LINE> <INDENT> value = _dict.pop(key) <NEW_LINE> _nested = None <NEW_LINE> if type(value) == dict: <NEW_LINE> <INDENT> _nested = value <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> _dict_from_value = transforms.loads(value, strict=False) <NEW_LINE> if _dict_from_value and type(_dict_from_value) == dict: <NEW_LINE> <INDENT> _nested = _dict_from_value <NEW_LINE> <DEDENT> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> if _nested: <NEW_LINE> <INDENT> flattened = cls._flatten_json( _nested, prefix=prefix + key + '_') <NEW_LINE> _dict.update(flattened) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> _dict[prefix + key] = unicode(value).encode('utf-8') <NEW_LINE> <DEDENT> <DEDENT> return _dict <NEW_LINE> <DEDENT> def map(self, unused_key, value): <NEW_LINE> <INDENT> json = self.json_parse(value) <NEW_LINE> if json: <NEW_LINE> <INDENT> json = CsvGenerator._flatten_json(json) <NEW_LINE> yield 'key', json <NEW_LINE> <DEDENT> <DEDENT> def reduce(self, unused_key, values): <NEW_LINE> <INDENT> master_list = [] <NEW_LINE> values = [value for value in values] <NEW_LINE> for value in values: <NEW_LINE> <INDENT> for key in value: <NEW_LINE> <INDENT> if key not in master_list: <NEW_LINE> <INDENT> master_list.append(key) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> try: <NEW_LINE> <INDENT> master_list = sorted(master_list, key=lambda item: int(item)) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> master_list = sorted(master_list) <NEW_LINE> <DEDENT> yield master_list, values
Generates a CSV file from a JSON formatted input file.
625990553539df3088ecd7dc
class ItemMedia(_BaseItemMedia): <NEW_LINE> <INDENT> def __init__(self, root, item): <NEW_LINE> <INDENT> _BaseItemMedia.__init__(self, root) <NEW_LINE> self.item = item <NEW_LINE> self.identifier = item.identifier <NEW_LINE> <DEDENT> def sprite(self, version=None): <NEW_LINE> <INDENT> identifier = self.identifier <NEW_LINE> if identifier.startswith(('tm', 'hm')): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> int(identifier[2:]) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> machines = self.item.machines <NEW_LINE> if version: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> machine = [ m for m in machines if m.version_group == version.version_group ][0] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> raise ValueError("%s doesn't exist in %s" % ( identifier, version.identifier)) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> machine = machines[-1] <NEW_LINE> <DEDENT> type_identifier = machine.move.type.identifier <NEW_LINE> identifier = identifier[:2] + '-' + type_identifier <NEW_LINE> <DEDENT> <DEDENT> elif identifier.startswith('data-card-'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> int(identifier[10:]) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> identifier = 'data-card' <NEW_LINE> <DEDENT> <DEDENT> if version is not None: <NEW_LINE> <INDENT> generation_id = version.generation.id <NEW_LINE> if generation_id <= 3 and identifier == 'dowsing-mchn': <NEW_LINE> <INDENT> identifier = 'itemfinder' <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> gen = 'gen%s' % generation_id <NEW_LINE> return self.from_path_elements([gen], identifier, '.png') <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> return self.from_path_elements([], identifier, '.png', surely_exists=True) <NEW_LINE> <DEDENT> def underground(self, rotation=0): <NEW_LINE> <INDENT> if not self.item.appears_underground: <NEW_LINE> <INDENT> raise ValueError("%s doesn't appear underground" % self.identifier) <NEW_LINE> <DEDENT> return super(ItemMedia, self).underground(rotation=rotation) <NEW_LINE> <DEDENT> def berry_image(self): <NEW_LINE> <INDENT> if not self.item.berry: <NEW_LINE> <INDENT> raise ValueError("%s is not a berry" % self.identifier) <NEW_LINE> <DEDENT> return self.from_path_elements(['berries'], self.identifier, '.png')
Media related to an item
62599055097d151d1a2c25a2
class DownloadError(Exception): <NEW_LINE> <INDENT> pass
Error happened during download or when processing the file
625990554e4d56256637393e
class LoadoutData(RESTPayload): <NEW_LINE> <INDENT> loadout_id: int <NEW_LINE> profile_id: int <NEW_LINE> faction_id: int <NEW_LINE> code_name: str
Data class for :class:`auraxium.ps2.Loadout`. This class mirrors the payload data returned by the API, you may use its attributes as keys in filters or queries.
62599055b5575c28eb713767
class EventDispatcher(Thread): <NEW_LINE> <INDENT> RESPONSE_HEADER = {'Content-Type': 'application/json'} <NEW_LINE> def __init__(self, event, subscription, retry_attempts, retry_interval): <NEW_LINE> <INDENT> Thread.__init__(self) <NEW_LINE> self.event = event <NEW_LINE> self.subscription = subscription <NEW_LINE> self.retry_attempts = retry_attempts <NEW_LINE> self.retry_interval = retry_interval <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> attempts_counter = 0 <NEW_LINE> done = False <NEW_LINE> try: <NEW_LINE> <INDENT> url = urlparse(self.subscription.redfish['Destination']) <NEW_LINE> json_str = self.event.serialize() <NEW_LINE> while (attempts_counter < self.retry_attempts and not done): <NEW_LINE> <INDENT> attempts_counter += 1 <NEW_LINE> try: <NEW_LINE> <INDENT> connection = HTTPConnection(url.hostname, port=url.port) <NEW_LINE> connection.request( 'POST', url.path, json_str, self.RESPONSE_HEADER) <NEW_LINE> done = True <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.exception( 'Could not dispatch event to {}. ' 'Error: {}'.format(url.netloc, e)) <NEW_LINE> time.sleep(self.retry_interval) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> connection.close() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> logging.exception( 'Error getting event and/or subscriber information: {}' .format(e))
Dispatches an event to its subscribers
6259905501c39578d7f141d3
class GraphWatershedAssignmentsLSF(GraphWatershedAssignmentsBase, LSFTask): <NEW_LINE> <INDENT> pass
GraphWatershedAssignments on lsf cluster
62599055379a373c97d9a55b
class ModuleDataGo1_10_15_64(ctypes.Structure): <NEW_LINE> <INDENT> _fields_ = [ ("pclntable", ctypes.c_uint64), ("pclntable_len", ctypes.c_uint64), ("pclntable_cap", ctypes.c_uint64), ("ftab", ctypes.c_uint64), ("ftab_len", ctypes.c_uint64), ("ftab_cap", ctypes.c_uint64), ("filetab", ctypes.c_uint64), ("filetab_len", ctypes.c_uint64), ("filetab_cap", ctypes.c_uint64), ("findfunctab", ctypes.c_uint64), ("minpc", ctypes.c_uint64), ("maxpc", ctypes.c_uint64), ("text", ctypes.c_uint64), ("etext", ctypes.c_uint64), ("noptrdata", ctypes.c_uint64), ("enoptrdata", ctypes.c_uint64), ("data", ctypes.c_uint64), ("edata", ctypes.c_uint64), ("bss", ctypes.c_uint64), ("ebss", ctypes.c_uint64), ("noptrbss", ctypes.c_uint64), ("enoptrbss", ctypes.c_uint64), ("end", ctypes.c_uint64), ("gcdata", ctypes.c_uint64), ("gcbss", ctypes.c_uint64), ("types", ctypes.c_uint64), ("etypes", ctypes.c_uint64), ("textsectmap", ctypes.c_uint64), ("textsectmap_len", ctypes.c_uint64), ("textsectmap_cap", ctypes.c_uint64), ("typelinks", ctypes.c_uint64), ("typelinks_len", ctypes.c_uint64), ("typelinks_cap", ctypes.c_uint64), ("itablinks", ctypes.c_uint64), ("itablinks_len", ctypes.c_uint64), ("itablinks_cap", ctypes.c_uint64), ("ptab", ctypes.c_uint64), ("ptab_len", ctypes.c_uint64), ("pluginpath", ctypes.c_uint64), ("pkghashes", ctypes.c_uint64), ("pkghashes_len", ctypes.c_uint64), ("pkghashes_cap", ctypes.c_uint64), ("modulename", ctypes.c_uint64), ("modulehashes", ctypes.c_uint64), ("modulehashes_len", ctypes.c_uint64), ("modulehashes_cap", ctypes.c_uint64), ("hasmain", ctypes.c_uint8), ("gcdatamask", ctypes.c_uint64), ("gcbssmask", ctypes.c_uint64), ("typemap", ctypes.c_uint64), ("bad", ctypes.c_bool), ("next", ctypes.c_uint64) ]
parse 64-bit Go1.10 through Go1.15
625990550c0af96317c577fb
class YandexMailLogin(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.driver = webdriver.Chrome() <NEW_LINE> self.driver.implicitly_wait(15) <NEW_LINE> self.driver.get('https://yandex.ru/') <NEW_LINE> <DEDENT> def test_login_yandex_mail(self): <NEW_LINE> <INDENT> driver = self.driver <NEW_LINE> self.assertIn('Яндекс', driver.title, msg='Открыта не главная страница Яндекс') <NEW_LINE> driver.find_element_by_link_text('Войти в почту').click() <NEW_LINE> driver.switch_to.window(driver.window_handles[1]) <NEW_LINE> self.assertIn('Авторизация', driver.title, msg='Страница авторизации не открылась') <NEW_LINE> driver.find_element(By.CSS_SELECTOR, '[name="login"]').send_keys('stesting.ru') <NEW_LINE> driver.find_element(By.CSS_SELECTOR, 'button.Button2').click() <NEW_LINE> driver.find_element(By.CSS_SELECTOR, '[name="passwd"]').send_keys('p1234567') <NEW_LINE> driver.find_element(By.CSS_SELECTOR, '.Button2_view_action').click() <NEW_LINE> time.sleep(1) <NEW_LINE> self.assertIn('Яндекс.Почта', driver.title, msg='Не перешли в почту. Могла открыться форма ввода моб.телефона')
Открываем главную страницу Яндекс, логинимся в почте
6259905521bff66bcd72419c
class RandomThreeParentsComposableTechnique(ComposableEvolutionaryTechnique): <NEW_LINE> <INDENT> def __init__(self, cr = 0.9, must_mutate_count=1, information_sharing=1, *pargs, **kwargs): <NEW_LINE> <INDENT> super(RandomThreeParentsComposableTechnique, self).__init__(*pargs, **kwargs) <NEW_LINE> self.cr = cr <NEW_LINE> self.must_mutate_count = must_mutate_count <NEW_LINE> self.information_sharing = information_sharing <NEW_LINE> <DEDENT> def minimum_number_of_parents(self): <NEW_LINE> <INDENT> return 4 <NEW_LINE> <DEDENT> def get_parents(self, population): <NEW_LINE> <INDENT> self.use_f = random.random() <NEW_LINE> population.sort(key=_.timestamp) <NEW_LINE> cfg = self.manipulator.copy(population[0].config) <NEW_LINE> shuffled_population = map(_.config, population[1:]) <NEW_LINE> shuffled_population += ([self.get_global_best_configuration()] * self.information_sharing) <NEW_LINE> random.shuffle(shuffled_population) <NEW_LINE> return [cfg] + shuffled_population[0:3] <NEW_LINE> <DEDENT> def update_population(self, config, population): <NEW_LINE> <INDENT> population.sort(key=_.timestamp) <NEW_LINE> if self.lt(config, population[0].config): <NEW_LINE> <INDENT> population[0].config = config <NEW_LINE> <DEDENT> population[0].touch() <NEW_LINE> return population <NEW_LINE> <DEDENT> def select_parameters(self, params): <NEW_LINE> <INDENT> random.shuffle(params) <NEW_LINE> ret_list = params[:self.must_mutate_count] <NEW_LINE> for param in params[self.must_mutate_count:]: <NEW_LINE> <INDENT> if random.random() < self.cr: <NEW_LINE> <INDENT> ret_list.append(k) <NEW_LINE> <DEDENT> <DEDENT> return ret_list <NEW_LINE> <DEDENT> def get_default_operator(self, param_type): <NEW_LINE> <INDENT> return {'op_name': 'op4_set_linear', 'args': [1.0, self.use_f, -self.use_f], 'kwargs': {}}
based on DifferentialEvolution
62599055a17c0f6771d5d63d
class BaseModel(pw.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> database = cc.model_setup()
Base class for all database models
62599055e5267d203ee6ce26
class Image(Resource): <NEW_LINE> <INDENT> def __init__(self, data, mime_type, title=None, inline=False): <NEW_LINE> <INDENT> super(Image, self).__init__(data=data, mime_type=mime_type, title=title) <NEW_LINE> self._inline = inline <NEW_LINE> <DEDENT> @property <NEW_LINE> def inline(self): <NEW_LINE> <INDENT> return self._inline <NEW_LINE> <DEDENT> def _to_html(self, context): <NEW_LINE> <INDENT> if self.title: <NEW_LINE> <INDENT> title_str = ' title="{}"'.format(escape(self.title)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> title_str = '' <NEW_LINE> <DEDENT> if not self.inline: <NEW_LINE> <INDENT> classes = ' class="block"' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> classes = '' <NEW_LINE> <DEDENT> return '<img src="{src}"{title_str}{classes} />'.format( src=escape(self.get_uri(context)), title_str=title_str, classes=classes, ) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_image(cls, image, format='PNG', title=None, inline=False): <NEW_LINE> <INDENT> if PILImage is None: <NEW_LINE> <INDENT> raise RuntimeError('`PIL` is not installed') <NEW_LINE> <DEDENT> if not isinstance(image, PILImage.Image): <NEW_LINE> <INDENT> raise TypeError('`image` must be an instance of `PIL.Image`') <NEW_LINE> <DEDENT> if format.upper() not in ('PNG', 'JPG', 'JPEG', 'BMP'): <NEW_LINE> <INDENT> raise ValueError('Image format {!r} is not allowed: only "PNG", ' '"JPG", "JPEG" or "BMP" are supported'. format(format)) <NEW_LINE> <DEDENT> with BytesIO() as f: <NEW_LINE> <INDENT> image.save(f, format=format) <NEW_LINE> f.seek(0) <NEW_LINE> data = f.read() <NEW_LINE> <DEDENT> mime_type = cls.guess_mime_type('.' + format) <NEW_LINE> return Image(data=data, mime_type=mime_type, title=title, inline=inline) <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def from_figure(cls, figure, dpi=None, tight_bbox=True, title=None, inline=False): <NEW_LINE> <INDENT> if not isinstance(figure, pyplot.Figure): <NEW_LINE> <INDENT> raise TypeError('`figure` must be an instance of ' '`matplotlib.pyplot.Figure`') <NEW_LINE> <DEDENT> kwargs = {'format': 'PNG'} <NEW_LINE> if dpi: <NEW_LINE> <INDENT> kwargs['dpi'] = dpi <NEW_LINE> <DEDENT> if tight_bbox: <NEW_LINE> <INDENT> kwargs['bbox_inches'] = 'tight' <NEW_LINE> <DEDENT> with BytesIO() as f: <NEW_LINE> <INDENT> figure.savefig(f, **kwargs) <NEW_LINE> f.seek(0) <NEW_LINE> data = f.read() <NEW_LINE> <DEDENT> return Image(data=data, mime_type='image/png', title=title, inline=inline)
Subclass of :class:`Resource`, rendered as an image.
62599055435de62698e9d33a
@six.add_metaclass(abc.ABCMeta) <NEW_LINE> class ProxyObjectBase(object): <NEW_LINE> <INDENT> @abc.abstractmethod <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> @abc.abstractmethod <NEW_LINE> def resolve(self, session): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def relative_to_timestep_id(self, existing_timestep_id): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def relative_to_timestep_cache(self, timestep_cache): <NEW_LINE> <INDENT> return self
A proxy for an object (i.e. halo, group, BH etc) in the database
625990553cc13d1c6d466c75
class Metric(models.Model): <NEW_LINE> <INDENT> name = models.CharField(max_length=50) <NEW_LINE> slug = models.SlugField(unique=True, max_length=60, db_index=True) <NEW_LINE> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Metric' <NEW_LINE> verbose_name_plural = 'Metrics' <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.id and not self.slug: <NEW_LINE> <INDENT> self.slug = slugify(self.name) <NEW_LINE> i = 0 <NEW_LINE> while True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return super(Metric, self).save(*args, **kwargs) <NEW_LINE> <DEDENT> except IntegrityError: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> self.slug = "%s_%d" % (self, i) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return super(Metric, self).save(*args, **kwargs)
The type of metric we want to store
62599055379a373c97d9a55c
class Quick: <NEW_LINE> <INDENT> def __init__(self, array): <NEW_LINE> <INDENT> self.array = array <NEW_LINE> pass <NEW_LINE> <DEDENT> def sort(self, lo=None, hi=None): <NEW_LINE> <INDENT> if lo == None: <NEW_LINE> <INDENT> lo = 0 <NEW_LINE> <DEDENT> if hi == None: <NEW_LINE> <INDENT> hi = len(self.array)-1 <NEW_LINE> <DEDENT> if lo >= hi: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> j = self.partition(lo, hi) <NEW_LINE> self.sort(lo=lo, hi=j-1) <NEW_LINE> self.sort(lo=j+1, hi=hi) <NEW_LINE> <DEDENT> def partition(self, lo, hi): <NEW_LINE> <INDENT> pivot = self.array[lo] <NEW_LINE> forward = lo + 1 <NEW_LINE> backward = hi <NEW_LINE> def exchange(i, j): <NEW_LINE> <INDENT> self.array[i], self.array[j] = self.array[j], self.array[i] <NEW_LINE> <DEDENT> while True: <NEW_LINE> <INDENT> while self.array[forward] < pivot: <NEW_LINE> <INDENT> if forward == hi: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> forward += 1 <NEW_LINE> <DEDENT> while self.array[backward] > pivot: <NEW_LINE> <INDENT> if backward == lo: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> backward -= 1 <NEW_LINE> <DEDENT> if forward >= backward: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> exchange(forward, backward) <NEW_LINE> <DEDENT> exchange(lo, backward) <NEW_LINE> return backward
Quick sorting implementation
62599055fff4ab517ebced5a
class TestValidate(unittest.TestCase): <NEW_LINE> <INDENT> def test_validate_pass(self): <NEW_LINE> <INDENT> response = {'snippet': {'channelTitle': 'paramount picture', 'title': 'Trailer'}, 'duration': 'PT04M15S'} <NEW_LINE> self.assertTrue(Validate.validate(response)) <NEW_LINE> <DEDENT> def test_validate_fail_title(self): <NEW_LINE> <INDENT> response = {'snippet': {'channelTitle': 'paramount picture', 'title': 'Deutsch Trailer'}, 'duration': 'PT04M15S'} <NEW_LINE> self.assertFalse(Validate.validate(response)) <NEW_LINE> <DEDENT> def test_validate_fail_channel(self): <NEW_LINE> <INDENT> response = {'snippet': {'channelTitle': '7even3hreetv', 'title': 'Trailer'}, 'duration': 'PT04M15S'} <NEW_LINE> self.assertFalse(Validate.validate(response)) <NEW_LINE> <DEDENT> def test_validate_fail_duration(self): <NEW_LINE> <INDENT> response = {'snippet': {'channelTitle': 'paramount picture', 'title': 'Trailer'}, 'duration': 'PT14M15S'} <NEW_LINE> self.assertFalse(Validate.validate(response)) <NEW_LINE> <DEDENT> def test_validate_fail_region(self): <NEW_LINE> <INDENT> response = {'snippet': {'channelTitle': 'paramount picture', 'title': 'Trailer'}, 'duration': 'PT14M15S', 'regionRestriction': {'blocked': ['GB']}} <NEW_LINE> self.assertFalse(Validate.validate(response)) <NEW_LINE> <DEDENT> def test_region_fail(self): <NEW_LINE> <INDENT> response = {'regionRestriction': {'blocked': ['GB']}} <NEW_LINE> self.assertFalse(Validate.region(response)) <NEW_LINE> <DEDENT> def test_region_pass(self): <NEW_LINE> <INDENT> response = {} <NEW_LINE> self.assertTrue(Validate.region(response)) <NEW_LINE> <DEDENT> def test_title_fail(self): <NEW_LINE> <INDENT> response = {'title': 'Deutsch Trailer'} <NEW_LINE> self.assertFalse(Validate.title(response)) <NEW_LINE> <DEDENT> def test_title_pass(self): <NEW_LINE> <INDENT> response = {'title': 'Trailer'} <NEW_LINE> self.assertTrue(Validate.title(response)) <NEW_LINE> <DEDENT> def test_channel_fail(self): <NEW_LINE> <INDENT> response = {'channelTitle': '7even3hreetv'} <NEW_LINE> self.assertFalse(Validate.channel_title(response)) <NEW_LINE> <DEDENT> def test_channel_pass(self): <NEW_LINE> <INDENT> response = {'channelTitle': 'paramount picture'} <NEW_LINE> self.assertTrue(Validate.channel_title(response)) <NEW_LINE> <DEDENT> def test_duration_pass(self): <NEW_LINE> <INDENT> response = {'duration': 'PT04M15S'} <NEW_LINE> self.assertTrue(Validate.duration(response)) <NEW_LINE> <DEDENT> def test_duration_fail(self): <NEW_LINE> <INDENT> response = {'duration': 'PT14M15S'} <NEW_LINE> self.assertFalse(Validate.duration(response)) <NEW_LINE> <DEDENT> def test_fix_duration(self): <NEW_LINE> <INDENT> self.assertEqual(Validate.fix_duration('PT1H02M15S'), 135) <NEW_LINE> self.assertEqual(Validate.fix_duration('PT02M'), 120)
Testing the class ValidateVideo
62599055d6c5a102081e3655
@command(user_commands) <NEW_LINE> class user_uuid2name(_init_synnefo_astakosclient, _optional_json): <NEW_LINE> <INDENT> def _run(self, uuids): <NEW_LINE> <INDENT> r = self.client.get_usernames(uuids) <NEW_LINE> self._print(r, self.print_dict) <NEW_LINE> unresolved = set(uuids).difference(r) <NEW_LINE> if unresolved: <NEW_LINE> <INDENT> self.error('Unresolved uuids: %s' % ', '.join(unresolved)) <NEW_LINE> <DEDENT> <DEDENT> def main(self, uuid, *more_uuids): <NEW_LINE> <INDENT> super(self.__class__, self)._run() <NEW_LINE> self._run(uuids=((uuid, ) + more_uuids))
Get user name(s) from uuid(s)
62599055a79ad1619776b559
class SectionCompositeImage: <NEW_LINE> <INDENT> def __init__(self, raw): <NEW_LINE> <INDENT> self.columns, = struct.unpack('>H', raw[0:2]) <NEW_LINE> self.rows, = struct.unpack('>H', raw[2:4]) <NEW_LINE> self.layout = [] <NEW_LINE> offset = 4 <NEW_LINE> for i in range(self.rows): <NEW_LINE> <INDENT> col = [] <NEW_LINE> for j in range(self.columns): <NEW_LINE> <INDENT> col.append(struct.unpack('>H', raw[offset:offset+2])[0]) <NEW_LINE> offset += 2 <NEW_LINE> <DEDENT> self.layout.append(col)
A composite image consists of a 2D array of rows and columns. The entries in the array are uid's.
625990553617ad0b5ee0767f
class MarkupTestCase(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> copy = copytext.Copy('examples/test_copy.xlsx') <NEW_LINE> self.sheet = copy['content'] <NEW_LINE> <DEDENT> def test_markup_row(self): <NEW_LINE> <INDENT> row = self.sheet['footer_title'] <NEW_LINE> self.assertTrue(isinstance(row.__html__(), string_types)) <NEW_LINE> self.assertEqual(row.__html__(), '<strong>This content goes to 12</strong>') <NEW_LINE> <DEDENT> def test_markup_cell(self): <NEW_LINE> <INDENT> cell = self.sheet['footer_title'].__str__() <NEW_LINE> print(type(cell)) <NEW_LINE> self.assertTrue(isinstance(cell, string_types)) <NEW_LINE> self.assertEqual(cell, '<strong>This content goes to 12</strong>')
Test strings get Markup'd.
62599055dc8b845886d54afc
class MemberViewSet(viewsets.ModelViewSet): <NEW_LINE> <INDENT> queryset = Member.objects.all() <NEW_LINE> serializer_class = MemberSerializer <NEW_LINE> permission_classes = [APIPermission] <NEW_LINE> def get_queryset(self): <NEW_LINE> <INDENT> allowed_query_params = [ 'id', 'account_id', 'phone_number', 'client_member_id' ] <NEW_LINE> for allowed_param in allowed_query_params: <NEW_LINE> <INDENT> query_value = self.request.query_params.get(allowed_param, None) <NEW_LINE> if query_value is not None: <NEW_LINE> <INDENT> if allowed_param == 'phone_number': <NEW_LINE> <INDENT> query_value = f'+{query_value[1:]}' <NEW_LINE> <DEDENT> filter_kwargs = { allowed_param: query_value } <NEW_LINE> return Member.objects.filter(**filter_kwargs) <NEW_LINE> <DEDENT> <DEDENT> return Member.objects.all()
A model ViewSet for viewing, creating and deleting Member objects.
6259905576d4e153a661dd17
class ContextEnd(RuntimeError): <NEW_LINE> <INDENT> pass
Context has been explicitly ended.
62599055baa26c4b54d507db
class FindDuplicateBlogPostSummaryTitlesJob(base_jobs.JobBase): <NEW_LINE> <INDENT> def run( self ) -> beam.PCollection[blog_validation_errors.DuplicateBlogTitleError]: <NEW_LINE> <INDENT> return ( self.pipeline | 'Get every Blog Summary Model' >> ( ndb_io.GetModels(blog_models.BlogPostSummaryModel.query())) | GetModelsWithDuplicatePropertyValues('title') | 'Flatten models into a list of errors' >> beam.FlatMap( lambda models: [ blog_validation_errors.DuplicateBlogTitleError(model) for model in models ]) )
Validates that all the Blog Post Summary Model have unique title.
625990554e696a045264e8be
@pwchecker('number_of_digits') <NEW_LINE> class CheckNumberOfDigits(PasswordChecker): <NEW_LINE> <INDENT> def __init__(self, digits=1): <NEW_LINE> <INDENT> self._requirement = _( "Must contain at least {digits} digits").format(digits=digits) <NEW_LINE> self.digits = digits <NEW_LINE> <DEDENT> def check_password(self, password, account=None): <NEW_LINE> <INDENT> if sum(c.isdigit() for c in password) < self.digits: <NEW_LINE> <INDENT> return [_('Password must contain at least {digits} digits').format( digits=self.digits)]
Require a minimum number of digits in the password.
62599055097d151d1a2c25a3
class Solution: <NEW_LINE> <INDENT> @timeit <NEW_LINE> def shortestPathLength(self, graph: List[List[int]]) -> int: <NEW_LINE> <INDENT> from collections import deque, defaultdict <NEW_LINE> n = len(graph) <NEW_LINE> stk = deque() <NEW_LINE> dist = defaultdict(lambda: n*n) <NEW_LINE> for i in range(n): <NEW_LINE> <INDENT> stk.append((i, 1 << i)) <NEW_LINE> dist[i, 1 << i] = 0 <NEW_LINE> <DEDENT> while stk: <NEW_LINE> <INDENT> u, rec = stk.popleft() <NEW_LINE> s = dist[u, rec] <NEW_LINE> if rec + 1 == 1 << n: <NEW_LINE> <INDENT> return s <NEW_LINE> <DEDENT> for v in graph[u]: <NEW_LINE> <INDENT> if s + 1 < dist[v, rec | (1 << v)]: <NEW_LINE> <INDENT> dist[v, rec | (1 << v)] = s + 1 <NEW_LINE> stk.append((v, rec | (1 << v))) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return -1
[847. 访问所有节点的最短路径](https://leetcode-cn.com/problems/shortest-path-visiting-all-nodes/)
6259905571ff763f4b5e8ce7
class BaseApp(GenericWSGIApplication): <NEW_LINE> <INDENT> def service(self, req): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return GenericWSGIApplication.service(self, req) <NEW_LINE> <DEDENT> except exc.HTTPException as error: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> except StandardError as error: <NEW_LINE> <INDENT> SlackAPI.error(str(error) + '\n' + traceback.format_exc()) <NEW_LINE> raise
Base class for all licensing WSGI application.
62599055d53ae8145f91999a
@functools.total_ordering <NEW_LINE> class Temp: <NEW_LINE> <INDENT> def __init__(self, temp_value: T.Any) -> None: <NEW_LINE> <INDENT> if isinstance(temp_value, Temp): <NEW_LINE> <INDENT> parsed = self.parse_temp(temp_value.value) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> parsed = self.parse_temp(temp_value) <NEW_LINE> <DEDENT> if parsed is None: <NEW_LINE> <INDENT> raise ValueError("{} is no valid temperature".format(repr(temp_value))) <NEW_LINE> <DEDENT> self.value = parsed <NEW_LINE> <DEDENT> def __add__(self, other: T.Any) -> "Temp": <NEW_LINE> <INDENT> if isinstance(other, (float, int)): <NEW_LINE> <INDENT> other = type(self)(other) <NEW_LINE> <DEDENT> elif not isinstance(other, type(self)): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> if self.is_off or other.is_off: <NEW_LINE> <INDENT> return type(self)(OFF) <NEW_LINE> <DEDENT> return type(self)(self.value + other.value) <NEW_LINE> <DEDENT> def __eq__(self, other: T.Any) -> bool: <NEW_LINE> <INDENT> if not isinstance(other, type(self)): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> return self.value == other.value <NEW_LINE> <DEDENT> def __float__(self) -> float: <NEW_LINE> <INDENT> if isinstance(self.value, float): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> raise ValueError("{} has no numeric value.".format(repr(self))) <NEW_LINE> <DEDENT> def __hash__(self) -> int: <NEW_LINE> <INDENT> return hash(str(self)) <NEW_LINE> <DEDENT> def __lt__(self, other: T.Any) -> bool: <NEW_LINE> <INDENT> if isinstance(other, (float, int)): <NEW_LINE> <INDENT> other = type(self)(other) <NEW_LINE> <DEDENT> if type(self) is not type(other): <NEW_LINE> <INDENT> return NotImplemented <NEW_LINE> <DEDENT> if not self.is_off and other.is_off: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if self.is_off and not other.is_off or self.value < other.value: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def __neg__(self) -> "Temp": <NEW_LINE> <INDENT> return type(self)(-self.value) <NEW_LINE> <DEDENT> def __repr__(self) -> str: <NEW_LINE> <INDENT> if isinstance(self.value, (float, int)): <NEW_LINE> <INDENT> return "{}°".format(self.value) <NEW_LINE> <DEDENT> return "{}".format(self.value) <NEW_LINE> <DEDENT> def __round__(self, ndigits: int = None) -> "Temp": <NEW_LINE> <INDENT> return type(self)(round(self.value, ndigits)) <NEW_LINE> <DEDENT> def __sub__(self, other: T.Any) -> "Temp": <NEW_LINE> <INDENT> return self.__add__(-other) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_off(self) -> bool: <NEW_LINE> <INDENT> return isinstance(self.value, Off) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def parse_temp(value: T.Any) -> T.Union[float, Off, None]: <NEW_LINE> <INDENT> if isinstance(value, str): <NEW_LINE> <INDENT> value = "".join(value.split()) <NEW_LINE> if value.upper() == "OFF": <NEW_LINE> <INDENT> return OFF <NEW_LINE> <DEDENT> <DEDENT> if isinstance(value, Off): <NEW_LINE> <INDENT> return OFF <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return float(value) <NEW_LINE> <DEDENT> except (ValueError, TypeError): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> <DEDENT> def serialize(self) -> str: <NEW_LINE> <INDENT> if self.is_off: <NEW_LINE> <INDENT> return "OFF" <NEW_LINE> <DEDENT> return str(self.value)
A class holding a temperature value.
6259905573bcbd0ca4bcb7c9
class WithDirective(Directive): <NEW_LINE> <INDENT> __slots__ = ['vars'] <NEW_LINE> def __init__(self, value, template, namespaces=None, lineno=-1, offset=-1): <NEW_LINE> <INDENT> Directive.__init__(self, None, template, namespaces, lineno, offset) <NEW_LINE> self.vars = [] <NEW_LINE> value = value.strip() <NEW_LINE> try: <NEW_LINE> <INDENT> ast = _parse(value, 'exec') <NEW_LINE> for node in ast.body: <NEW_LINE> <INDENT> if not isinstance(node, _ast.Assign): <NEW_LINE> <INDENT> raise TemplateSyntaxError('only assignment allowed in ' 'value of the "with" directive', template.filepath, lineno, offset) <NEW_LINE> <DEDENT> self.vars.append(([_assignment(n) for n in node.targets], Expression(node.value, template.filepath, lineno, lookup=template.lookup))) <NEW_LINE> <DEDENT> <DEDENT> except SyntaxError as err: <NEW_LINE> <INDENT> err.msg += ' in expression "%s" of "%s" directive' % (value, self.tagname) <NEW_LINE> raise TemplateSyntaxError(err, template.filepath, lineno, offset + (err.offset or 0)) <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def attach(cls, template, stream, value, namespaces, pos): <NEW_LINE> <INDENT> if type(value) is dict: <NEW_LINE> <INDENT> value = value.get('vars') <NEW_LINE> <DEDENT> return super(WithDirective, cls).attach(template, stream, value, namespaces, pos) <NEW_LINE> <DEDENT> def __call__(self, stream, directives, ctxt, **vars): <NEW_LINE> <INDENT> frame = {} <NEW_LINE> ctxt.push(frame) <NEW_LINE> for targets, expr in self.vars: <NEW_LINE> <INDENT> value = _eval_expr(expr, ctxt, vars) <NEW_LINE> for assign in targets: <NEW_LINE> <INDENT> assign(frame, value) <NEW_LINE> <DEDENT> <DEDENT> for event in _apply_directives(stream, directives, ctxt, vars): <NEW_LINE> <INDENT> yield event <NEW_LINE> <DEDENT> ctxt.pop() <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '<%s>' % (type(self).__name__)
Implementation of the ``py:with`` template directive, which allows shorthand access to variables and expressions. >>> from genshi.template import MarkupTemplate >>> tmpl = MarkupTemplate('''<div xmlns:py="http://genshi.edgewall.org/"> ... <span py:with="y=7; z=x+10">$x $y $z</span> ... </div>''') >>> print(tmpl.generate(x=42)) <div> <span>42 7 52</span> </div>
625990558da39b475be04724
class Preview(JAMediaButton): <NEW_LINE> <INDENT> def __init__(self, pagina): <NEW_LINE> <INDENT> JAMediaButton.__init__(self) <NEW_LINE> self.color = Gdk.Color(65000,65000,50000) <NEW_LINE> for child in self.get_children(): <NEW_LINE> <INDENT> self.remove(child) <NEW_LINE> child.destroy() <NEW_LINE> <DEDENT> self.pagina = pagina <NEW_LINE> self.zoom = 0.2 <NEW_LINE> self.set_zoom(self.zoom) <NEW_LINE> <DEDENT> def seleccionar(self): <NEW_LINE> <INDENT> self.estado_select = True <NEW_LINE> self.colornormal = self.color <NEW_LINE> self.colorselect = self.color <NEW_LINE> self.colorclicked = self.color <NEW_LINE> self.modify_bg(0, self.colornormal) <NEW_LINE> <DEDENT> def des_seleccionar(self): <NEW_LINE> <INDENT> self.estado_select = False <NEW_LINE> self.colornormal = G.BLANCO <NEW_LINE> self.colorselect = G.AMARILLO <NEW_LINE> self.colorclicked = self.color <NEW_LINE> self.modify_bg(0, self.colornormal) <NEW_LINE> <DEDENT> def set_zoom(self, zoom): <NEW_LINE> <INDENT> self.zoom = zoom <NEW_LINE> if self.zoom <= 0.2: self.zoom = 0.2 <NEW_LINE> w,h = self.pagina.get_size() <NEW_LINE> w,h = (int(w * self.zoom), int(h * self.zoom)) <NEW_LINE> self.set_size_request( int(w), int(h) ) <NEW_LINE> <DEDENT> def do_draw(self, context): <NEW_LINE> <INDENT> if not self.pagina: return <NEW_LINE> context.scale(self.zoom, self.zoom) <NEW_LINE> self.pagina.render(context) <NEW_LINE> <DEDENT> def set_imagen(self, archivo = None): <NEW_LINE> <INDENT> pass
Preview para las paginas del documento pdf.
62599055009cb60464d02a6e
class Peer(object): <NEW_LINE> <INDENT> __slots__ = ( 'tchannel', 'state', 'host', 'port', '_out_conns', '_in_conns', '_connecting', ) <NEW_LINE> connection_class = StreamConnection <NEW_LINE> def __init__(self, tchannel, hostport, state=None): <NEW_LINE> <INDENT> state = state or PeerHealthyState(self) <NEW_LINE> assert hostport, "hostport is required" <NEW_LINE> assert isinstance(state, PeerState), "state must be a PeerState" <NEW_LINE> self.tchannel = tchannel <NEW_LINE> self.state = state <NEW_LINE> self.host, port = hostport.rsplit(':', 1) <NEW_LINE> self.port = int(port) <NEW_LINE> self._out_conns = deque() <NEW_LINE> self._in_conns = deque() <NEW_LINE> self._connecting = None <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> conns = ( conn for conn in chain(self._out_conns, self._in_conns) if not conn.closed ) <NEW_LINE> try: <NEW_LINE> <INDENT> conn = next(conns) <NEW_LINE> <DEDENT> except StopIteration: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return gen.maybe_future(conn) <NEW_LINE> <DEDENT> if self._connecting: <NEW_LINE> <INDENT> return self._connecting <NEW_LINE> <DEDENT> conn_future = self._connecting = self.connection_class.outgoing( hostport=self.hostport, process_name=self.tchannel.process_name, serve_hostport=self.tchannel.hostport, handler=self.tchannel.receive_call, tchannel=self.tchannel, ) <NEW_LINE> def on_connect(_): <NEW_LINE> <INDENT> if not conn_future.exception(): <NEW_LINE> <INDENT> connection = conn_future.result() <NEW_LINE> self._out_conns.appendleft(connection) <NEW_LINE> <DEDENT> self._connecting = None <NEW_LINE> <DEDENT> conn_future.add_done_callback(on_connect) <NEW_LINE> return conn_future <NEW_LINE> <DEDENT> def register_incoming(self, conn): <NEW_LINE> <INDENT> assert conn, "conn is required" <NEW_LINE> self._in_conns.append(conn) <NEW_LINE> <DEDENT> @property <NEW_LINE> def hostport(self): <NEW_LINE> <INDENT> return "%s:%d" % (self.host, self.port) <NEW_LINE> <DEDENT> @property <NEW_LINE> def connections(self): <NEW_LINE> <INDENT> return list(chain(self._in_conns, self._out_conns)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def outgoing_connections(self): <NEW_LINE> <INDENT> return list(self._out_conns) <NEW_LINE> <DEDENT> @property <NEW_LINE> def incoming_connections(self): <NEW_LINE> <INDENT> return list(self._in_conns) <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_ephemeral(self): <NEW_LINE> <INDENT> return self.host == '0.0.0.0' and self.port == 0 <NEW_LINE> <DEDENT> @property <NEW_LINE> def connected(self): <NEW_LINE> <INDENT> for conn in self.connections: <NEW_LINE> <INDENT> if not conn.closed: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return False <NEW_LINE> <DEDENT> def close(self): <NEW_LINE> <INDENT> for connection in self.connections: <NEW_LINE> <INDENT> connection.close()
A Peer manages connections to or from a specific host-port.
62599055cb5e8a47e493cc23
class Preferences: <NEW_LINE> <INDENT> def __init__(self, known_roles="ON", reveal_on_death="ON", kick_on_death="OFF", know_if_saved="ON", start_night="EVEN", standard_roles="OFF"): <NEW_LINE> <INDENT> self.book = {} <NEW_LINE> self.book["known_roles"] = known_roles <NEW_LINE> self.book["reveal_on_death"] = reveal_on_death <NEW_LINE> self.book["kick_on_death"] = kick_on_death <NEW_LINE> self.book["know_if_saved"] = know_if_saved <NEW_LINE> self.book["start_night"] = start_night <NEW_LINE> self.book["standard_roles"] = standard_roles <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> result = "" <NEW_LINE> for rule,setting in self.book.items(): <NEW_LINE> <INDENT> result += rule + ": " + setting + "\n" <NEW_LINE> <DEDENT> result = result[0:-1] <NEW_LINE> return result
Holds all of the preference variables for how the game is played
6259905563b5f9789fe866aa
class Humain(object): <NEW_LINE> <INDENT> def __init__(self,x,y): <NEW_LINE> <INDENT> self.x=x <NEW_LINE> self.y=y <NEW_LINE> <DEDENT> def maj(self, field, nature_case): <NEW_LINE> <INDENT> Lx=[] <NEW_LINE> Ly=[] <NEW_LINE> L_krank=[] <NEW_LINE> min=[] <NEW_LINE> min_choix=[] <NEW_LINE> dist_min=0 <NEW_LINE> for i in [self.x-2,self.x-1,self.x,self.x+1,self.x+2]: <NEW_LINE> <INDENT> for j in [self.y-2,self.y-1,self.y,self.y+1,self.y+2]: <NEW_LINE> <INDENT> if i>=0 and i<field.shape[0] and j>=0 and j<field.shape[1] and field[i,j].nature!=0 and [i,j]!=[self.x,self.y] and field[self.x,self.y].presence==False: <NEW_LINE> <INDENT> Lx=Lx+[i] <NEW_LINE> Ly=Ly+[j] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for i in [self.x-1,self.x,self.x+1]: <NEW_LINE> <INDENT> for j in [self.y-1,self.y,self.y+1]: <NEW_LINE> <INDENT> if i>=0 and i<field.shape[0] and j>=0 and j<field.shape[1] and field[i,j].nature==0 and field[self.x,self.y].presence==False: <NEW_LINE> <INDENT> Lx=Lx+[i] <NEW_LINE> Ly=Ly+[j] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> for x in range(field.shape[0]): <NEW_LINE> <INDENT> for y in range(field.shape[1]): <NEW_LINE> <INDENT> if field[x,y].nature==nature_case: <NEW_LINE> <INDENT> L_krank=L_krank+[[x,y]] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> if L_krank==[]: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> min=L_krank[0] <NEW_LINE> dist_min=distance(L_krank[0][0],self.x,L_krank[0][1],self.y) <NEW_LINE> for i in range(len(L_krank)-1): <NEW_LINE> <INDENT> if distance(L_krank[i][0],self.x,L_krank[i][1],self.y)<dist_min: <NEW_LINE> <INDENT> min=L_krank[i] <NEW_LINE> dist_min=distance(L_krank[i][0],self.x,L_krank[i][1],self.y) <NEW_LINE> <DEDENT> <DEDENT> min_choix=[Lx[0],Ly[0]] <NEW_LINE> dist_min=distance(Lx[0],min[0],Ly[0],min[1]) <NEW_LINE> for x in Lx: <NEW_LINE> <INDENT> for y in Ly: <NEW_LINE> <INDENT> if distance(x,min[0],y,min[1])<dist_min: <NEW_LINE> <INDENT> min_choix=[x,y] <NEW_LINE> dist_min=distance(min_choix[0],min[0],min_choix[1],min[1]) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> field[self.x,self.y].presence=False <NEW_LINE> self.x=min_choix[0] <NEW_LINE> self.y=min_choix[1] <NEW_LINE> field[self.x,self.y].presence=True
superclass which contains the AI moving on the map :param x,y : position of the case where is the element
6259905524f1403a9268636b
class GetPageRevisionInfos(QueryOperation): <NEW_LINE> <INDENT> field_prefix = 'rv' <NEW_LINE> input_field = MultiParam('titles', key_prefix=False) <NEW_LINE> fields = [StaticParam('prop', 'revisions'), MultiParam('prop', DEFAULT_PROPS)] <NEW_LINE> output_type = [RevisionInfo] <NEW_LINE> examples = [OperationExample('Coffee', 10)] <NEW_LINE> def extract_results(self, query_resp): <NEW_LINE> <INDENT> ret = [] <NEW_LINE> pages = [p for p in query_resp.get('pages', {}).values() if 'missing' not in p] <NEW_LINE> for pid_dict in pages: <NEW_LINE> <INDENT> for rev in pid_dict.get('revisions', []): <NEW_LINE> <INDENT> rev_dict = dict(pid_dict) <NEW_LINE> rev_dict.update(rev) <NEW_LINE> rev_info = RevisionInfo.from_query(rev_dict, source=self.source) <NEW_LINE> ret.append(rev_info) <NEW_LINE> <DEDENT> <DEDENT> return ret
Fetch revisions for pages.
625990558e71fb1e983bd002
class MultilabelDiceMeter(Meter): <NEW_LINE> <INDENT> def __init__(self, n_labels=2, prefix="", parse_output=None, parse_target=None, cond=None): <NEW_LINE> <INDENT> super(MultilabelDiceMeter, self).__init__(name='dice', prefix=prefix, desc_name=None) <NEW_LINE> self.__parse_output = parse_output <NEW_LINE> self.__parse_target = parse_target if parse_target is not None else self.default_parse_target <NEW_LINE> self.__cond = self.default_cond if cond is None else cond <NEW_LINE> self.n_labels = n_labels <NEW_LINE> self.values = np.zeros(n_labels) <NEW_LINE> self.n_samples = 0 <NEW_LINE> <DEDENT> def on_epoch_begin(self, *args, **kwargs): <NEW_LINE> <INDENT> self.n_samples = 0 <NEW_LINE> self.values = np.zeros(self.n_labels) <NEW_LINE> <DEDENT> def on_minibatch_end(self, target, output, **kwargs): <NEW_LINE> <INDENT> with torch.no_grad(): <NEW_LINE> <INDENT> if self.__cond(target, output): <NEW_LINE> <INDENT> target = self.__parse_target(target) <NEW_LINE> output = self.__parse_output(output) <NEW_LINE> for i in range(target.size(0)): <NEW_LINE> <INDENT> t = target[i] <NEW_LINE> o = output[i] <NEW_LINE> coeffs = [] <NEW_LINE> for cls in range(self.n_labels): <NEW_LINE> <INDENT> t_cls = t[cls] <NEW_LINE> o_cls = o[cls] <NEW_LINE> val = ItemWiseBinaryJaccardDiceMeter.compute_dice(t_cls.unsqueeze(0), o_cls.unsqueeze(0)).item() <NEW_LINE> coeffs.append(val) <NEW_LINE> <DEDENT> self.n_samples += 1 <NEW_LINE> self.values += np.array(coeffs) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def current(self): <NEW_LINE> <INDENT> return (self.values / self.n_samples).mean()
Implements device-invariant image-Wise Jaccard and Dice Meter for binary multilabel sigementation problems. Parameters ---------- n_labels: int Number of outputs in the segmentation model prefix: str Prefix to be displayed in the progressbar and tensorboard parse_output: Callable Function to parse the output parse_target: Callable Function to parse the target tensor cond: Callable Condition under which the metric will be updated
625990551f037a2d8b9e5308
class FlattenDictTransformer(BaseEstimator, TransformerMixin): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def fit(self, X, y=None): <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> def transform(self, X, y=None, parent_key='', sep='_'): <NEW_LINE> <INDENT> if not X: <NEW_LINE> <INDENT> return {} <NEW_LINE> <DEDENT> flattened = [] <NEW_LINE> for k, v in X.items(): <NEW_LINE> <INDENT> new_key = parent_key + sep + k if parent_key else k <NEW_LINE> if isinstance(v, dict): <NEW_LINE> <INDENT> flattened.extend(self.transform(X=v, parent_key=new_key, sep=sep).items()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if isinstance(v, str): <NEW_LINE> <INDENT> full_key = new_key + sep + v <NEW_LINE> flattened.append((full_key, 1)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_v = 1 if v else 0 <NEW_LINE> flattened.append((new_key, new_v)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return dict(flattened)
Flatten nested dicts for use in DictVectorizer.
62599055adb09d7d5dc0baa3
class UVFitsError(Exception): <NEW_LINE> <INDENT> def __init__(self, message, file_name): <NEW_LINE> <INDENT> self.file_name = file_name <NEW_LINE> self.message = message <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return f"{self.message}: {self.file_name}"
Base class for exceptions in this module.
6259905591af0d3eaad3b360
class IpCommand(DeviceCtrl): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super().__init__(self, *args, **kwargs) <NEW_LINE> self.cmdSocket = IpCmdIf.IpCmdSocket(self, *args, **kwargs ) <NEW_LINE> self.sendCmds = { "targ": kwargs.get("target", "FF:FF:FF:FF:FF:FF"), "cmd": kwargs.get("command", "get_param"), "login-ack": kwargs.get("user", "admin"), "pwd-msg": kwargs.get("password", "admin"), "data": kwargs.get("data", None) } <NEW_LINE> ColorMsg.debug_msg("set sendCmds", debug=True) <NEW_LINE> <DEDENT> def _run(self, command="get_param", data=None, **kwargs ): <NEW_LINE> <INDENT> self.sendCmds['cmd'] = command <NEW_LINE> if data is not None: <NEW_LINE> <INDENT> self.sendCmds['data'] = data <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.sendCmds['data'] = [] <NEW_LINE> <DEDENT> localIpAddr = localIp.get_lan_ip_address("enp0s3") <NEW_LINE> self.sendCmds['targ'] = kwargs.get("target", "FF:FF:FF:FF:FF:FF") <NEW_LINE> self.sendCmds['811Ip'] = kwargs.get("811Ip", localIpAddr) <NEW_LINE> self.sendCmds['811Port'] = kwargs.get("811Port", 3840 ) <NEW_LINE> self.start_time = time.time() <NEW_LINE> msg = self.cmdSocket.send(cmd=self.sendCmds) <NEW_LINE> result = self.cmdSocket.receive() <NEW_LINE> self.timeused = (time.time() - self.start_time) * 1000 <NEW_LINE> ColorMsg.debug_msg('After %s ms,JSON result type %s: "%s"\n' %(self.timeused, type(result), result), self.debug ) <NEW_LINE> for res in result: <NEW_LINE> <INDENT> if res['login-ack'] != "OK": <NEW_LINE> <INDENT> ColorMsg.error_msg("\tIP Command '%s' failed %s" %(self.sendCmds["cmd"], res['pwd-msg'])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> None <NEW_LINE> <DEDENT> <DEDENT> return result
demonstration class only - coded for clarity, not efficiency
6259905532920d7e50bc7589
class Snippet: <NEW_LINE> <INDENT> def __init__(self, name: str, content: str): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.interpreter_type = "python" <NEW_LINE> ca = content.split('\n') <NEW_LINE> if ca[0].startswith('#!'): <NEW_LINE> <INDENT> self.interpreter_type = ca.pop(0)[2:] <NEW_LINE> <DEDENT> self.content = content <NEW_LINE> <DEDENT> def interpreter(self): <NEW_LINE> <INDENT> return create_interpreter(self.interpreter_type, self.content)
Represents a code snippet and is stringy.
62599055b57a9660fecd2fb4
class PullContainer: <NEW_LINE> <INDENT> request_id: str <NEW_LINE> received_count: int <NEW_LINE> request_count: int <NEW_LINE> status: PullProcess <NEW_LINE> last_received: datetime <NEW_LINE> messages: List[HorseMessage] <NEW_LINE> future: asyncio.Future <NEW_LINE> each_msg_func: Callable[[int, HorseMessage], None]
Response container of pull request
62599055dd821e528d6da418
class StrandCommunicationException(SLAException): <NEW_LINE> <INDENT> pass
Raise when there's an over-the-wire issue receiving a request/response from Strand
6259905582261d6c52730966
class Scheduler(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.nodes = OrderedDict() <NEW_LINE> self.ready = OrderedDict() <NEW_LINE> <DEDENT> def initialize(self): <NEW_LINE> <INDENT> visited = {} <NEW_LINE> for node in self.nodes.values(): <NEW_LINE> <INDENT> for leaf in get_leaves(node, visited): <NEW_LINE> <INDENT> leaf.cascade() <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def add_node(self, uid, data=None): <NEW_LINE> <INDENT> if uid not in self.nodes: <NEW_LINE> <INDENT> self.nodes[uid] = SchedNode(uid, self, data) <NEW_LINE> <DEDENT> return self.nodes[uid] <NEW_LINE> <DEDENT> def get_node(self, uid): <NEW_LINE> <INDENT> return self.nodes.get(uid, None) <NEW_LINE> <DEDENT> def enqueue(self, node): <NEW_LINE> <INDENT> if node.uid in self.ready: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.ready[node.uid] = node <NEW_LINE> <DEDENT> def dequeue(self, node): <NEW_LINE> <INDENT> self.ready.pop(node.uid, None) <NEW_LINE> <DEDENT> def status(self): <NEW_LINE> <INDENT> status = { 'ready': [], 'done': [], 'cancelled': [], 'waiting': [], 'submitted': [] } <NEW_LINE> for node in self.nodes.values(): <NEW_LINE> <INDENT> status[node.state].append(node) <NEW_LINE> <DEDENT> return status
the design of this scheduler is that it should be invoked iteratively to obtain a list of nodes that are "ready" to process. each node that is ready should either: - be submitted: node.submitted() - be marked as done: node.done() - be cancelled: node.cancelled()
62599055b7558d58954649c7
class SubscriberSendSMS(ProtectedView): <NEW_LINE> <INDENT> permission_required = ['send_sms', 'view_subscriber'] <NEW_LINE> def get(self, request, imsi=None): <NEW_LINE> <INDENT> user_profile = UserProfile.objects.get(user=request.user) <NEW_LINE> network = user_profile.network <NEW_LINE> try: <NEW_LINE> <INDENT> subscriber = Subscriber.objects.get(imsi=imsi, network=network) <NEW_LINE> <DEDENT> except Subscriber.DoesNotExist: <NEW_LINE> <INDENT> return HttpResponseBadRequest() <NEW_LINE> <DEDENT> initial_form_data = { 'imsi': subscriber.imsi } <NEW_LINE> context = { 'network': network, 'networks': get_objects_for_user(request.user, 'view_network', klass=Network), 'user_profile': user_profile, 'subscriber': subscriber, 'send_sms_form': dform.SubscriberSendSMSForm( initial=initial_form_data), 'network': network } <NEW_LINE> template = get_template('dashboard/subscriber_detail/send_sms.html') <NEW_LINE> html = template.render(context, request) <NEW_LINE> return HttpResponse(html) <NEW_LINE> <DEDENT> def post(self, request, imsi=None): <NEW_LINE> <INDENT> user_profile = UserProfile.objects.get(user=request.user) <NEW_LINE> network = user_profile.network <NEW_LINE> if 'message' not in request.POST: <NEW_LINE> <INDENT> return HttpResponseBadRequest() <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> sub = Subscriber.objects.get(imsi=imsi, network=network) <NEW_LINE> <DEDENT> except Subscriber.DoesNotExist: <NEW_LINE> <INDENT> return HttpResponseBadRequest() <NEW_LINE> <DEDENT> num = sub.number_set.all()[0] <NEW_LINE> params = { 'to': num.number, 'sender': '0000', 'text': request.POST['message'], 'msgid': str(uuid.uuid4()) } <NEW_LINE> url = sub.bts.inbound_url + "/endaga_sms" <NEW_LINE> tasks.async_post.delay(url, params) <NEW_LINE> params = { 'imsi': sub.imsi } <NEW_LINE> url_params = { 'sent': 'true' } <NEW_LINE> base_url = urlresolvers.reverse('subscriber-send-sms', kwargs=params) <NEW_LINE> url = '%s?%s' % (base_url, urllib.urlencode(url_params)) <NEW_LINE> return redirect(url)
Send an SMS to a single subscriber.
62599055be383301e0254d29
class RemoteServiceError(MaybeRecoverableError): <NEW_LINE> <INDENT> pass
E.g. google
625990553cc13d1c6d466c77
class Translation(object): <NEW_LINE> <INDENT> __instance = None <NEW_LINE> def __new__(cls): <NEW_LINE> <INDENT> if cls.__instance == None: <NEW_LINE> <INDENT> cls.__instance = super().__new__(cls) <NEW_LINE> <DEDENT> return cls.__instance <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def get_instance(cls): <NEW_LINE> <INDENT> inst = cls.__new__(cls) <NEW_LINE> cls.__init__(cls.__instance) <NEW_LINE> return inst <NEW_LINE> <DEDENT> def __init__(self): <NEW_LINE> <INDENT> self.config_ini=ConfigIni.getInstance() <NEW_LINE> localedir = os.path.join(os.path.abspath(os.path.dirname(__file__)), LOCALES_DIR) <NEW_LINE> self.translate = gettext.translation(PACKAGE_NAME, localedir=localedir, languages=self.__get_language_code(), fallback=True) <NEW_LINE> <DEDENT> def __get_language_code(self): <NEW_LINE> <INDENT> return [self.config_ini.getLanguage()] <NEW_LINE> <DEDENT> def _(self, text): <NEW_LINE> <INDENT> return self.translate.gettext(text)
This singleton handles the translation. The object is created by calling the get_instance() method. The language is defined in the ini file's [languages] section as "language" key The _() method is to get back the translated string. If the translation file or the translation in the file is not there then the string in the parameter will we used instead of raiseing error Using this Object directly is not necessary. There is a _() method defined out of the class which creates the instance and calls the _() method.
62599055004d5f362081fa89
class StoneCell(gtk.Button): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> gtk.Button.__init__(self, None) <NEW_LINE> self.set_size_request(40,40) <NEW_LINE> self.image = gtk.Image() <NEW_LINE> self.add(self.image) <NEW_LINE> <DEDENT> def set_value(self, value): <NEW_LINE> <INDENT> pixbuf=pixbufs[value] <NEW_LINE> pixbuf = pixbuf.scale_simple(30, 30, gtk.gdk.INTERP_BILINEAR) <NEW_LINE> self.image.set_from_pixbuf(pixbuf)
Il widget che mostra le pedine in attesa di inserimento
62599055379a373c97d9a55e
class LegacyAssessmentAdapterMixin: <NEW_LINE> <INDENT> def set_legacy_attr(self, pk): <NEW_LINE> <INDENT> self.parent = get_object_or_404(self.parent_model, pk=pk) <NEW_LINE> self.assessment = self.parent.get_assessment()
A mixin that allows API viewsets to interact with legacy methods.
62599055dc8b845886d54afe
class TestFaultCohesive(TestAbstractComponent): <NEW_LINE> <INDENT> _class = FaultCohesive
Unit testing of FaultCohesive object.
6259905516aa5153ce401a1e
class WebMusicSong(WebMusicSong): <NEW_LINE> <INDENT> def __init__(self) -> None: <NEW_LINE> <INDENT> self.copyright = False <NEW_LINE> self.duration = None <NEW_LINE> self.is_original = False <NEW_LINE> self.labels = [] <NEW_LINE> self.name = "" <NEW_LINE> self.other_sites = [] <NEW_LINE> self.poster = "" <NEW_LINE> self.pub_company = None <NEW_LINE> self.pub_date = None <NEW_LINE> self.site = "" <NEW_LINE> self.url = "" <NEW_LINE> self.plain = {} <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _build_instance(plain: dict) -> WebMusicSong: <NEW_LINE> <INDENT> __returns = WebMusicSong() <NEW_LINE> __returns.plain = plain <NEW_LINE> __returns.copyright = get_attr(plain, "copyright") <NEW_LINE> __returns.duration = get_attr(plain, "duration") <NEW_LINE> __returns.is_original = get_attr(plain, "is_original") <NEW_LINE> __returns.labels = get_attr(plain, "labels") <NEW_LINE> __returns.name = get_attr(plain, "name") <NEW_LINE> __returns.other_sites = get_attr(plain, "other_sites") <NEW_LINE> __returns.poster = get_attr(plain, "poster") <NEW_LINE> __returns.pub_company = get_attr(plain, "pub_company") <NEW_LINE> __returns.pub_date = get_attr(plain, "pub_date") <NEW_LINE> __returns.site = get_attr(plain, "site") <NEW_LINE> __returns.url = get_attr(plain, "url") <NEW_LINE> return __returns
网页搜索音乐歌曲信息搜索结果结果模型 这是一个遵照BaiduSpider网页搜索音乐歌曲信息搜索结果结果模型创建的返回模型类。 Attributes: copyright (bool): 歌曲是否有版权限制 duration (datetime.time): 歌曲时长 is_original (bool): 歌曲是否为原唱 labels (List[str]): 歌曲标签 name (str): 歌曲名称 other_sites (List[str]): 歌曲其他网站链接 poster (str): 歌曲海报图片链接 pub_company (str | None): 歌曲发布公司 pub_date (datetime.datetime | None): 歌曲发布日期 site (str): 歌曲发布站点(拼音) url (str): 歌曲链接 plain (dict): 源搜索结果字典
62599055d99f1b3c44d06bda
@singleton <NEW_LINE> class DbHelper(object): <NEW_LINE> <INDENT> TAG = "DbHelper" <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.connect() <NEW_LINE> self.logger = Logger() <NEW_LINE> <DEDENT> def connect(self): <NEW_LINE> <INDENT> self.conn = MySQLdb.connect( host=Config.HOST, port=Config.PORT, user=Config.USER, passwd=Config.PASSWORD, db=Config.DB_NAME ) <NEW_LINE> self.conn.autocommit(True) <NEW_LINE> self.cursor = self.conn.cursor() <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> self.cursor.close() <NEW_LINE> self.conn.close() <NEW_LINE> <DEDENT> def execute(self, sql): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.conn.ping() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> self.connect() <NEW_LINE> self.logger.i(self.TAG, "Mysql reconnected.") <NEW_LINE> <DEDENT> self.connect() <NEW_LINE> self.cursor.execute(sql) <NEW_LINE> <DEDENT> def getResult(self, count=0): <NEW_LINE> <INDENT> if count == 0: <NEW_LINE> <INDENT> return self.cursor.fetchall() <NEW_LINE> <DEDENT> return self.cursor.fetchmany(count)
Encapsulate basic operations of database
62599055d53ae8145f91999c
class MaxLeverage(object): <NEW_LINE> <INDENT> def start_of_simulation(self, *args): <NEW_LINE> <INDENT> self._max_leverage = 0.0 <NEW_LINE> <DEDENT> def end_of_bar(self, packet, ledger, dt, session_ix, data_portal): <NEW_LINE> <INDENT> self._max_leverage = max(self._max_leverage, ledger.account.leverage) <NEW_LINE> packet['cumulative_risk_metrics']['max_leverage'] = self._max_leverage <NEW_LINE> <DEDENT> end_of_session = end_of_bar
Tracks the maximum account leverage.
6259905521a7993f00c674a8
class KubernetesRole(Role): <NEW_LINE> <INDENT> _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'kind': {'required': True}, 'system_data': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'host_platform_type': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'kind': {'key': 'kind', 'type': 'str'}, 'system_data': {'key': 'systemData', 'type': 'SystemData'}, 'host_platform': {'key': 'properties.hostPlatform', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'host_platform_type': {'key': 'properties.hostPlatformType', 'type': 'str'}, 'kubernetes_cluster_info': {'key': 'properties.kubernetesClusterInfo', 'type': 'KubernetesClusterInfo'}, 'kubernetes_role_resources': {'key': 'properties.kubernetesRoleResources', 'type': 'KubernetesRoleResources'}, 'role_status': {'key': 'properties.roleStatus', 'type': 'str'}, } <NEW_LINE> def __init__( self, **kwargs ): <NEW_LINE> <INDENT> super(KubernetesRole, self).__init__(**kwargs) <NEW_LINE> self.kind = 'Kubernetes' <NEW_LINE> self.host_platform = kwargs.get('host_platform', None) <NEW_LINE> self.provisioning_state = None <NEW_LINE> self.host_platform_type = None <NEW_LINE> self.kubernetes_cluster_info = kwargs.get('kubernetes_cluster_info', None) <NEW_LINE> self.kubernetes_role_resources = kwargs.get('kubernetes_role_resources', None) <NEW_LINE> self.role_status = kwargs.get('role_status', None)
Kubernetes role. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: The path ID that uniquely identifies the object. :vartype id: str :ivar name: The object name. :vartype name: str :ivar type: The hierarchical type of the object. :vartype type: str :param kind: Required. Role type.Constant filled by server. Possible values include: "IOT", "ASA", "Functions", "Cognitive", "MEC", "CloudEdgeManagement", "Kubernetes". :type kind: str or ~azure.mgmt.databoxedge.v2020_09_01_preview.models.RoleTypes :ivar system_data: Role configured on ASE resource. :vartype system_data: ~azure.mgmt.databoxedge.v2020_09_01_preview.models.SystemData :param host_platform: Host OS supported by the Kubernetes role. Possible values include: "Windows", "Linux". :type host_platform: str or ~azure.mgmt.databoxedge.v2020_09_01_preview.models.PlatformType :ivar provisioning_state: State of Kubernetes deployment. Possible values include: "Invalid", "Creating", "Created", "Updating", "Reconfiguring", "Failed", "Deleting". :vartype provisioning_state: str or ~azure.mgmt.databoxedge.v2020_09_01_preview.models.KubernetesState :ivar host_platform_type: Platform where the runtime is hosted. Possible values include: "KubernetesCluster", "LinuxVM". :vartype host_platform_type: str or ~azure.mgmt.databoxedge.v2020_09_01_preview.models.HostPlatformType :param kubernetes_cluster_info: Kubernetes cluster configuration. :type kubernetes_cluster_info: ~azure.mgmt.databoxedge.v2020_09_01_preview.models.KubernetesClusterInfo :param kubernetes_role_resources: Kubernetes role resources. :type kubernetes_role_resources: ~azure.mgmt.databoxedge.v2020_09_01_preview.models.KubernetesRoleResources :param role_status: Role status. Possible values include: "Enabled", "Disabled". :type role_status: str or ~azure.mgmt.databoxedge.v2020_09_01_preview.models.RoleStatus
6259905563b5f9789fe866ac
class ServiceSerializer(BaseSerializer, serializers.ServiceSerializer, RelatedSerializerMixin): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> model = Service <NEW_LINE> fields = ('name', 'db_version', 'description', 'short_description', 'runner', 'srv_run_params', 'submissions', 'service_outputs', 'exit_codes') <NEW_LINE> <DEDENT> db_version = rest_serializer.SerializerMethodField() <NEW_LINE> submissions = ServiceSubmissionSerializer(many=True, required=False) <NEW_LINE> exit_codes = ExitCodeSerializer(many=True, required=False) <NEW_LINE> service_outputs = ServiceOutputSerializer(many=True, required=False) <NEW_LINE> runner = RunnerSerializer(many=False, required=False) <NEW_LINE> srv_run_params = ServiceRunnerParamSerializer(many=True, required=False) <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.skip_runner = kwargs.pop('skip_run', False) <NEW_LINE> super(ServiceSerializer, self).__init__(*args, **kwargs) <NEW_LINE> <DEDENT> @transaction.atomic <NEW_LINE> def create(self, validated_data): <NEW_LINE> <INDENT> submissions = validated_data.pop('submissions', []) <NEW_LINE> outputs = validated_data.pop('service_outputs', []) <NEW_LINE> ext_codes = validated_data.pop('exit_codes', []) <NEW_LINE> runner = validated_data.pop('runner', []) <NEW_LINE> srv_run_params = validated_data.pop('srv_run_params', []) <NEW_LINE> if not self.skip_runner: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> run_on = Runner.objects.filter(clazz=runner['clazz']).first() <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> srv = RunnerSerializer(data=runner) <NEW_LINE> if srv.is_valid(): <NEW_LINE> <INDENT> run_on = srv.save() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> run_on = None <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> run_on = None <NEW_LINE> <DEDENT> srv_object = Service.objects.create(**validated_data) <NEW_LINE> srv_object.runner = run_on <NEW_LINE> srv_object.save() <NEW_LINE> if not self.skip_runner: <NEW_LINE> <INDENT> s_run_p = ServiceRunnerParamSerializer(data=srv_run_params, many=True) <NEW_LINE> if s_run_p.is_valid(): <NEW_LINE> <INDENT> s_run_p.save(service=srv_object) <NEW_LINE> <DEDENT> <DEDENT> srv_object.submissions = self.create_related(foreign={'service': srv_object}, serializer=ServiceSubmissionSerializer, datas=submissions) <NEW_LINE> srv_object.service_outputs = self.create_related(foreign={'service': srv_object}, serializer=ServiceOutputSerializer, datas=outputs) <NEW_LINE> srv_object.exit_codes = self.create_related(foreign={'service': srv_object}, serializer=ExitCodeSerializer, datas=ext_codes) <NEW_LINE> return srv_object <NEW_LINE> <DEDENT> def get_db_version(self, obj): <NEW_LINE> <INDENT> from waves.wcore.settings import waves_settings <NEW_LINE> return waves_settings.DB_VERSION
Service export / import
6259905524f1403a9268636c