text
stringlengths
15
7.82k
ids
sequencelengths
1
7
def METHOD_NAME(self, qtbot, analysis_segmentation2, part_settings): widget = MeasurementWidget(part_settings) qtbot.addWidget(widget) assert widget.measurement_type.count() == 3 part_settings.set_project_info(analysis_segmentation2) widget.measurement_type.setCurrentIndex(2) assert widget.recalculate_button.isEnabled() widget.recalculate_button.click() assert widget.info_field.columnCount() == 2 assert widget.info_field.rowCount() == 3 assert widget.info_field.item(1, 1).text() == "4" widget.horizontal_measurement_present.setChecked(True) assert widget.info_field.columnCount() == 3 assert widget.info_field.rowCount() == 2
[ 9, 13157 ]
def METHOD_NAME(self) -> 'outputs.DevOpsConfigurationPropertiesResponse': """ DevOps Configuration properties. """ return pulumi.get(self, "properties")
[ 748 ]
def METHOD_NAME(self) -> None: self._client.METHOD_NAME()
[ 1462 ]
def METHOD_NAME(self): combo_box = self.system_tray_icon_theme_combobox # type: QComboBox for index, icon_name in GeneralSettings.ICON_TABLE: combo_box.setItemData(index, icon_name, Qt.UserRole)
[ 1917, 857, 875, 2695, 21, 365 ]
def METHOD_NAME(self) -> str: return "Split: {split}".format(**self.__dict__)
[ 1967, 92 ]
def METHOD_NAME(self): for rec in self: if rec.tipo_declaracion == "N": rec.tipo_declaracion_negativa = rec.tipo_declaracion rec.tipo_declaracion_positiva = False else: rec.tipo_declaracion_positiva = rec.tipo_declaracion rec.tipo_declaracion_negativa = False
[ 226, 16874, 16875 ]
def METHOD_NAME( category: str, task: Task, bg_color: Tuple[float, float, float] = (0.0, 0.0, 0.0), single_sequence_id: Optional[int] = None, num_workers: int = 16,
[ 1195, -1, 43, 253 ]
def METHOD_NAME(self): self.assertTrue(self.evaluate('number_list:1')) self.assertTrue(self.evaluate('number_list:2')) self.assertTrue(self.evaluate('number_list:3')) self.assertTrue(self.evaluate('boolean_list:true')) self.assertTrue(self.evaluate('boolean_list:false')) self.assertTrue(self.evaluate('string_list:"hello world"')) self.assertTrue(self.evaluate('string_list:example')) self.assertFalse(self.evaluate('number_list:4')) self.assertFalse(self.evaluate('string_list:"missing"'))
[ 9, 245, 99 ]
def METHOD_NAME(method): def wrapper(*args, **kwargs): try: return method(*args, **kwargs) except osparc.exceptions.ApiException as e: args[0]._api_client.close() expt = json.loads(e.body) raise osparc_server_exception("\n".join(expt["errors"])) from None return wrapper
[ 972 ]
def METHOD_NAME(): return 'session'
[ 19, 549, 156 ]
def METHOD_NAME(): with pytest.raises(TypeError): Package(42, "name", "location")
[ 9, 909, 44, 623, 5498, 147 ]
def METHOD_NAME(self): """ sub_mult is positive """ return self._run_query(SQL("{0} <= 0").format(Identifier('sub_mult')))
[ 250, 1066, 1998, 2302 ]
def METHOD_NAME(region: str) -> Set[str]: """Returns a set of zones in the region.""" # As of 2021 all Azure AZs are numbered 1-3 for eligible regions. return set([f'{region}-{i}' for i in range(1, 4)])
[ 19, 3051, 623, 1216 ]
def METHOD_NAME(node): vcol_start = Vector(node.color_start) vcol_end = Vector(node.color_end) def element_iterated(matrix, theta, index): return matrix, Color(vcol_start.lerp(vcol_end, index*theta))[:] data = node.inputs['Matrix'].sv_get() data_out = [] get_mat_theta_idx = data_out.append if len(data) > 0: theta = 1 / len(data) for idx, matrix in enumerate(data): get_mat_theta_idx([matrix, theta, idx]) return [element_iterated(*values) for values in data_out]
[ 590, 36, 24, 430 ]
def METHOD_NAME(): """Hides the homophones display""" close_homophones()
[ 2688, 1243 ]
def METHOD_NAME(self): self.assertIsNone(CTi.get_entity('1//0'))
[ 9, 1068, 2419 ]
def METHOD_NAME(premium_data_fixture): session_id = "session-id" user = premium_data_fixture.create_user( has_active_premium_license=True, session_id=session_id ) view = premium_data_fixture.create_grid_view(user=user) decorator_type_name = "left_border_color" value_provider_type_name = "" value_provider_conf = {} action_type_registry.get_by_type(CreateDecorationActionType).do( view, decorator_type_name, value_provider_type_name, value_provider_conf, user=user, ) ActionHandler.undo(user, [ViewActionScopeType.value(view.id)], session_id) action_redone = ActionHandler.redo( user, [ViewActionScopeType.value(view.id)], session_id ) assert_undo_redo_actions_are_valid(action_redone, [CreateDecorationActionType]) assert ViewDecoration.objects.count() == 1
[ 9, 1046, 2796, 2797, 129, 14376 ]
def METHOD_NAME(self): a_signal.connect(receiver_1_arg, sender=self) try: expected = [(receiver_1_arg, 'test')] result = a_signal.send(sender=self, val='test') assert result == expected finally: a_signal.disconnect(receiver_1_arg, sender=self) self._testIsClean(a_signal)
[ 9, 2017 ]
def METHOD_NAME(backend): if backend == "azure": return "eastus" return "some-region"
[ 1216 ]
def METHOD_NAME(self): self.assertLocalizedHolidays( "en_US", ("2022-01-01", "New Year's Day"), ("2022-02-24", "Independence Day"), ("2022-04-15", "Good Friday"), ("2022-04-17", "Easter Sunday"), ("2022-05-01", "Spring Day"), ("2022-06-05", "Whit Sunday"), ("2022-06-23", "Victory Day"), ("2022-06-24", "Midsummer Day"), ("2022-08-20", "Independence Restoration Day"), ("2022-12-24", "Christmas Eve"), ("2022-12-25", "Christmas Day"), ("2022-12-26", "Second Day of Christmas"), )
[ 9, 1594, 4334, 4335 ]
def METHOD_NAME(conf): """ Detects msgfmt and sets the ``MSGFMT`` variable """ conf.find_program('msgfmt', var='MSGFMT')
[ 416, 9953 ]
def METHOD_NAME(self): #save window position (only; not size!) settings = QSettings() settings.setValue('SamplingPosition',self.frameGeometry().topLeft())
[ 1308, 817 ]
def METHOD_NAME( self, ) -> Address: message = {"type": -103000} response = self._sent_sync_request(message) return Address( public_key=response["pub_key"], private_key=response["wif"], index=response["index"], address=response["address"], )
[ 567, 85 ]
def METHOD_NAME(item): """ pytest hook to skip all tests that have the mark 'remotedata' if the pytest_remotedata plugin is not installed. """ if isinstance(item, pytest.Function): if 'remote_data' in item.keywords and not HAVE_REMOTEDATA: pytest.skip("skipping remotedata tests as pytest-remotedata is not installed") # Confirm that the pyplot figure stack is empty before the test if HAVE_MATPLOTLIB and plt.get_fignums(): raise SunpyUserWarning(f"There are stale pyplot figures prior to running {item.name}")
[ 2595, 2596, 102 ]
def METHOD_NAME(self): pass
[ 0, 1 ]
def METHOD_NAME(self, filename): self.filenames.append(filename) self.current_filename = filename self.element_builders_by_filename[self.current_filename] = {} self.material_builders_by_filename[self.current_filename] = {} f = open(filename, "r") line = f.readline() while line: line = line.strip().replace("\t", " ") self.read_one_item(f, line) line = f.readline()
[ 203, 280, 171 ]
def METHOD_NAME(self): """Test execution statistics. Statistics are an instance of :class:`~robot.model.statistics.Statistics` that is created based on the contained ``suite`` and possible :func:`configuration <configure>`. Statistics are created every time this property is accessed. Saving them to a variable is thus often a good idea to avoid re-creating them unnecessarily:: from robot.api import ExecutionResult result = ExecutionResult('output.xml') result.configure(stat_config={'suite_stat_level': 2, 'tag_stat_combine': 'tagANDanother'}) stats = result.statistics print(stats.total.failed) print(stats.total.passed) print(stats.tags.combined[0].total) """ return Statistics(self.suite, rpa=self.rpa, **self._stat_config)
[ 68 ]
def METHOD_NAME(filename, formattername="CustomFormatter", **options): """Load a formatter from a file. This method expects a file located relative to the current working directory, which contains a class named CustomFormatter. By default, it expects the Formatter to be named CustomFormatter; you can specify your own class name as the second argument to this function. Users should be very careful with the input, because this method is equivalent to running eval on the input file. Raises ClassNotFound if there are any problems importing the Formatter. .. versionadded:: 2.2 """ try: # This empty dict will contain the namespace for the exec'd file custom_namespace = {} with open(filename, 'rb') as f: exec(f.read(), custom_namespace) # Retrieve the class `formattername` from that namespace if formattername not in custom_namespace: raise ClassNotFound('no valid %s class found in %s' % (formattername, filename)) formatter_class = custom_namespace[formattername] # And finally instantiate it with the options return formatter_class(**options) except OSError as err: raise ClassNotFound('cannot read %s: %s' % (filename, err)) except ClassNotFound: raise except Exception as err: raise ClassNotFound('error when loading custom formatter: %s' % err)
[ 557, 2931, 280, 171 ]
def METHOD_NAME(nframes, atom_types): natoms = len(atom_types) data = {} data["coords"] = np.random.random([nframes, natoms, 3]) data["forces"] = np.random.random([nframes, natoms, 3]) data["cells"] = np.random.random([nframes, 9]) data["energies"] = np.random.random([nframes, 1]) types = list(set(atom_types)) types.sort() data["atom_names"] = [] data["atom_numbs"] = [] for ii in range(len(types)): data["atom_names"].append("TYPE_%d" % ii) data["atom_numbs"].append(np.sum(atom_types == ii)) data["atom_types"] = np.array(atom_types, dtype=int) return data
[ 370, 3709 ]
def METHOD_NAME(self, queryCoords, qdist): """Get attributes by coordinates (all available layers) Return line id or None if no line is found""" line = None nselected = 0 try: data = grass.vector_what( map=self.map, coord=(float(queryCoords[0]), float(queryCoords[1])), distance=float(qdist), ) except grass.ScriptError: GError( parent=None, message=_( "Failed to query vector map <{map}>. " "Check database settings and topology." ).format(map=self.map), ) if len(data) < 1 or all(("Table" not in record) for record in data): return None # process attributes ret = dict() for key in ["Category", "Layer", "Table", "Id"]: ret[key] = list() for record in data: if "Table" not in record: continue table = record["Table"] for key, value in record["Attributes"].items(): if len(value) < 1: value = None else: if self.tables[table][key]["ctype"] != str: value = self.tables[table][key]["ctype"](value) else: value = GetUnicodeValue(value) self.tables[table][key]["values"].append(value) for key, value in record.items(): if key == "Attributes": continue if key in ret: ret[key].append(value) if "Id" not in record.keys(): ret["Id"].append(None) return ret
[ 1472, 604, 1669 ]
def METHOD_NAME(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict())
[ 24, 3 ]
def METHOD_NAME(self): return self.__open_range
[ 19, 1452, 661 ]
def METHOD_NAME(self, plain_password): """Check the password against existing credentials. """ return PasswordUtil.is_password_valid(plain_password, self._password)
[ 187, 2897 ]
def METHOD_NAME(self, area): return self.threshold_yellow * area
[ 10113, 853, 559 ]
def METHOD_NAME(ts): usno = Topos('38.9215 N', '77.0669 W', elevation_m=92.0) t = ts.tt(jd=api.T0) p = usno.at(t) a = api.Angle(degrees=10.0) d = api.Distance(au=0.234) with assert_raises(ValueError, 'the alt= parameter with an Angle'): p.from_altaz(alt='Bad value', alt_degrees=0, az_degrees=0) with assert_raises(ValueError, 'the az= parameter with an Angle'): p.from_altaz(az='Bad value', alt_degrees=0, az_degrees=0) p.from_altaz(alt=a, alt_degrees='bad', az_degrees=0) p.from_altaz(az=a, alt_degrees=0, az_degrees='bad') assert str(p.from_altaz(alt=a, az=a).distance()) == '0.1 au' assert str(p.from_altaz(alt=a, az=a, distance=d).distance()) == '0.234 au'
[ 9, 280, 5726, 386 ]
def METHOD_NAME(self): self.__importing = False
[ 512, 1239 ]
def METHOD_NAME(): log_cfg = """
[ 102, 663 ]
def METHOD_NAME(self, os_mock): static_dir = "mydir" cwd = "cwd" resolved_path = "cwd/mydir" os_mock.path.join.return_value = resolved_path os_mock.path.exists.return_value = True # Fake the path to exist result = LocalApiService._make_static_dir_path(cwd, static_dir) self.assertEqual(resolved_path, result) os_mock.path.join.assert_called_with(cwd, static_dir) os_mock.path.exists.assert_called_with(resolved_path)
[ 9, 1923, 1014, 41, 1924, 24, 1925 ]
def METHOD_NAME(self, text, searchphrase=None): "Make dialog visible on top of others and ready to use." self.text = text if not self.top: self.create_widgets() else: self.top.deiconify() self.top.tkraise() self.top.transient(text.winfo_toplevel()) if searchphrase: self.ent.delete(0,"end") self.ent.insert("end",searchphrase) self.ent.focus_set() self.ent.selection_range(0, "end") self.ent.icursor(0) self.top.grab_set()
[ 1452 ]
f METHOD_NAME(self):
[ 9, 144, 24, 1161, 471, 12738 ]
METHOD_NAME(self):
[ 3476, 24, 865, 1024 ]
def METHOD_NAME(pce): """ Generate text for course enrollment, including ID and is_active value. """ enrollment = pce.course_enrollment if not enrollment: return None active_string = "Active" if enrollment.is_active else "Inactive" return "id={enrollment.id:09} ({active_string})".format( enrollment=enrollment, active_string=active_string )
[ 15657, 7104 ]
def METHOD_NAME(self, sql_insert, records): """ insert data into table using a list of lists (i.e. executemany). This should be an efficient bulk insert. :param records: a list of list :return: """ try: c = self.conn.cursor() c.executemany(sql_insert, records) self.conn.commit() except Error as e: print(e)
[ 408, 2278 ]
def METHOD_NAME(capfd, mocker): set_module_args({'login_host': 'localhost', 'login_password': 'secret', 'key': 'foo', '_ansible_check_mode': True}) mocker.patch('redis.Redis.get', return_value='bar') with pytest.raises(SystemExit): redis_data_incr.main() out, err = capfd.readouterr() print(out) assert not err assert json.loads(out)['failed'] assert json.loads(out)[ 'msg'] == "Value: bar of key: foo is not incrementable(int or float)" assert 'value' not in json.loads(out) assert not json.loads(out)['changed']
[ 9, 2485, 365, 6000, 250, 854, 130 ]
def METHOD_NAME( self, req: features.AzureDiskOptionSettings, cap: features.AzureDiskOptionSettings, disk_type: schema.DiskType = schema.DiskType.StandardHDDLRS, data_disk_count: int = 1, data_disk_caching_type: str = constants.DATADISK_CACHING_TYPE_NONE, data_disk_iops: int = 500, data_disk_size: int = 32, ) -> None: reason = req.check(cap) self.assertTrue(reason.result, f"check reasons: {reason.reasons}") min_value: features.AzureDiskOptionSettings = req.generate_min_capability(cap) self.assertEqual(disk_type, min_value.data_disk_type) self.assertEqual(data_disk_count, min_value.data_disk_count) self.assertEqual(data_disk_caching_type, min_value.data_disk_caching_type) self.assertEqual(data_disk_iops, min_value.data_disk_iops) self.assertEqual(data_disk_size, min_value.data_disk_size)
[ 638, 113 ]
def METHOD_NAME(self): self.test_for_break(no_pyobj_flags)
[ 9, 43, 699, 1022 ]
def METHOD_NAME(): mask_data = np.ones((10, 10)) bbox = RegionBoundingBox(5, 15, 5, 15) mask = RegionMask(mask_data, bbox) with pytest.raises(ValueError): mask.cutout(np.arange(10)) with pytest.raises(ValueError): mask.to_image((10,))
[ 9, 361, 1979, 555 ]
def METHOD_NAME(): """Test the process function with an input cube that has both rain and snow in its name""" rain, snow = setup_cubes() rain.rename("its_raining_snowy_kittens") snow.rename("puppies") with pytest.raises( ValueError, match=( "Failed to find unique rain and snow cubes from " r"\['its_raining_snowy_kittens', 'puppies'\]" ), ): SnowFraction()(iris.cube.CubeList([rain, snow]))
[ 9, 362, 156, 855, 2171, 12005, 168 ]
async def METHOD_NAME(connection, cmd, sub_val): val = await connection.execute_command(cmd, sub_val) return val
[ 22, 1660 ]
async def METHOD_NAME(): if not (fully_loaded and model_loaded): raise fastapi.HTTPException(status_code=503, detail="Server not fully loaded") return {"status": "ok"}
[ 3393 ]
def METHOD_NAME(rules): for rule in rules: if rule.type == "error": yield "error", rule continue if rule.type == "at-rule" and rule.content: at_rules = tinycss2.parser.parse_rule_list( rule.content, skip_comments=True, skip_whitespace=True ) media_selector = selectors.media_query_selector(rule.prelude) if not media_selector: continue media_query = compile_node(media_selector) yield from ( ((_combine(media_query, selspec[0]), selspec[1]), declaration) for selspec, declaration in METHOD_NAME(at_rules) if selspec != "error" ) if rule.type != "qualified-rule": continue try: selector_list = compile_selector_list(rule.prelude) except selectors.SelectorError as e: yield "error", e continue declaration = { prop: value for prop, value in parse_declarations(rule.content) if prop != "error" and value is not None } yield from ((selector, declaration) for selector in selector_list)
[ 296, 1634 ]
METHOD_NAME(any):
[ 2147, 80, 280, 1042, 101 ]
def METHOD_NAME(self, configurationAttributes): return 1
[ 19, 29, 1970, 1910 ]
def METHOD_NAME(self) -> Dict[str, str]: return { f"{dep.db}.{dep.schema}.{dep.name}": dep.type for dep in self.dependencies }
[ 947, 1042 ]
def METHOD_NAME(d: np.ndarray) -> np.ndarray: """Computes Autodock Vina's hydrogen bond interaction term. Here, d is the set of surface distances as defined in [1]_ Parameters ---------- d: np.ndarray A numpy array of shape `(N, M)`. Returns ------- np.ndarray A `(N, M)` array of hydrophoboic interactions in a piecewise linear curve. References ---------- .. [1] Jain, Ajay N. "Scoring noncovalent protein-ligand interactions: a continuous differentiable function tuned to compute binding affinities." Journal of computer-aided molecular design 10.5 (1996): 427-440. """ out_tensor = np.where( d < -0.7, np.ones_like(d), np.where(d < 0, (1.0 / 0.7) * (0 - d), np.zeros_like(d))) return out_tensor
[ 7238, 7239 ]
def METHOD_NAME(self, is_active: bool) -> CbsdAPIDataBuilder: self.payload['is_active'] = is_active return self
[ 41, 137, 923 ]
def METHOD_NAME(write_client): i = Index("test-blog", using=write_client) i.settings(number_of_shards=3, number_of_replicas=0) i.save() i.settings(number_of_replicas=1) i.save() assert ( "1" == i.get_settings()["test-blog"]["settings"]["index"]["number_of_replicas"] )
[ 9, 724, 1046, 673, 2973, 5602, 41 ]
def METHOD_NAME(self) -> None: third_party_linter = css_linter.ThirdPartyCSSLintChecksManager([]) lint_task_report = third_party_linter.perform_all_lint_checks() self.assertEqual( 'There are no HTML or CSS files to lint.', lint_task_report[0].get_report()[0]) self.assertEqual('CSS lint', lint_task_report[0].name) self.assertFalse(lint_task_report[0].failed)
[ 9, 407, 75, 3060, 2676, 41, 654 ]
def METHOD_NAME() -> int: return 6
[ 391, 1221, 2374 ]
def METHOD_NAME(self, code): if 0 <= code <= 255: return repr(chr(code)) else: return "chr(%d)" % code
[ 278, 3874 ]
def METHOD_NAME(self): return """\ maxpoints Sets the maximum number of points to keep on the plots from an incoming stream. If `maxpoints` is set to 50, only the newest 50 points will be displayed on the plot. token The stream id number links a data trace on a plot with a stream. See https://chart-studio.plotly.com/settings for more details. """
[ 1302, 1303 ]
def METHOD_NAME(self) -> str: """ The URL at which the image can be accessed. """ return pulumi.get(self, "image_url")
[ 660, 274 ]
def METHOD_NAME(self, name): count = 0 ns = self.sms.get_namespace(name) while ns.status != 'Active': count = count + 1 if count > 120: self.assertTrue( False, 'Timed out waiting for service bus namespace activation.') time.sleep(5) ns = self.sms.get_namespace(name)
[ 618, 43, 1194, 923 ]
def METHOD_NAME() -> Iterable[TargetHost]: host_1 = TargetHost(ip=IPv4Address("10.0.0.1")) host_2 = TargetHost(ip=IPv4Address("10.0.0.3")) return [host_1, host_2]
[ 3175 ]
def METHOD_NAME(self): #Make sure the conditional acquiring of the lock works. self.assertTrue(self.lock.acquire(0), "Conditional acquiring of the lock failed.")
[ 9, 1944, 1489, 1434 ]
def METHOD_NAME(cone): """Convert a COMPAS cone to a Rhino cone. Parameters ---------- cone: :class:`~compas.geometry.Cone` Returns ------- :rhino:`Rhino.Geometry.Cone` """ return RhinoCone(plane_to_rhino(cone.circle.plane), cone.height, cone.circle.radius)
[ 5568, 24, 6154 ]
def METHOD_NAME(self, statistics: RuleMatchStatistics) -> None: self._statistics = statistics self._recalc_opt_ruleblocks()
[ 86, 68 ]
def METHOD_NAME(request, region_slug): """ Set read flag for a list of feedback items :param request: Object representing the user call :type request: ~django.http.HttpRequest :param region_slug: The slug of the current region :type region_slug: str :return: A redirection to the region feedback list :rtype: ~django.http.HttpResponseRedirect """ region = request.region selected_ids = request.POST.getlist("selected_ids[]") selected_feedback = Feedback.objects.filter( id__in=selected_ids, region=region, is_technical=False ) for feedback in selected_feedback: invalidate_obj(feedback) if hasattr(feedback, "feedback_ptr"): invalidate_obj(feedback.feedback_ptr) selected_feedback.update(read_by=request.user) logger.debug( "Feedback objects %r marked as read by %r", selected_ids, request.user, ) messages.success(request, _("Feedback was successfully marked as read")) return redirect("region_feedback", region_slug=region_slug)
[ 1743, 1216, 2921, 947, 203 ]
def METHOD_NAME(labels, logits): loss = loss_fn(labels, logits) return tf.nn.compute_average_loss(loss, global_batch_size=args.global_batch_size)
[ 5501, 1572 ]
def METHOD_NAME(self) -> NamedJsonDBTuple: """May raise: - DeserializationError if something fails during conversion to the DB tuple """ event_type = self.event_type.serialize_for_db() try: string_data = rlk_jsondumps(self.data) except (OverflowError, ValueError, TypeError) as e: raise DeserializationError( f'Could not dump json to string for NamedJson. Error was {e!s}', ) from e return event_type, string_data
[ 24, 1267, 1815 ]
def METHOD_NAME(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict())
[ 24, 3 ]
def METHOD_NAME() -> str: """Return the currently configured root mephisto directory""" # This file is at ROOT/mephisto/utils/dirs.py return os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
[ 19, 1563, 1190 ]
def METHOD_NAME(self): res = self.res data = self.data fitted = res.fittedvalues.iloc[1:10:2] # plain numpy array pred = res.predict(res.model.exog[1:10:2], transform=False) assert_allclose(pred, fitted.values, rtol=1e-13) # pandas DataFrame x = pd.DataFrame(res.model.exog[1:10:2], index = data.index[1:10:2], columns=res.model.exog_names) pred = res.predict(x) pdt.assert_index_equal(pred.index, fitted.index) assert_allclose(pred.values, fitted.values, rtol=1e-13) # one observation - 1-D pred = res.predict(res.model.exog[1], transform=False) assert_allclose(pred, fitted.values[0], rtol=1e-13) # one observation - pd.Series pred = res.predict(x.iloc[0]) pdt.assert_index_equal(pred.index, fitted.index[:1]) assert_allclose(pred.values[0], fitted.values[0], rtol=1e-13)
[ 9, -1 ]
def METHOD_NAME(path, parent=None, user=None, exists=None): """ Retrieve a plot file from Plotly without needing a fid. :param (str) path: The '/'-delimited path specifying the file location. :param (int) parent: Parent id, an integer, which the path is relative to. :param (str) user: The username to target files for. Defaults to requestor. :param (bool) exists: If True, don't return the full file, just a flag. :returns: (requests.Response) Returns response directly from requests. """ url = build_url(RESOURCE, route="lookup") params = make_params(path=path, parent=parent, user=user, exists=exists) return request("get", url, params=params)
[ 1906 ]
def METHOD_NAME(self): return sorted(glob.glob(self.get_input_path("*.{}".format(self.extension))))
[ 362, 7570 ]
def METHOD_NAME(self, metadata: Metadata) -> str: title = metadata.get("type") if title is not None: value = metadata.get("value") if value: title += f": {truncatechars(value.splitlines()[0], 100)}" # If there's no value for display_title_with_tree_label, or if the # value is None, we should show the tree labels anyway since it's an # old event. if metadata.get("display_title_with_tree_label") in (None, True): return compute_title_with_tree_label(title, metadata) return title or metadata.get("function") or "<unknown>"
[ 226, 2893 ]
def METHOD_NAME(name, region=None, key=None, keyid=None, profile=None): """ Return attributes currently set on an SQS queue. CLI Example: .. code-block:: bash salt myminion boto_sqs.get_attributes myqueue """ conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: url = conn.get_queue_url(QueueName=name)["QueueUrl"] r = conn.get_queue_attributes(QueueUrl=url, AttributeNames=["All"]) return {"result": r["Attributes"]} except botocore.exceptions.ClientError as e: return {"error": __utils__["boto3.get_error"](e)}
[ 19, 177 ]
def METHOD_NAME(data, min=4): result = "" for c in data: if chr(c) in string.printable: result += chr(c) continue if len(result) >= min: yield result result = "" if len(result) >= min: yield result
[ 19, 3224 ]
def METHOD_NAME(self, rec, verbose=False): """ check level_* attributes """ return self._check_level(rec, verbose=verbose)
[ 250, 33 ]
def METHOD_NAME(self, key, string): ...
[ -1 ]
def METHOD_NAME(self, aedtapp, st, local_scratch): self.aedtapp = aedtapp self.st = st self.local_scratch = local_scratch
[ 176 ]
def METHOD_NAME(self, sd: pp.Grid, data: dict): """Return the rhs for a discretization of the integrated source term. Also discretize the necessary operators if the data dictionary does not contain a source term. Parameters: sd (Grid): Computational grid, with geometry fields computed. data (dictionary): With data stored. Returns: np.array (self.ndof): Right hand side vector representing the source. """ matrix_dictionary = data[pp.DISCRETIZATION_MATRICES][self.keyword] parameter_dictionary = data[pp.PARAMETERS][self.keyword] sources = parameter_dictionary["source"] assert sources.size == self.ndof( sd ), "There should be one source value for each cell" return matrix_dictionary["bound_source"] * sources
[ 1893, 8919 ]
def METHOD_NAME(self): auth = self._create_authorization_header(self.application.client_id, self.application.client_secret_plain) response = self.client.get("/oauth2-test/", HTTP_AUTHORIZATION=auth, HTTP_X_AUTHENTICATION=self._create_authentication_header(self.test_username)) self.assertEqual(response.status_code, 200)
[ 9, 1970, 2569 ]
def METHOD_NAME(self): self.assertMarkdownRenders( self.dedent( """ ABBR *[ABBR]: Abbreviation """ ), self.dedent( """ <p><abbr title="Abbreviation">ABBR</abbr></p> """ ) )
[ 9, 4946, 534, 699 ]
def METHOD_NAME(): class Obj: def __init__(self, a): self.a = a self.b = 3.0 self.c = [1, 2, "test", ["nested list"]] self.d = {2: 3, "2": "salut"} o = Obj(2) o_serialized = hashing.get_json(o) assert ( str(o_serialized) == '{"a": 2, "b": 3.0, "c": [1, 2, "test", ["nested list"]], "d": {"2": 3, "2": "salut"}}' )
[ 9, 10308, 293, 41, 279 ]
async def METHOD_NAME(self) -> None: ...
[ 2869 ]
def METHOD_NAME(self, data, ensure_copy=False): v = self.real_zero_vector() np_view = np.array(v.impl, copy=False) np_view[:] = data return v
[ 1866, 798, 280, 2028 ]
def METHOD_NAME(self): '''check starter settings''' if self.gasheli_settings.ignition_chan <= 0 or self.gasheli_settings.ignition_chan > 8: print("Invalid ignition channel %d" % self.gasheli_settings.ignition_chan) return False if self.gasheli_settings.starter_chan <= 0 or self.gasheli_settings.starter_chan > 14: print("Invalid starter channel %d" % self.gasheli_settings.starter_chan) return False return True
[ 1205, 3803, 817 ]
def METHOD_NAME(self, file: str) -> bool: try: minio_client = self._get_client() minio_client.stat_object(bucket_name=self._connect_param._bucket_name, object_name=file) except S3Error as err: if err.code == "NoSuchKey": return False self._throw(f"Failed to stat MinIO/S3 object, error: {err}") return True
[ 2437, 954 ]
def METHOD_NAME(hg_repo_with_content): """Test simple hg clone to a target dir""" upstream, node_id = hg_repo_with_content with TemporaryDirectory() as clone_dir: spec = {"repo": upstream} mercurial = Mercurial() for _ in mercurial.fetch(spec, clone_dir): pass assert (Path(clone_dir) / "test").exists() assert mercurial.content_id == node_id
[ 9, 670 ]
def METHOD_NAME(self, name: str) -> None | Route: """Search for a route from all alternative data sources.""" for _key, value in sorted( self.alternatives.items(), # lowest priority for the default source of information key=lambda key: 1 if key[0] == "default" else 0, ): alt = value[name] if alt is not None: return alt return None
[ 285, 19 ]
def METHOD_NAME(tmp_path: pathlib.Path) -> None: env = get_dummy_env() base_path = tensorboard.get_base_path({"base_path": BASE_PATH}) sync_path = tensorboard.get_sync_path( env.det_cluster_id, env.det_experiment_id, env.det_trial_id ) manager = SharedFSTensorboardManager(str(tmp_path), base_path, sync_path) test_files = [ "no_show.txt", "79375caf89e9.kernel_stats.pb", "79375caf89e9.memory_profile.json.gz", "events.out.tfevents.example", ] test_filepaths = [BASE_PATH.joinpath("tensorboard--0", test_file) for test_file in test_files] tb_files = manager.list_tb_files(0, lambda _: True) assert set(test_filepaths) == set(tb_files)
[ 9, 245, 6345, 1537 ]
def METHOD_NAME(instance, status): assert instance.identity_migration_status == status
[ 9, 2989, 2672, 452 ]
def METHOD_NAME(self): self.close() self.__init__(config=self.config)
[ 1141 ]
def METHOD_NAME() -> None: warnings.warn( message="""Dep002: You are batching manually. This means you are NOT using the client's built-in multi-threading. Setting `batch_size` in `client.batch.configure()` to an int value will enabled automatic batching. See: https://weaviate.io/developers/weaviate/current/restful-api-references/batch.html#example-request-1""", category=DeprecationWarning, stacklevel=1, )
[ 2663, 11103 ]
def METHOD_NAME ( objects, matchCollection, deltaRMax = 0.3 ): '''Univoque association of an element from matchCollection to an element of objects. Reco and Gen objects get the "matched" attribute, true is they are re part of a matched tulpe. By default, the matching is true only if delta R is smaller than 0.3. ''' pairs = {} if len(objects)==0: return pairs if len(matchCollection)==0: return dict( list(zip(objects, [None]*len(objects))) ) # build all possible combinations allPairs = sorted([(deltaR2 (object.eta(), object.phi(), match.eta(), match.phi()), (object, match)) for object in objects for match in matchCollection]) # to flag already matched objects # FIXME this variable remains appended to the object, I do not like it for object in objects: object.matched = False for match in matchCollection: match.matched = False deltaR2Max = deltaRMax * deltaRMax for dR2, (object, match) in allPairs: if dR2 > deltaR2Max: break if dR2 < deltaR2Max and object.matched == False and match.matched == False: object.matched = True match.matched = True pairs[object] = match for object in objects: if object.matched == False: pairs[object] = None return pairs # by now, the matched attribute remains in the objects, for future usage # one could remove it with delattr (object, attrname)
[ 590, 279, 16023 ]
def METHOD_NAME( faker: Faker, ) -> Callable[..., RabbitResourceTrackingStartedMessage]: def _creator(**kwargs: dict[str, Any]) -> RabbitResourceTrackingStartedMessage: msg_config = { "channel_name": "io.simcore.service.tracking", "service_run_id": faker.uuid4(), "created_at": datetime.now(timezone.utc), "message_type": RabbitResourceTrackingMessageType.TRACKING_STARTED, "wallet_id": faker.pyint(), "wallet_name": faker.pystr(), "pricing_plan_id": faker.pyint(), "pricing_detail_id": faker.pyint(), "product_name": "osparc", "simcore_user_agent": faker.pystr(), "user_id": faker.pyint(), "user_email": faker.email(), "project_id": faker.uuid4(), "project_name": faker.pystr(), "node_id": faker.uuid4(), "node_name": faker.pystr(), "service_key": "simcore/services/comp/itis/sleeper", "service_version": "2.1.6", "service_type": "computational", "service_resources": { "container": { "image": "simcore/services/comp/itis/sleeper:2.1.6", "resources": { "CPU": {"limit": 0.1, "reservation": 0.1}, "RAM": {"limit": 134217728, "reservation": 134217728}, }, "boot_modes": ["CPU"], } }, "service_additional_metadata": {}, **kwargs, } return RabbitResourceTrackingStartedMessage(**msg_config) return _creator
[ 236, 14107, 277, 447 ]
async def METHOD_NAME( connection: Connection, admin_structure_id: UUID, structure_id: UUID ) -> UUID | None: record = await connection.fetchrow( """ INSERT INTO public.admin_structure_structure(admin_structure_id, structure_id) VALUES ($1, $2) ON CONFLICT ON CONSTRAINT admin_structure_structure_admin_structure_id_structure_id_key DO UPDATE SET deleted_at = NULL RETURNING id """, # noqa: E501 admin_structure_id, structure_id, ) if record: return record["id"]
[ 408, 2870, 1011, 1011 ]
def METHOD_NAME(self): pass
[ 709, 710 ]
def METHOD_NAME(mock_run, parse_records, record_q): run = mock_run() metirc = run.define_metric( "metric", ) assert metirc.name == "metric" parsed = parse_records(record_q) assert len(parsed.records) == 1 assert len(parsed.metric) == 1
[ 9, 1341, 156 ]