code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def start_auto_awsume(args, app, profiles, credentials_file_path, user_session, role_session): <NEW_LINE> <INDENT> LOG.info('starting auto refresher') <NEW_LINE> profile = profiles[args.target_profile_name] <NEW_LINE> if args.session_name: <NEW_LINE> <INDENT> role_session_name = args.session_name <NEW_LINE> LOG.debug('...
Start autoawsume. Parameters ---------- - args - the commandline args - app - the AWSume app object - profiles - the collected aws profiles - credentials_file_path - the path to the credentials file - user_session - the session credentials from the get-session-token api call - role_session - the session credentials fr...
625941f39f2886367277ae8e
def create_words_set(self): <NEW_LINE> <INDENT> sentences = " ".join(self.sent_list) <NEW_LINE> words_sequence = text_to_word_sequence(text=sentences, filters='\n', split=" ") <NEW_LINE> self.words_set = set(sorted(words_sequence)) <NEW_LINE> return self.words_set
単語のセットを返す。言語モデルなら機能語を加えて返す
625941f366673b3332b92697
def test_trim_raises_ValueError_for_jobs_on_run_list(self): <NEW_LINE> <INDENT> self.session.update_desired_job_list([self.job_a]) <NEW_LINE> with self.assertRaises(ValueError) as boom: <NEW_LINE> <INDENT> self.session.trim_job_list(JobIdQualifier("a")) <NEW_LINE> self.assertEqual( str(boom.exception), "cannot remove j...
verify that trim_job_list() raises ValueError when any of the jobs marked for removal is in the run_list.
625941f324f1403a92601167
def serialize(self, buff): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> length = len(self.translation) <NEW_LINE> buff.write(_struct_I.pack(length)) <NEW_LINE> pattern = '<%sf'%length <NEW_LINE> buff.write(struct.pack(pattern, *self.translation)) <NEW_LINE> length = len(self.rotation) <NEW_LINE> buff.write(_struct_I.pa...
serialize message into buffer :param buff: buffer, ``StringIO``
625941f31f5feb6acb0c514f
def take_picture(self): <NEW_LINE> <INDENT> self._set_property(Network.CAMERA, 100)
Takes a picture on MODI Play :return: None
625941f31f037a2d8b946802
def test_offline_menu(self): <NEW_LINE> <INDENT> addon.run(['plugin://plugin.video.vrt.nu/offline', '0', '']) <NEW_LINE> self.assertEqual(plugin.url_for(addon.offline), 'plugin://plugin.video.vrt.nu/offline')
Soon offline menu: /offline/<page>
625941f3287bf620b61d4066
def _known_content_types(self): <NEW_LINE> <INDENT> types = self._portal_types_types() <NEW_LINE> found_objects = self._object_types_per_folder() <NEW_LINE> all_types = set() <NEW_LINE> for folder in found_objects: <NEW_LINE> <INDENT> content_types = found_objects[folder].keys() <NEW_LINE> all_types.update(set(content_...
Return all content types: based on the portal types tool and the actual content.
625941f37047854f462a1a09
def test_2AAD_frames1to3_second_frame(self): <NEW_LINE> <INDENT> frame = 2 <NEW_LINE> self.o.read_pdb(DataPath+'2AAD-1to3.pdb') <NEW_LINE> result = self.o.write_pdb(moduleDataPath+'test-results/2AAD-1to3-2-writepdb-test.pdb',frame,'w') <NEW_LINE> self.assertEqual(result,1) <NEW_LINE> os.remove(moduleDataPath+'test-resu...
test the second frame a pdb file with 2 amino acids and 3 frames
625941f3a8370b7717052ea4
def recreate(self): <NEW_LINE> <INDENT> ensure_root() <NEW_LINE> if not self._load_existent(): <NEW_LINE> <INDENT> print_error('Can not recreate "{}": The image does not exist.'.format(self.name)) <NEW_LINE> return False <NEW_LINE> <DEDENT> config_fname = self.get_config_location() <NEW_LINE> if not os.path.isfile(conf...
Recreate a container base image
625941f3d99f1b3c44c67b89
def deserialize(self, str): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if self.header is None: <NEW_LINE> <INDENT> self.header = std_msgs.msg.Header() <NEW_LINE> <DEDENT> if self.status is None: <NEW_LINE> <INDENT> self.status = actionlib_msgs.msg.GoalStatus() <NEW_LINE> <DEDENT> if self.result is None: <NEW_LINE> <I...
unpack serialized message in str into this message instance :param str: byte array of serialized message, ``str``
625941f3d53ae8145f87a86a
def test_collection_bytes_unsupported(self): <NEW_LINE> <INDENT> manager = SharedMemoryManager() <NEW_LINE> content = [b'x01', b'x02'] <NEW_LINE> datum = bind_meta.Datum(type='collection_bytes', value=content) <NEW_LINE> is_supported = manager.is_supported(datum) <NEW_LINE> self.assertFalse(is_supported)
Verify that the given input is unsupported by SharedMemoryManager. This input is collection_bytes.
625941f37cff6e4e81117f8c
def calc_gw_flux_at_node(self): <NEW_LINE> <INDENT> gw = ( self._grid.at_link["groundwater__specific_discharge"][ self._grid.links_at_node ] * self._grid.link_dirs_at_node ) <NEW_LINE> gw_out = -np.sum(gw * (gw < 0), axis=1) <NEW_LINE> return gw_out
Calculate the sum of the groundwater flux leaving a node. (m2/s)
625941f33317a56b8693a24f
def run_query(self, config_entity, **kwargs): <NEW_LINE> <INDENT> full_query = self._add_to_query(**kwargs) if len(kwargs.keys()) > 0 else None <NEW_LINE> return self.parse_query(config_entity, full_query)
Prepends the given or default group_by (if any) and/or optional values to the query, runs the query, and returns results TODO Since ordering of query parts makes a big difference, we might have to let kwargs specify positions in the query :param kwargs['group_by']: use this group_by or the else self.group_by or...
625941f3091ae3566866755b
def movingaverage(interval, window_size): <NEW_LINE> <INDENT> window = np.ones(int(window_size)) / float(window_size) <NEW_LINE> return np.convolve(interval, window, 'same')
Smooths a list with the moving average method. Args: interval: List to be smoothed window_size: Size of convolution window Returns: Smoothed list
625941f39f2886367277ae8f
def mirror_peaks(peaklist1, peaklist2, ax=None, normalize=True, kwargs1=None, kwargs2=None, **kwargs): <NEW_LINE> <INDENT> pretty = kwargs.pop("pretty", True) <NEW_LINE> if kwargs1 is None: <NEW_LINE> <INDENT> kwargs1 = {} <NEW_LINE> <DEDENT> if kwargs2 is None: <NEW_LINE> <INDENT> kwargs2 = {} <NEW_LINE> <DEDENT> if a...
Create a mirror plot of two peak lists. Plot one peak list upside-down below another peak list. Commonly used to compare/contrast two two peak lists visually. Parameters ---------- peaklist1 : :class:`~.Iterable` The peak list to plot right-side up. peaklist2 : :class:`~.Iterable` The peak list to plot upside...
625941f3e76e3b2f99f3ae08
def test_invite_existing(self): <NEW_LINE> <INDENT> self.project.add_user(self.user, "@Administration") <NEW_LINE> response = self.client.post( reverse("invite-user", kwargs=self.kw_project), { "email": self.user.email, "username": self.user.username, "full_name": "name", }, follow=True, ) <NEW_LINE> self.assertContain...
Test inviting existing user.
625941f321a7993f00bc8302
def _devpath(dev): <NEW_LINE> <INDENT> return os.path.join('/dev', _devbase(dev))
Return /dev name of just about any dev :return: /dev/devicename
625941f321a7993f00bc8303
def __init__(self, *args): <NEW_LINE> <INDENT> this = _Client.new_Notification(*args) <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this
__init__(self) -> Notification __init__(self, BaseObject o) -> Notification __init__(self, int t) -> Notification __init__(self, int t, BaseObject o) -> Notification
625941f32c8b7c6e89b35dc2
def data_received_peer(self, peer, msg): <NEW_LINE> <INDENT> logger.debug('Received %s from %s', msg['type'], peer) <NEW_LINE> if self.persist['currentTerm'] < msg['term']: <NEW_LINE> <INDENT> self.persist['currentTerm'] = msg['term'] <NEW_LINE> if not type(self) is Follower: <NEW_LINE> <INDENT> logger.info('Remote ter...
Receive peer messages from orchestrator and pass them to the appropriate method.
625941f3b830903b967e9f0b
def _check_values(self, name, values): <NEW_LINE> <INDENT> if isinstance(values, (float, int)): <NEW_LINE> <INDENT> values = [values] * len(self.links) <NEW_LINE> <DEDENT> elif not isinstance(values, (list, tuple, np.ndarray)): <NEW_LINE> <INDENT> raise TypeError("Expecting the given '" + name + "' to be a list/tuple/n...
Check the given values to be set.
625941f31f037a2d8b946803
def __init__(self, name="", uri=None, **kwargs): <NEW_LINE> <INDENT> Loggable.__init__(self) <NEW_LINE> self.log("name:%s, uri:%s", name, uri) <NEW_LINE> self.name = name <NEW_LINE> self.author = "" <NEW_LINE> self.year = "" <NEW_LINE> self.settings = None <NEW_LINE> self.description = "" <NEW_LINE> self.uri = uri <NEW...
@param name: the name of the project @param uri: the uri of the project
625941f396565a6dacc8fcd0
def install(self, repo): <NEW_LINE> <INDENT> repos = self._search(repo) <NEW_LINE> if repo in repos: <NEW_LINE> <INDENT> self._print_headers() <NEW_LINE> self._add_app(repo) <NEW_LINE> self._check(repo) <NEW_LINE> self._update(repo) <NEW_LINE> self._print_footer() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> STD.messa...
Install an application from Github repository name
625941f38da39b475bd65583
def prepare_graph(g, req): <NEW_LINE> <INDENT> log.debug('Copying graph') <NEW_LINE> graph = g.copy() <NEW_LINE> for n in graph.nodes(): <NEW_LINE> <INDENT> graph.node[n]['data'] = {key: Node(name=n) for key in req} <NEW_LINE> <DEDENT> return graph
Copy the given graph and preset nodes attribute :type g: DiGraph :return: DiGraph :type req: {dest: fwd_req} :param req: The requirements for that graph
625941f3f548e778e58cdb87
def _getProfileFromUser(self): <NEW_LINE> <INDENT> p_key = self._getUserProfileKey() <NEW_LINE> profile = p_key.get() <NEW_LINE> if not profile: <NEW_LINE> <INDENT> user = endpoints.get_current_user() <NEW_LINE> profile = Profile( key=p_key, displayName=user.nickname(), mainEmail=user.email(), teeShirtSize=str(TeeShirt...
Return user Profile from datastore, creating new one if non-existent.
625941f45fc7496912cc3f84
def sync(self): <NEW_LINE> <INDENT> now = time.time() <NEW_LINE> if self.delay > now-self.last: <NEW_LINE> <INDENT> time.sleep(self.delay - (now-self.last)) <NEW_LINE> <DEDENT> self.last = max(now, self.last+self.delay)
Wait if required.
625941f471ff763f4b549c9e
def handle(self: AbstractHandler, request: Request) -> None: <NEW_LINE> <INDENT> result = self.check_request(request) <NEW_LINE> if not result and self._next_handler: <NEW_LINE> <INDENT> self._next_handler.handle(request)
Метод обработки запроса.
625941f4e1aae11d1e74a2c4
def max_point(self): <NEW_LINE> <INDENT> x = self.p1.x <NEW_LINE> if self.p2.x > x: <NEW_LINE> <INDENT> x = self.p2.x <NEW_LINE> <DEDENT> y = self.p1.y <NEW_LINE> if self.p2.y > y: <NEW_LINE> <INDENT> y = self.p2.y <NEW_LINE> <DEDENT> return Point(x, y)
Return the max point of the shape
625941f4f8510a7c17cf9d08
def __call__(self, text): <NEW_LINE> <INDENT> index = 0 <NEW_LINE> new_list = [] <NEW_LINE> while index < len(text): <NEW_LINE> <INDENT> index1, match = self._find_start(text, index) <NEW_LINE> if index1 >= 0: <NEW_LINE> <INDENT> for i in range(index, index1): <NEW_LINE> <INDENT> new_list.extend(text[i]) <NEW_LINE> <DE...
Walk through the text performing the replaces required. :param text: the text to work on >>> a = StreamEditor() >>> a.substitute('does not match',to='new') >>> a('turn old to new') 'turn old to new' >>> a = StreamEditor() >>> a.substitute('old',to='new') >>> a('turn old to new') 'turn new to new' >>> a = StreamEdi...
625941f407f4c71912b11a8c
def formatTime(self, record, datefmt=None): <NEW_LINE> <INDENT> ct = self.converter(record.created) <NEW_LINE> if datefmt: <NEW_LINE> <INDENT> ct = self.converter(record.created) <NEW_LINE> s = ct.strftime(datefmt) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> t = ct.strftime(self.default_time_format) <NEW_LINE> s = se...
Return the creation time of the specified LogRecord as formatted text. This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: if datefmt (a string)...
625941f4f7d966606f6aa613
def output(self): <NEW_LINE> <INDENT> if self._into_file: <NEW_LINE> <INDENT> self._into_file.seek(0) <NEW_LINE> return bytes(self._into_file.read()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return bytes()
Get all output from the redirected-to file if it exists.
625941f4d18da76e23532ae5
def forget_fact(term): <NEW_LINE> <INDENT> logger.info('Removing fact %s', term) <NEW_LINE> db.facts.remove({'term': term_regex(term)}) <NEW_LINE> return random.choice(ACKS)
Forgets a fact by removing it from the database
625941f4ff9c53063f47c7f7
def test_transaction_with_reconnect(self): <NEW_LINE> <INDENT> self.kill_connections(self.db) <NEW_LINE> self.db.transaction(("INSERT INTO unit_test_int_table VALUES (1)",), callback=self.stop_callback) <NEW_LINE> self.wait_for_result() <NEW_LINE> self.db.execute("SELECT COUNT(1) FROM unit_test_int_table", callback=sel...
Test whether transaction works after reconnect
625941f456ac1b37e62647ca
def is_single_line(self): <NEW_LINE> <INDENT> state_set = self.get_state_set() <NEW_LINE> return state_set and state_set.contains(Atspi.StateType.SINGLE_LINE)
Is active accessible a single line text entry?
625941f4507cdc57c63072f1
def update_coverage_set(db, coverage_sel, update_set): <NEW_LINE> <INDENT> if not db: <NEW_LINE> <INDENT> return (False, 'inner application error') <NEW_LINE> <DEDENT> coll = db[collection] <NEW_LINE> doc = coll.find_one(coverage_sel) <NEW_LINE> if not doc: <NEW_LINE> <INDENT> return (False, 'no such coverage') <NEW_LI...
updates data of a single coverage_id
625941f45166f23b2e1a5760
def msgID_797_DomesticHotWoter(self, msgtuple, buffer, length): <NEW_LINE> <INDENT> nickname = "WW" <NEW_LINE> (msgid, offset) = msgtuple <NEW_LINE> temptext = "{0:4}_{1:<2}:{2:3}:".format(msgid, offset, nickname) <NEW_LINE> for x in range(0, length): <NEW_LINE> <INDENT> temptext += format(buffer[x], "02x") + " " <NEW_...
decoding of msgID:797 -> Domestic Hot Water(DHW) message.
625941f430bbd722463cc3d1
def _ldap_connection(self, base, server=None, scheme=None): <NEW_LINE> <INDENT> naming_context = self._resolve_naming_context(base) <NEW_LINE> scheme = self._fixup_scheme(scheme) <NEW_LINE> if self.m_connections is None: <NEW_LINE> <INDENT> self.m_connections = {} <NEW_LINE> <DEDENT> key = (naming_context, server, sche...
Return the (cached) LDAP connection for a naming naming_context.
625941f4f8510a7c17cf9d09
def removeLeafNodes(self, root, target): <NEW_LINE> <INDENT> if not root: return None <NEW_LINE> if not root.left and not root.right: <NEW_LINE> <INDENT> if root.val == target: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return root <NEW_LINE> <DEDENT> <DEDENT> root.left = self.removeL...
:type root: TreeNode :type target: int :rtype: TreeNode
625941f4ab23a570cc25078f
def _combine_text_nodes(self, nodes, _string_types=string_types): <NEW_LINE> <INDENT> if not nodes: <NEW_LINE> <INDENT> return [] <NEW_LINE> <DEDENT> nodes = nodes[:] <NEW_LINE> out_nodes = [nodes.pop(0)] <NEW_LINE> append = out_nodes.append <NEW_LINE> for node in nodes: <NEW_LINE> <INDENT> if isinstance(node, _string_...
Combines consecutive text nodes in to a single text node
625941f491af0d3eaac9c025
def imshow(self, mask=None, new_figure=True, title=None, xlabel='', ylabel='', interpolation='nearest', colorbar=True, percentile=0, **keywords): <NEW_LINE> <INDENT> if np.iscomplexobj(self): <NEW_LINE> <INDENT> data = abs(self.magnitude) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = self.magnitude.copy() <NEW_L...
A graphical display method specialising matplotlib's imshow. mask : array-like, optional Data mask. True means masked. new_figure : boolean, optional If True, a new figure if created. Default is True. title : str, optional The plot title. xlabel : str, optional Plot X label. ylabel : str, optional Pl...
625941f4167d2b6e3121919c
def process(self): <NEW_LINE> <INDENT> return self.get_value('process')
return process name
625941f48e05c05ec3eea981
def get(self, id_or_uri): <NEW_LINE> <INDENT> return self._client.get(id_or_uri)
Gets the connection template with the specified ID or URI. Args: id_or_uri: ID or URI of connection template. Returns: dict: the connection template
625941f4cb5e8a47e48b80a7
@main.route('/draft-services/copy-from/<string:service_id>', methods=['PUT']) <NEW_LINE> def copy_draft_service_from_existing_service(service_id): <NEW_LINE> <INDENT> is_valid_service_id_or_400(service_id) <NEW_LINE> updater_json = validate_and_return_updater_request() <NEW_LINE> service = Service.query.filter( Service...
Create a draft service from an existing service :param service_id: :return:
625941f4462c4b4f79d1dcd7
def GetAlpha(self): <NEW_LINE> <INDENT> return _itkHessianToObjectnessMeasureImageFilterPython.itkHessianToObjectnessMeasureImageFilterISSRTD22IUL2_GetAlpha(self)
GetAlpha(self) -> double
625941f4099cdd3c635f125f
def solve(a, b, N): <NEW_LINE> <INDENT> sum_ = 0 <NEW_LINE> n = (N-1) // a + 1; <NEW_LINE> sum_ += (n * (n-1)*a) // 2; <NEW_LINE> n = (N-1) // b + 1; <NEW_LINE> sum_ += (n * (n-1)*b) // 2; <NEW_LINE> c = a * b // gcd(a, b) <NEW_LINE> n = (N-1) // c + 1; <NEW_LINE> sum_ -= (n * (n-1)*c) // 2; <NEW_LINE> return sum_
Returns sum of multiples of a *or* b *below* N Uses formular for sum of an AP.
625941f494891a1f4081c0b4
def threeSum(self, nums, target): <NEW_LINE> <INDENT> result = [] <NEW_LINE> if nums == [] or len(nums) < 3: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> solved = [] <NEW_LINE> for i in range(len(nums)): <NEW_LINE> <INDENT> a = nums[i] <NEW_LINE> if a in solved: <NEW_LINE> <INDENT> continue <N...
:type nums: List[int] :rtype: List[List[int]]
625941f4d8ef3951e3243b45
def move_up(self): <NEW_LINE> <INDENT> index = self.listbox.index <NEW_LINE> if index != 0: <NEW_LINE> <INDENT> self.data_list[index - 1], self.data_list[index] = self.data_list[index], self.data_list[index - 1] <NEW_LINE> self.listbox.index = index - 1
上移一项
625941f4a8ecb033257d36d2
def test_06(self): <NEW_LINE> <INDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> Rectangle.save_to_file() <NEW_LINE> <DEDENT> with self.assertRaises(TypeError): <NEW_LINE> <INDENT> Square.save_to_file([], 1)
Checks exception raises.
625941f40383005118ecfbe8
def measure_score(path: str, code_a: Union[str, bytes], code_b: Union[str, bytes], return_seq: bool = True) -> Union[List[float], float]: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> code_a = code_a.encode("utf-8") <NEW_LINE> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> try: <NEW_LINE> <...
Measure similarity score between 2 pieces of code. Algorithm 1) tokenize -> merge_indentation -> insert_noop 2) iterate over 2 list of tokens and measure common ratio between them (if only one of them is IndentationNode - ratio is 0, if both - measure score using `SequenceMatcher.ratio`) TLDR: The more - the bette...
625941f43c8af77a43ae3daf
def genre_child(genre_id=None): <NEW_LINE> <INDENT> url = API_ENPOINT + 'genre/child' <NEW_LINE> if genre_id is not None: <NEW_LINE> <INDENT> return requests.get(url, params={ 'api_key': API_KEY, 'session_key': SESSION_KEY, 'genre_id': genre_id }).json() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return { 'total': 7...
Return all genre's children of specify genre. If genre_id is not specified, this will return root genres.
625941f49c8ee82313fbbd7f
def create_graph(): <NEW_LINE> <INDENT> graph = Graph() <NEW_LINE> for line in get_all(): <NEW_LINE> <INDENT> start = line['start'] <NEW_LINE> finish = line['finish'] <NEW_LINE> distance = line['distance'] <NEW_LINE> graph.add_node(start) <NEW_LINE> graph.add_node(finish) <NEW_LINE> graph.add_edge(start, finish, distan...
:rtype: Graph
625941f423e79379d52eeb63
def reconnect(self): <NEW_LINE> <INDENT> self.connected = True <NEW_LINE> self._create_subsurface() <NEW_LINE> if self not in self.master.children: <NEW_LINE> <INDENT> self.master.children.append(self) <NEW_LINE> <DEDENT> for child in self.children: <NEW_LINE> <INDENT> child.reconnect() <NEW_LINE> <DEDENT> self.appear(...
Used to actualise the connections of subsurfaces (makes self.surface to be a subsurface of self.master.surface if possible). Can be called by master. Public.
625941f4046cf37aa974d349
def __filter_query(self) -> str: <NEW_LINE> <INDENT> filter_query = 'WHERE %s' <NEW_LINE> bind_values = {} <NEW_LINE> if not self.__filters: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> for filter in self.__filters: <NEW_LINE> <INDENT> bind = { 'name': Security.random_string(5), 'value': filter['value']} <NEW_LI...
Generate a WHERE/AND string for SQL
625941f429b78933be1e5cac
def __init__(self, p, degree): <NEW_LINE> <INDENT> self.p = p <NEW_LINE> methods = {90: Image.ROTATE_90, 180: Image.ROTATE_180, 270: Image.ROTATE_270} <NEW_LINE> if degree not in methods.keys(): <NEW_LINE> <INDENT> raise NotImplementedError("We only support multiple of 90 degree rotations for now") <NEW_LINE> <DEDENT> ...
Creates an `JointRandomRotation` instance. Args: p: the probability for rotating.
625941f48a349b6b435e877a
def test_step_context_when_do_not_fail(ctx): <NEW_LINE> <INDENT> observer = ctx.observer(EventType.STEP_ENDED) <NEW_LINE> invoked = False <NEW_LINE> with pytest.raises(ZeroDivisionError) as exc_info: <NEW_LINE> <INDENT> with ctx.step(SampleStep).do_not_fail.do(5, 0, operation=lambda x, y: x / y): <NEW_LINE> <INDENT> in...
Step context not called when exceptions are raised even if do_not_fail is enabled
625941f432920d7e50b287dd
def draw_labeled_bboxes(img, labels, color=(0, 0, 255)): <NEW_LINE> <INDENT> colors = [(0, 255, 0), (255, 0, 0)] <NEW_LINE> for color, label_collection in zip(colors, labels): <NEW_LINE> <INDENT> for car_number in range(1, label_collection[1] + 1): <NEW_LINE> <INDENT> nonzero = (label_collection[0] == car_number).nonze...
Draw boxes for two different sets of labels (high confidence and low confidence) with different color.
625941f415fb5d323cde1121
def task_status_stats(self): <NEW_LINE> <INDENT> waiting_tasks = 0 <NEW_LINE> ready_to_run_tasks = 0 <NEW_LINE> blocked_tasks = 0 <NEW_LINE> completed_tasks = 0 <NEW_LINE> for analysis in self: <NEW_LINE> <INDENT> if analysis.update_analysis: <NEW_LINE> <INDENT> waiting_tasks += 1 <NEW_LINE> if len(analysis.check_ready...
Compute the number of tasks that are complete, ready to run, and waiting on dependencies :return: Tuple of ints with: * number of completed tasks * total number of tasks waiting to be executed * total number of waiting tasks that are ready to be run * total number of waiting tasks that are blocked, e.g....
625941f4d486a94d0b98e74f
def date_to_str(date): <NEW_LINE> <INDENT> return datetime.datetime.strftime(date, DATE_FORMAT) if date else None
Converts a datetime value to a string. :param date: the datetime value to convert.
625941f47047854f462a1a0a
def apply_move(self, tree): <NEW_LINE> <INDENT> pass
Applies itself to the given state and returns the resulting state Move is expected to be valid in game :tree: GameTree Origin GameTree :returns: State State with this action applied
625941f4956e5f7376d71473
def get_active_sessions(self): <NEW_LINE> <INDENT> for last_timestamp, events in self.recently_active: <NEW_LINE> <INDENT> yield Session(events[-1].user, unpack_events(events))
Retrieves the active, unexpired sessions. :Returns: A generator of :class:`~mw.lib.sessions.Session`
625941f4bd1bec0571d90c37
def sigmoid_backward(dA, cache): <NEW_LINE> <INDENT> Z = cache <NEW_LINE> s = 1 / (1 + np.exp(-Z)) <NEW_LINE> dZ = dA * s * (1-s) <NEW_LINE> assert(Z.shape == dZ.shape) <NEW_LINE> return dZ
Implement the backward propagation for a single SIGMOID unit. Arguments: dA -- post-activation gradient, of any shape cache -- 'Z' where we store for computing backward propagation efficiently Returns: dZ -- Gradient of the cost with respect to Z
625941f46fece00bbac2dd4e
def food_add_favorite(self, food_id, serving_id=None, number_of_units=None): <NEW_LINE> <INDENT> params = {'method': 'food.add_favorite', 'format': 'json', 'food_id': food_id} <NEW_LINE> if serving_id and number_of_units: <NEW_LINE> <INDENT> params['serving_id'] = serving_id <NEW_LINE> params['number_of_units'] = numbe...
Add a food to a user's favorite according to the parameters specified. :param food_id: The ID of the favorite food to add. :type food_id: str :param serving_id: Only required if number_of_units is present. This is the ID of the favorite serving. :type serving_id: str :param number_of_units: Only required if serving_id...
625941f4b5575c28eb68e60e
def check_dose_range_sanity(dose_list): <NEW_LINE> <INDENT> low_dose = 10000 <NEW_LINE> high_dose = 0 <NEW_LINE> constrained_list = [] <NEW_LINE> for dose in dose_list: <NEW_LINE> <INDENT> if low_dose > dose: <NEW_LINE> <INDENT> low_dose = dose <NEW_LINE> <DEDENT> if high_dose < dose: <NEW_LINE> <INDENT> high_dose = do...
Method determines whether or not any of the dosages passed in the dose_list parameter are an order of magnitude greater than any of the others; if so, they are chopped at 10x the lowest dosage. TODO: Check to see if this would be better implemented as the method below :param dose_list: :return:
625941f450812a4eaa59c923
def _an_element_impl(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self(self._formal_sum_module([ (self.base_ring().random_element(), self.group().random_element()), (self.base_ring().random_element(), self.group().random_element()), ])) <NEW_LINE> <DEDENT> except StandardError: <NEW_LINE> <INDENT> return ...
Return an element of self. EXAMPLE: sage: from sage.algebras.group_algebra import GroupAlgebra sage: GroupAlgebra(SU(2, 13), QQ).an_element() # random; hideous formatting! -1/95*[ 9 2*a + 12] [ 0 3] - 4*[ 9 9*a + 2] [3*a + 5 1]
625941f4fb3f5b602dac3ca2
def load_loan_defaulters(): <NEW_LINE> <INDENT> return _load_dataset('loan-defaulters.csv')
Load and return the loan defaulters dataset. Source: "Introduction to Data Mining" (1st Edition) by Pang-Ning Tan Figure 5.9, Page 230 ================= ==================== Classes 2 Samples per class [7, 3] Samples total 10 Dimensionality ...
625941f460cbc95b062c6b4c
def setupDefaultGeometry(self): <NEW_LINE> <INDENT> return _osgManipulator.TrackballDragger_setupDefaultGeometry(self)
setupDefaultGeometry(TrackballDragger self)
625941f4090684286d50f2f8
def neigh_diff_standard(bmus: torch.Tensor, positions: torch.Tensor) -> torch.Tensor: <NEW_LINE> <INDENT> return bmus - positions
Positional difference function. Computes index difference between Best Matching Units (`bmus`) and `positions`, where `positions` are indices of elements inside the SOM grid. Parameters ---------- bmus : torch.Tensor The list of Best Matching Units (2D indices) positions : torch.Tensor The 2D tensor of grid e...
625941f4e5267d203edce29d
def plotdata_comparison(xdata, ydata, xname, yname, fname, extension=".eps"): <NEW_LINE> <INDENT> legend = ["Uniform spacing", "Cosine spacing"] <NEW_LINE> fig = plt.figure(figsize=(6,4.5)) <NEW_LINE> ax = fig.add_subplot(111) <NEW_LINE> for i in range(len(legend)): <NEW_LINE> <INDENT> ax.plot(xdata[i], ydata[i], label...
Plots data with given names and saves it to a filename with extension
625941f40c0af96317bb87ef
def get_api(): <NEW_LINE> <INDENT> return twitter.Api(consumer_key=os.environ['TWITTER_CONSUMER_KEY'], consumer_secret=os.environ['TWITTER_CONSUMER_SECRET'], access_token_key=os.environ['TWITTER_ACCESS_TOKEN_KEY'], access_token_secret=os.environ['TWITTER_ACCESS_TOKEN_SECRET'])
read environment variables and create API object
625941f4090684286d50f2f9
def print_relations(self, other): <NEW_LINE> <INDENT> print("{self} shares with {other}:".format(self=self, other=other)) <NEW_LINE> print(" " + str([blob for blob in self.blobs if blob in other.blobs])) <NEW_LINE> print(" NOT SHARED:" + str(len( [blob for blob in self.blobs if blob not in other.blobs] )))
Recursively show relations of the manifest.
625941f4cc0a2c11143dd49a
def solve_bubble(graph, debut, fin): <NEW_LINE> <INDENT> ensemble_chemins = [] <NEW_LINE> for path in nx.all_simple_paths(graph, source=debut, target=fin): <NEW_LINE> <INDENT> ensemble_chemins.append(path) <NEW_LINE> <DEDENT> print(ensemble_chemins) <NEW_LINE> if len(ensemble_chemins) >= 2 and type(ensemble_chemins[...
Fonction permettant de nettoyer le graph, en prenant un noeud ancêtre et un noeud descendant.
625941f499cbb53fe67931ed
def test_phandle_bad2(self): <NEW_LINE> <INDENT> dtb_file = get_dtb_file('dtoc_test_phandle_bad2.dts', capture_stderr=True) <NEW_LINE> output = tools.GetOutputFilename('output') <NEW_LINE> with self.assertRaises(ValueError) as e: <NEW_LINE> <INDENT> self.run_test(['struct'], dtb_file, output) <NEW_LINE> <DEDENT> self.a...
Test a phandle target missing its #*-cells property
625941f4adb09d7d5db6cd94
def _by_columns(self, columns): <NEW_LINE> <INDENT> return columns if self.isstr(columns) else self._backtick_columns(columns)
Allow select.group and select.order accepting string and list
625941f4851cf427c661ab12
def decrypt(data: bytes, privkey: datatypes.PrivateKey, shared_mac_data: bytes = b'') -> bytes: <NEW_LINE> <INDENT> if data[:1] != b'\x04': <NEW_LINE> <INDENT> raise DecryptionError("wrong ecies header") <NEW_LINE> <DEDENT> shared = data[1:1 + PUBKEY_LEN] <NEW_LINE> key_material = ecdh_agree(privkey, keys.PublicKey(sha...
Decrypt data with ECIES method using the given private key 1) generate shared-secret = kdf( ecdhAgree(myPrivKey, msg[1:65]) ) 2) verify tag 3) decrypt ecdhAgree(r, recipientPublic) == ecdhAgree(recipientPrivate, R) [where R = r*G, and recipientPublic = recipientPrivate*G]
625941f48c0ade5d55d3efc9
def copy(self): <NEW_LINE> <INDENT> return ImageInText(self.get_link_title()[0], self.get_image_alt()[0], self.get_original_image_path(), self.get_thumbnail_image_path(), self.get_full_filename(), self.get_thumbnail_filename())
Returns a copy of this image. :return: A copy of this image.
625941f44a966d76dd55161e
def bucletotal(num,lado): <NEW_LINE> <INDENT> for i in range (3,num+1): <NEW_LINE> <INDENT> pintapol(i,lado,5) <NEW_LINE> t.reset()
Dibuja los poligonos num de veces, los borra y pone el siguiente hasta llegar a num
625941f4b57a9660fec33e95
def portfolio(request): <NEW_LINE> <INDENT> return render(request, 'portfolio.html')
Takes the request and renders Portfolio page
625941f41f5feb6acb0c5151
def __init__(self, did, name, description, project, parent=None, reactions=None, metabolites=None, genes=None, removed_metabolites=None, removed_reactions=None, removed_genes=None, base_model=None, conditions=None, is_pydesign=False, design_func=None): <NEW_LINE> <INDENT> self._as_model = None <NEW_LINE> self.project =...
Class for handling strain designs created by the project Mainly the useful functionality of this over dicts is validation, relationship to projects, creating the models as well as displaying the contents as a pandas dataframe :param project: Where project is None, the model will not be able to
625941f4a8ecb033257d36d3
def icrs_to_body_centered(r, v, target_body, epoch=J2000, rotate_meridian=False): <NEW_LINE> <INDENT> ra, dec, W = target_body.rot_elements_at_epoch(epoch) <NEW_LINE> icrs_frame_pos_coord, icrs_frame_vel_coord = get_body_barycentric_posvel(target_body.name, time=epoch) <NEW_LINE> r_trans1 = r - icrs_frame_pos_coord.xyz...
Converts position and velocity in ICRS to body-centered frame. Parameters ---------- r : ~astropy.units.Quantity Position vector in ICRS. v : ~astropy.units.Quantity Velocity vector in ICRS. target_body : Body Target body. epoch : ~astropy.time.Time, optional Epoch, default to J2000. rotate_meridian : ...
625941f48a349b6b435e877b
def p_expression(self, p): <NEW_LINE> <INDENT> if in_function_parsing_phase(): <NEW_LINE> <INDENT> p[0] = "" <NEW_LINE> return <NEW_LINE> <DEDENT> if len(p) == 4: <NEW_LINE> <INDENT> expr = Production(pre_type=None) <NEW_LINE> if p[1].pre_type == "list" or p[3].pre_type == "list": <NEW_LINE> <INDENT> print_err("Express...
expression : expression boolean_operator expression_pre_term expression : expression_pre_term
625941f476e4537e8c351c81
def check_primitive_type(self, value, prim_type, path, **kwargs): <NEW_LINE> <INDENT> matches = [] <NEW_LINE> if isinstance(value, dict): <NEW_LINE> <INDENT> return matches <NEW_LINE> <DEDENT> default_message = 'Value for {0} must be of type {1}' <NEW_LINE> if not isinstance(value, self.valid_attributes.get('primitive_...
Check primitive types
625941f499fddb7c1c9de996
def key_str(self, match): <NEW_LINE> <INDENT> ret = {} <NEW_LINE> for status, keys in self.name_match(match).items(): <NEW_LINE> <INDENT> ret[status] = {} <NEW_LINE> for key in salt.utils.isorted(keys): <NEW_LINE> <INDENT> path = os.path.join(self.opts['pki_dir'], status, key) <NEW_LINE> with open(path, 'r') as fp_: <N...
Return the specified public key or keys based on a glob
625941f43346ee7daa2b337a
def get_possible_digits_at_position(x, y, arr): <NEW_LINE> <INDENT> if int(arr[x, y]) is not 0: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> row_vals = list(filter(lambda a: a != 0, get_row(x, arr))) <NEW_LINE> col_vals = list(filter(lambda a: a != 0, get_col(y, arr))) <NEW_LINE> grid_vals = list(filter(lambda a...
Return a list of possible digits at position (x,y) This function enforces the rules of sudoku and returns a list of all possible digits at position (x,y). Handy for creating a tabu list.
625941f44527f215b584ca5a
def registered(self, conn): <NEW_LINE> <INDENT> return len(self.message_table.get(id(conn), EMPTY)) != 0
Check if a connection is registered into message table.
625941f47cff6e4e81117f8e
def num_words_on_board(board, words): <NEW_LINE> <INDENT> word_count=0 <NEW_LINE> for word_index in range(len(words)): <NEW_LINE> <INDENT> if board_contains_word(board, words[word_index]): <NEW_LINE> <INDENT> word_count=word_count+1 <NEW_LINE> <DEDENT> <DEDENT> return word_count
(list of list of str, list of str) -> int Return how many words appear on board. >>> num_words_on_board([['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']], ['ANT', 'BOX', 'SOB', 'TO']) 3
625941f4d53ae8145f87a86c
def ifft(spectrum): <NEW_LINE> <INDENT> fftdata = numpy.fft.irfft(spectrum) <NEW_LINE> frame = fftdata.view(pymir.Frame) <NEW_LINE> frame.sampleRate = spectrum.sampleRate <NEW_LINE> return frame
Compute the Inverse FFT
625941f466656f66f7cbc7b6
def createVolume(self, sdUUID, imgUUID, size, volFormat, preallocate, diskType, volUUID=None, desc="", srcImgUUID=sc.BLANK_UUID, srcVolUUID=sc.BLANK_UUID, initialSize=None, addBitmaps=False, legal=True, sequence=0, bitmap=None): <NEW_LINE> <INDENT> img_ns = rm.getNamespace(sc.IMAGE_NAMESPACE, sdUUID) <NEW_LINE> if imgU...
Creates a new volume. .. note:: If the *imgUUID* is **identical** to the *srcImgUUID* the new volume will be logically considered a snapshot of the old volume. If the *imgUUID* is **different** from the *srcImgUUID* the old volume will be logically considered as a template of the new volume. :para...
625941f4435de62698dfe256
def set_thread_priority(self, priority): <NEW_LINE> <INDENT> return _SDR_swig.Random_Bits_Generator_sptr_set_thread_priority(self, priority)
set_thread_priority(Random_Bits_Generator_sptr self, int priority) -> int
625941f416aa5153ce362a82
@lm.user_loader <NEW_LINE> def load_user(uid): <NEW_LINE> <INDENT> db = dbGetDatabase() <NEW_LINE> return dbGetUser(db, uid)
Given an ID, fetch the DB and return the corresponding user, if any.
625941f456b00c62f0f14c66
def __init__(self, ebunch=None): <NEW_LINE> <INDENT> super(DynamicBayesianNetwork, self).__init__() <NEW_LINE> if ebunch: <NEW_LINE> <INDENT> self.add_edges_from(ebunch) <NEW_LINE> <DEDENT> self.cpds = [] <NEW_LINE> self.cardinalities = defaultdict(int) <NEW_LINE> self.state_names= {}
Base class for Dynamic Bayesian Network This is a time variant model of the static Bayesian model, where each time-slice has some static nodes and is then replicated over a certain time period. The nodes can be any hashable python objects. Parameters: ---------- ebunch: Data to initialize graph. If data=None (defau...
625941f466673b3332b9269a
def update_site_forward(apps, schema_editor): <NEW_LINE> <INDENT> Site = apps.get_model('sites', 'Site') <NEW_LINE> Site.objects.update_or_create( id=settings.SITE_ID, defaults={ 'domain': 'alted.io', 'name': 'alted' } )
Set site domain and name.
625941f423e79379d52eeb64
def previous_layers_weights_jacobian(x, weights, loss): <NEW_LINE> <INDENT> d_hidden = softmax_layer_jacobian_wrt_inputs(weights, loss) <NEW_LINE> return np.dot(d_hidden.T, x)
:param x: (batch size x n) :param weights: (m x h) :param loss: (batch_size x m) :return: previous layers weights (h x n)
625941f4e76e3b2f99f3ae0a
def get_message(self): <NEW_LINE> <INDENT> return self._message
Get the message of the exception. :return: the message of the exception. :rtype: str
625941f42c8b7c6e89b35dc4
def scheduled_messages(self): <NEW_LINE> <INDENT> msg = False <NEW_LINE> now = time.strftime('%H:%M') <NEW_LINE> if now in TIMED: <NEW_LINE> <INDENT> msg = TIMED[now] <NEW_LINE> <DEDENT> if msg: <NEW_LINE> <INDENT> if isinstance(msg, str): <NEW_LINE> <INDENT> msg = (msg,) <NEW_LINE> <DEDENT> for i in msg: <NEW_LINE> <I...
Function which broadcasts scheduled messages to chat
625941f4009cb60464c639b5
def connect(self): <NEW_LINE> <INDENT> log.info('Creating/updating resource group: {} with location: {}'.format(self.group_name, self.location)) <NEW_LINE> self.resource_client.resource_groups.create_or_update(self.group_name, {'location': self.location}) <NEW_LINE> if self.instancetype == 'Standard_NC6' or self.instan...
Obtain the Azure connector by authenticating. This also creates the keypair and security group for the instance.
625941f44e4d5625662d49d7
def __init__( self, *, location: str, tags: Optional[Dict[str, str]] = None, source_virtual_machine: Optional["SubResource"] = None, storage_profile: Optional["ImageStorageProfile"] = None, **kwargs ): <NEW_LINE> <INDENT> super(Image, self).__init__(location=location, tags=tags, **kwargs) <NEW_LINE> self.source_virtual...
:keyword location: Required. Resource location. :paramtype location: str :keyword tags: A set of tags. Resource tags. :paramtype tags: dict[str, str] :keyword source_virtual_machine: The source virtual machine from which Image is created. :paramtype source_virtual_machine: ~azure.mgmt.compute.v2018_10_01.models.SubReso...
625941f4be8e80087fb21240
def getUID(obj,preferences): <NEW_LINE> <INDENT> uid = None <NEW_LINE> if hasattr(obj,"IfcData"): <NEW_LINE> <INDENT> if "IfcUID" in obj.IfcData.keys(): <NEW_LINE> <INDENT> uid = str(obj.IfcData["IfcUID"]) <NEW_LINE> <DEDENT> <DEDENT> if not uid: <NEW_LINE> <INDENT> uid = ifcopenshell.guid.new() <NEW_LINE> if preferenc...
gets or creates an UUID for an object
625941f40c0af96317bb87f0
def _walk(self,**kwargs): <NEW_LINE> <INDENT> self.update(**kwargs) <NEW_LINE> skip_dir_set = set(self.skip_dir_list) <NEW_LINE> for p in ( self._jumeg_path_list ): <NEW_LINE> <INDENT> for root, dirs, files in os.walk(p): <NEW_LINE> <INDENT> if (set(root.split(os.sep)) & skip_dir_set): continue <NEW_LINE> for f in fil...
search recursive for executable modules Parameters: ----------- stage_prefix : stage prefix <jumeg> prefix : file prefix <jumeg> postfix : file postfix <None> extention : file extention <".py> permission: file permission <os.X_OK|os.R_OK> Results: -------- list of executable modules, full filena...
625941f4d6c5a10208144659
def add_line(self, line) -> None: <NEW_LINE> <INDENT> entry_info = self.extract_info(line) <NEW_LINE> if entry_info: <NEW_LINE> <INDENT> self.update_stats(entry_info)
Получив на вход строку лога, проверяет её на корректность и добавляет в статистику.
625941f44e4d5625662d49d8
def deformationModelVersion(self): <NEW_LINE> <INDENT> return self._deformationModelVersion
Returns the deformation model version
625941f4925a0f43d254a486
def get_bridge_list(self): <NEW_LINE> <INDENT> if self._hypervisor_handler is None: <NEW_LINE> <INDENT> self._hypervisor_handler = self.get_handler() <NEW_LINE> <DEDENT> bridge_name_list = [] <NEW_LINE> for netdom in self._hypervisor_handler.listAllNetworks(): <NEW_LINE> <INDENT> bridge_name_list.append(netdom.bridgeNa...
@return: return all the switch/bridge names on host @note: can not list the bridge which is not defined by xml
625941f426238365f5f0f47f