code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def __init__(self, api_version=None, items=None, kind=None, metadata=None): <NEW_LINE> <INDENT> self._api_version = None <NEW_LINE> self._items = None <NEW_LINE> self._kind = None <NEW_LINE> self._metadata = None <NEW_LINE> self.discriminator = None <NEW_LINE> if api_version is not None: <NEW_LINE> <INDENT> self.api_ve...
IoK8sApiCoreV1List - a model defined in Swagger
625941c84f88993c3716c0dc
def get_conn(): <NEW_LINE> <INDENT> for name in GENERATOR_DICT: <NEW_LINE> <INDENT> print('api name set:', name) <NEW_LINE> if not hasattr(g, name): <NEW_LINE> <INDENT> setattr(g, name + '_cookies', eval('CookiesRedisClient' + '(name="' + name + '")')) <NEW_LINE> <DEDENT> <DEDENT> return g
创建对应db属性,返回当前访问的request :return:
625941c876e4537e8c3516e6
def __str__(self) -> str: <NEW_LINE> <INDENT> return json.dumps(self.to_dict(), indent=2)
Return a `str` version of this SearchResultMetadata object.
625941c882261d6c526ab512
def load_vect_post_to_net(self, vect_post): <NEW_LINE> <INDENT> from . import load_vect_post <NEW_LINE> load_vect_post.main(self, vect_post)
load vector format to network
625941c8f9cc0f698b140671
def CheckAutoSave(self): <NEW_LINE> <INDENT> if self._decider is None: <NEW_LINE> <INDENT> ImproveSaveLogger.fatal(Fore.LIGHTRED_EX + 'have not set decision_generator which is the method for ' 'decide save the model weight or not , if you have no plane to' 'complement the method you can use the default decision by call...
check the save can work or not :return: bool, True: model can save the weight. False: model is not necessary to save the weight(decide by the self._decision_generator
625941c8fbf16365ca6f6237
def get(self, seqid): <NEW_LINE> <INDENT> get_sequence(self.properties, self.g_request, self.g_response) <NEW_LINE> self.finalize_response()
Get sequence HTTP response
625941c8187af65679ca5193
def main(): <NEW_LINE> <INDENT> os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dailypythontip.settings') <NEW_LINE> try: <NEW_LINE> <INDENT> from django.core.management import execute_from_command_line <NEW_LINE> <DEDENT> except ImportError as exc: <NEW_LINE> <INDENT> raise ImportError( "Couldn't import Django. Are y...
Run administrative tasks.
625941c8fb3f5b602dac3707
def send_forgot_pin_email_by_email(self, forgot_pin_link_by_email_model, email_template=None, reset_pin_url=None): <NEW_LINE> <INDENT> if(forgot_pin_link_by_email_model is None): <NEW_LINE> <INDENT> raise Exception(self._lr_object.get_validation_message("forgot_pin_link_by_email_model")) <NEW_LINE> <DEDENT> query_param...
This API sends the reset pin email to specified email address. Args: forgot_pin_link_by_email_model: Model Class containing Definition for Forgot Pin Link By Email API email_template: Email template name reset_pin_url: Reset PIN Url Returns: Response containing Definition of Complete Validatio...
625941c857b8e32f5248350f
def gen_tx(self): <NEW_LINE> <INDENT> if not self.address: <NEW_LINE> <INDENT> raise StellarAddressInvalidError('Transaction does not have any source address.') <NEW_LINE> <DEDENT> if not self.sequence: <NEW_LINE> <INDENT> raise SequenceError('No sequence is present, maybe not funded?') <NEW_LINE> <DEDENT> tx = Transac...
Generate a :class:`Transaction <stellar_base.transaction.Transaction>` object from the list of operations contained within this object. :return: A transaction representing all of the operations that have been appended to this builder. :rtype: :class:`Transaction <stellar_base.transaction.Transaction>`
625941c84d74a7450ccd4238
@mock.patch('md_resume.convert_to_html') <NEW_LINE> def test_main(mock_convert_to_html): <NEW_LINE> <INDENT> sys.argv.clear() <NEW_LINE> sys.argv.extend(['garbage', 'input', 'output', '--style', 'stylesheet']) <NEW_LINE> md_resume.main() <NEW_LINE> mock_convert_to_html.assert_called_with( file_in='input', file_out='out...
Tests the argparsing of md_resume.
625941c8091ae35668666fd4
def read_linear_acceleration(self): <NEW_LINE> <INDENT> x, y, z = self._read_vector(self.BNO055_LINEAR_ACCEL_DATA_X_LSB_ADDR) <NEW_LINE> return (x/100.0, y/100.0, z/100.0)
Return the current linear acceleration (acceleration from movement, not from gravity) reading as a tuple of X, Y, Z values in meters/second^2.
625941c88c3a87329515842e
def hint_by_depth(puzzle, n): <NEW_LINE> <INDENT> if puzzle.is_solved(): <NEW_LINE> <INDENT> return 'Already at a solution!' <NEW_LINE> <DEDENT> soln = _get_sol_and_num_moves(puzzle) <NEW_LINE> if soln is not None: <NEW_LINE> <INDENT> if soln[1] > n: <NEW_LINE> <INDENT> soln = None <NEW_LINE> <DEDENT> <DEDENT> puzzles_...
Return a valid str representation of what the user would need to input to get a step closer to the solution. If <puzzle> is already solved, return the string 'Already at a solution!'. If <puzzle> cannot lead to a solution or other valid state within <n> moves, return the string 'No possible extensions!'. Precondition...
625941c82ae34c7f2600d1a6
def SetHyperText(self, hyper=True): <NEW_LINE> <INDENT> self._hypertext = hyper
Sets whether the item is hypertext or not.
625941c815fb5d323cde0b83
def _fn_3(date_str): <NEW_LINE> <INDENT> now = datetime.now() <NEW_LINE> formats = ['%d %b', '%b %d', '%d %B', '%B %d'] <NEW_LINE> for _format in formats: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> r = datetime.strptime(date_str, _format) <NEW_LINE> return datetime(now.year, r.month, r.day, 18, 0) <NEW_LINE> <DEDENT>...
Format dd mm; mm dd
625941c823e79379d52ee5da
def pchip_interpolate(xi, yi, x, der=0, axis=0): <NEW_LINE> <INDENT> P = PchipInterpolator(xi, yi, axis=axis) <NEW_LINE> if der == 0: <NEW_LINE> <INDENT> return P(x) <NEW_LINE> <DEDENT> elif _isscalar(der): <NEW_LINE> <INDENT> return P(x, der=der) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return [P(x, nu) for nu in...
Convenience function for pchip interpolation. xi and yi are arrays of values used to approximate some function f, with ``yi = f(xi)``. The interpolant uses monotonic cubic splines to find the value of new points x and the derivatives there. See `PchipInterpolator` for details. Parameters ---------- xi : array_like ...
625941c8a79ad161976cc1ba
def hash_roles(self, node): <NEW_LINE> <INDENT> res = hash(self.MODEL_CLASS) <NEW_LINE> for role in node.roles: <NEW_LINE> <INDENT> res += hash(str(role)) <NEW_LINE> <DEDENT> return hash(str(res))
Logic to extract hash from node's roles :param node: UAST node :return: hash of roles
625941c8d58c6744b4257cd5
def __init__( self, *, enabled: Optional[bool] = None, **kwargs ): <NEW_LINE> <INDENT> super(SmbMultichannel, self).__init__(**kwargs) <NEW_LINE> self.enabled = enabled
:keyword enabled: If SMB multichannel is enabled. :paramtype enabled: bool
625941c83cc13d1c6d3c73ef
def test_raises_unknown_module(self): <NEW_LINE> <INDENT> self.assertRaises(NonExistentModuleError, factorize, module='unknown', object_type='UnknownClass')
Test to raises exception when module and class don't exist in the module
625941c8f548e778e58cd5f2
def validate_dataset_xml(dataset: Union[str, Path]) -> ET.ElementTree: <NEW_LINE> <INDENT> dataset_path = str(dataset) <NEW_LINE> tree = ET.parse(dataset_path) <NEW_LINE> root = tree.getroot() <NEW_LINE> validate_dataset_tag(dataset_path, root) <NEW_LINE> dataset_type = root.attrib["type"] <NEW_LINE> Validator = valida...
Returns dataset ElementTree if the dataset has valid XML a DatasetValidationError will be thrown when a dataset is invalid with details about why it's invalid.
625941c850485f2cf553ce0e
def get_optimizer_class(optimizer_name, **kwargs): <NEW_LINE> <INDENT> assert isinstance( optimizer_name, str ), f"Expected string for optimizer_name but got {optimizer_name}." <NEW_LINE> optimizer_name = optimizer_name.lower() <NEW_LINE> if optimizer_name == "adam": <NEW_LINE> <INDENT> adam_args = ["lr", "betas", "eps...
get_optimizer_class(optimizer_name) Returns a torch optimizer according to the input string
625941c87cff6e4e811179fb
def p_expr_or_star_expr(self, p): <NEW_LINE> <INDENT> p[0] = p[1]
expr_or_star_expr : expr | star_expr
625941c845492302aab5e337
def __get_all_addons(self, obj): <NEW_LINE> <INDENT> from ..utils import ProgressMeter <NEW_LINE> pm = ProgressMeter(_("Install all Addons"), _("Installing..."), message_area=True) <NEW_LINE> pm.set_pass(total=len(self.addon_model)) <NEW_LINE> errors = [] <NEW_LINE> for row in self.addon_model: <NEW_LINE> <INDENT> pm.s...
Get all addons from the wiki and install them.
625941c807d97122c41788ff
def get_flatten_values(self): <NEW_LINE> <INDENT> def parse_value(value, masks): <NEW_LINE> <INDENT> assert len(masks) == 3 <NEW_LINE> feat_masks, id_masks, sparse_masks = masks <NEW_LINE> assert len(feat_masks) == 5 <NEW_LINE> assert len(id_masks) == 2 <NEW_LINE> assert len(sparse_masks) == 1 <NEW_LINE> values = self....
Get and reformat the raw flatten numpy values list from query.
625941c8dc8b845886cb55a9
def _prepare_invoice(self, cr, uid, order, lines, context=None): <NEW_LINE> <INDENT> if context is None: <NEW_LINE> <INDENT> context = {} <NEW_LINE> <DEDENT> res = super(sale_order,self)._prepare_invoice(cr, uid, order, lines, context) <NEW_LINE> user = self.pool.get('res.users').browse(cr, uid, uid) <NEW_LINE> if user...
Overwrite this method to send the payment term new to invoice
625941c821a7993f00bc7d63
def test_pcoords_sample_invalid_type(self): <NEW_LINE> <INDENT> with self.assertRaises(YellowbrickTypeError): <NEW_LINE> <INDENT> ParallelCoordinates(sample='foo')
Non-numeric values for 'sample' argument should raise.
625941c866656f66f7cbc21f
@pytest.fixture() <NEW_LINE> def db_session(request, settings): <NEW_LINE> <INDENT> engine = db.make_engine(settings) <NEW_LINE> db.bind_engine(engine, should_create=True, should_drop=True) <NEW_LINE> api_db.use_session(db.Session) <NEW_LINE> def destroy(): <NEW_LINE> <INDENT> transaction.commit() <NEW_LINE> db.Session...
SQLAlchemy session.
625941c8d6c5a102081440bf
@rename_keyword(color='rgbcolor') <NEW_LINE> @options(alpha=1, fill=False, thickness=1, rgbcolor=(0,0,0), zorder=2, linestyle='solid') <NEW_LINE> def bezier_path(path, **options): <NEW_LINE> <INDENT> from sage.plot.all import Graphics <NEW_LINE> g = Graphics() <NEW_LINE> g._set_extra_kwds(g._extract_kwds_for_show(optio...
Returns a Graphics object of a Bezier path corresponding to the path parameter. The path is a list of curves, and each curve is a list of points. Each point is a tuple ``(x,y)``. The first curve contains the endpoints as the first and last point in the list. All other curves assume a starting point given by the las...
625941c84f88993c3716c0dd
def _get_method_url(self, method): <NEW_LINE> <INDENT> return join(self._base_url, method)
Build base URL path :param method: Name of iMonnit API method. e.g. "Logon" or "SensorList" :return: Root URL path. e.g. https://www.imonnit.com/xml/Logon
625941c86fece00bbac2d7b3
def request_successful(self): <NEW_LINE> <INDENT> if 'errors' in self.result: <NEW_LINE> <INDENT> self._raise_error() <NEW_LINE> <DEDENT> return True
Returns true if request was successful
625941c8d164cc6175782dc2
@app.route('/') <NEW_LINE> @app.route('/index') <NEW_LINE> @login_required <NEW_LINE> def index(): <NEW_LINE> <INDENT> sort = request.args.get('sort') <NEW_LINE> way = request.args.get('way') <NEW_LINE> if way == '1': <NEW_LINE> <INDENT> way = 'desc' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> way = 'asc' <NEW_LINE> ...
Lists movies with status of 2 (ready for viewing)
625941c866656f66f7cbc220
def test_create_share_owning_other_company(self): <NEW_LINE> <INDENT> company1, company2 = factories.CompanyFactory.create_batch(size=2, game=self.game) <NEW_LINE> url = reverse('companyshare-list') <NEW_LINE> data = {'owner': company1.pk, 'company': company2.pk} <NEW_LINE> response = self.client.post(url, data) <NEW_L...
Ensure that companies can own shares in other companies.
625941c8e64d504609d748b5
def main(): <NEW_LINE> <INDENT> n = 99 <NEW_LINE> a = fill_a(n) <NEW_LINE> print("{}th approx to e's digit sum = {}".format( n + 1, sum(int(d) for d in str(find_numerator(a, n)))))
Find the sum of the 100th continued fraction numerator in the expansion of e. Note we start from n = 0 so we actually look for the n = 99 term.
625941c871ff763f4b5496ff
@debug_decorator <NEW_LINE> def process_yes_no_input(): <NEW_LINE> <INDENT> user_input = input().lower() <NEW_LINE> if user_input == "y" or user_input == "yes": <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif user_input == "n" or user_input =="no": <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> logger.in...
Processes input that shoul be either accept or decline return: (bool) True for accept, False for decline
625941c8cc0a2c11143dcf06
def get_current_formplayer_version(environment): <NEW_LINE> <INDENT> formplayer0 = environment.groups["formplayer"][0] <NEW_LINE> try: <NEW_LINE> <INDENT> res = requests.get(f"http://{formplayer0}:8081/info", timeout=5) <NEW_LINE> res.raise_for_status() <NEW_LINE> <DEDENT> except RequestException as e: <NEW_LINE> <INDE...
Get version of currently deployed Formplayer by querying the Formplayer management endpoint to get the build info.
625941c8de87d2750b85fe07
def test_echo_context_manager(self): <NEW_LINE> <INDENT> with forward_server.ForwardServer(None) as fwd: <NEW_LINE> <INDENT> self.assertTrue(fwd.running) <NEW_LINE> self.assertEqual(fwd.server_address_family, socket.AF_INET) <NEW_LINE> self.assertIsInstance(fwd.server_address, tuple) <NEW_LINE> self.assertEqual(len(fwd...
Basic echo test that context manager makes socket information available
625941c83eb6a72ae02ec550
def verify_capture_in_with_icmp_errors(self, capture, in_if, packet_num=3, icmp_type=11): <NEW_LINE> <INDENT> self.assertEqual(packet_num, len(capture)) <NEW_LINE> for packet in capture: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.assertEqual(packet[IP].dst, in_if.remote_ip4) <NEW_LINE> self.assertTrue(packet.has...
Verify captured packets with ICMP errors on inside network :param capture: Captured packets :param in_if: Inside interface :param packet_num: Expected number of packets (Default 3) :param icmp_type: Type of error ICMP packet we are expecting (Default 11)
625941c850485f2cf553ce0f
def get_next_raw(self, clean=True): <NEW_LINE> <INDENT> if self.raw_chunk_list == []: <NEW_LINE> <INDENT> return (None, None) <NEW_LINE> <DEDENT> if clean: <NEW_LINE> <INDENT> (next_start, next_end, next_time) = self.raw_chunk_list.pop(0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (next_start, next_end, next_time) =...
Get the next chunk of raw characters from the buffer, clearing all that comes before it. Default behavior is to clear the buffer before and including this data. @param clean Remove the buffer contents before and including this data @return A tuple of (timestamp, data_chunk) where timestamp is in NTP4 float...
625941c86aa9bd52df036e19
def eigsh(self, k=(0, 0, 0), n=10, gauge='R', eigvals_only=True, **kwargs): <NEW_LINE> <INDENT> spin = kwargs.pop('spin', 0) <NEW_LINE> dtype = kwargs.pop('dtype', None) <NEW_LINE> kwargs.update({'which': kwargs.get('which', 'SM')}) <NEW_LINE> if self.spin.kind == Spin.POLARIZED: <NEW_LINE> <INDENT> P = self.Pk(k=k, dt...
Calculates a subset of eigenvalues of the physical quantity (default 10) Setup the quantity and overlap matrix with respect to the given k-point and calculate a subset of the eigenvalues using the sparse algorithms. All subsequent arguments gets passed directly to :code:`scipy.linalg.eigsh` Parameters ---------- sp...
625941c8d164cc6175782dc3
def evaluate_on(self, data_sample): <NEW_LINE> <INDENT> mention = data_sample['word'] <NEW_LINE> gold_id = int(data_sample['wikiId']) <NEW_LINE> candidates = self._ball.get_stats_for_mention(mention) <NEW_LINE> self._total_count += 1 <NEW_LINE> if candidates is None: <NEW_LINE> <INDENT> self._bad_candidates += 1 <NEW_L...
Takes a single example - gets all candidate id's and uses the model to run inference. Does this by running the model on each candidate id, and picking one with the highest probability.
625941c8d486a94d0b98e1bb
def setcurrenttable(self, event): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> s = self.notebook.index(self.notebook.select()) <NEW_LINE> self.currenttable = self.sheets[s] <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return
Set the currenttable so that menu items work with visible sheet
625941c855399d3f05588729
def _get_buildout_script_paths(search_path: Path): <NEW_LINE> <INDENT> project_root = _get_parent_dir_with_file(search_path, 'buildout.cfg') <NEW_LINE> if not project_root: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> bin_path = project_root.joinpath('bin') <NEW_LINE> if not bin_path.exists(): <NEW_LINE> <INDENT> ret...
if there is a 'buildout.cfg' file in one of the parent directories of the given module it will return a list of all files in the buildout bin directory that look like python files. :param search_path: absolute path to the module. :type search_path: str
625941c88e71fb1e9831d81f
@pytest.fixture() <NEW_LINE> def init_admin_api(request): <NEW_LINE> <INDENT> print("\nAPI logining...") <NEW_LINE> env = request.config.getoption('--testenv') <NEW_LINE> cfg = get_config(env) <NEW_LINE> init.api_login(cfg) <NEW_LINE> print("Initializing api sets...") <NEW_LINE> Config.COMMON = Common()
初始化API模块 :param request:
625941c83539df3088e2e3c0
def test_rush(self): <NEW_LINE> <INDENT> rusher = Rusher(self._sleepy_worker, 1) <NEW_LINE> _, results = rusher.rush() <NEW_LINE> self.assertEqual(sorted(results), [0]) <NEW_LINE> rusher.thread_count = 2 <NEW_LINE> _, results = rusher.rush() <NEW_LINE> self.assertEqual(sorted(results), [0, 1])
Check that a rush without a timeout works as expected.
625941c8a79ad161976cc1bb
def following(self, username): <NEW_LINE> <INDENT> ampache_url = self.AMPACHE_URL + '/server/' + self.AMPACHE_API + '.server.php' <NEW_LINE> data = {'action': 'following', 'auth': self.AMPACHE_SESSION, 'username': username} <NEW_LINE> data = urllib.parse.urlencode(data) <NEW_LINE> full_url = ampache_url + '?' + data <N...
following MINIMUM_API_VERSION=380001 This get the user list followed by an user INPUTS * username =
625941c84428ac0f6e5ba867
def derivative(func, xmax=100, n=100, power=1): <NEW_LINE> <INDENT> x = np.linspace(0, xmax, n, endpoint=True) <NEW_LINE> f = np.vectorize(func) <NEW_LINE> Df = np.linalg.matrix_power(gradient(x), power) @ f(x) <NEW_LINE> return Df
derivative(func, n=100) function description: computes the the derivative to some power of some function func for n domain points Args: func - the function to compute the derivative of n - the number of domain points (defaults to 100) power - the power to compute the derivative to (defaults to 1) (ex. pow...
625941c8627d3e7fe0d68ec5
def pytest_configure(config): <NEW_LINE> <INDENT> if config.getoption('gae_sdk') is not None: <NEW_LINE> <INDENT> set_up_gae_environment(config.getoption('gae_sdk'))
Configures the App Engine SDK imports on py.test startup.
625941c8498bea3a759b9b24
def as_class_name(*args, **kwargs): <NEW_LINE> <INDENT> return delimited_to_camelcase(*args, **kwargs)
Convert string into a CamelCase class name.
625941c88da39b475bd64fe8
def testTicket617(self): <NEW_LINE> <INDENT> im = afwImage.ImageD(afwGeom.Extent2I(100, 100)) <NEW_LINE> im.set(666) <NEW_LINE> mi = afwImage.MaskedImageD(im)
Test reading an F64 image and converting it to a MaskedImage
625941c891f36d47f21ac567
def test_delasport(self): <NEW_LINE> <INDENT> expected, rolls = generate_rolls(copy.deepcopy(DELASPORT_ROLLS)) <NEW_LINE> score = generate(rolls) <NEW_LINE> validate_score(self, expected, score)
Test score generator returns expected scores from Delasport taks
625941c8167d2b6e31218c0c
def segment_watershed(image, window=None): <NEW_LINE> <INDENT> import cv2 <NEW_LINE> import numpy as np <NEW_LINE> if window: <NEW_LINE> <INDENT> subimage = np.array(image) <NEW_LINE> x, y, w, h = window <NEW_LINE> image = subimage[y:y + h, x:x + w] <NEW_LINE> <DEDENT> rects, display = segment_edges(image, variance_thr...
Segments an image using watershed technique. Parameters ---------- image : (M, N, 3) array Image to process. window : tuple, (x, y, w, h) Optional subwindow in image. Returns ------- (rects, display) : list, (M, N, 3) array Region results and visualization image.
625941c830c21e258bdfa512
def logout(self): <NEW_LINE> <INDENT> result = { 'status': False, 'errLog': '' } <NEW_LINE> try: <NEW_LINE> <INDENT> self.channel.close() <NEW_LINE> self.isLogin = False <NEW_LINE> result['status'] = True <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> result['status'] = False <NEW_LINE> result['content'...
Logout method A session used to log out of a target device
625941c88a349b6b435e81e9
def pc_work_time_avg(self): <NEW_LINE> <INDENT> return _qtgui_swig.const_sink_c_sptr_pc_work_time_avg(self)
pc_work_time_avg(const_sink_c_sptr self) -> float
625941c84428ac0f6e5ba868
def r1_select_best_cell(self, ca): <NEW_LINE> <INDENT> neighborhood = ca.get_empty_agent_neighborhood(self.x, self.y, self.vision) <NEW_LINE> best_cells = list() <NEW_LINE> max_dist = 0 <NEW_LINE> max_w = 0 <NEW_LINE> for cell in list(neighborhood.values()): <NEW_LINE> <INDENT> if not best_cells: <NEW_LINE> <INDENT> be...
Agent selects the best cell to move to, according to: its resources, occupier and tribal alignment.
625941c8c4546d3d9de72aa9
def tune_zero_thresh(self, image): <NEW_LINE> <INDENT> cv2.namedWindow('To Zero Threshold') <NEW_LINE> cv2.createTrackbar('threshold', 'To Zero Threshold', 0, 255, self.nothing) <NEW_LINE> key = 0 <NEW_LINE> while key != 13: <NEW_LINE> <INDENT> key = cv2.waitKey(1) <NEW_LINE> self.thresh_val = cv2.getTrackbarPos('thres...
Brings up a window with track bar to adjust threshold value.
625941c82c8b7c6e89b35837
def maximalSquare(self, matrix): <NEW_LINE> <INDENT> m = len(matrix) <NEW_LINE> if m == 0: return 0 <NEW_LINE> n = len(matrix[0]) <NEW_LINE> area = 0 <NEW_LINE> for i in range(m): <NEW_LINE> <INDENT> for j in range(n): <NEW_LINE> <INDENT> matrix[i][j] = int(matrix[i][j]) <NEW_LINE> <DEDENT> <DEDENT> for i in range(m): ...
:type matrix: List[List[str]] :rtype: int
625941c821a7993f00bc7d64
def tabChanged(self, index) : <NEW_LINE> <INDENT> self.tabs.setCurrentIndex(index) <NEW_LINE> self.table = self.tabs.currentWidget()
Keep track og current tabs and table index - take the index of current tab
625941c8cdde0d52a9e530a8
def roll_doubles(self): <NEW_LINE> <INDENT> not_doubles = True <NEW_LINE> while not_doubles: <NEW_LINE> <INDENT> roll1 = self.die1.roll() <NEW_LINE> roll2 = self.die2.roll() <NEW_LINE> print(roll1, roll2) <NEW_LINE> if roll1 == roll2: <NEW_LINE> <INDENT> not_doubles = False
The roll_doubles method that will roll die1 and die2 (attributes from constructor method), display rolled values,and continue iterating until a double is rolled.
625941c891f36d47f21ac568
def register_click(self, event): <NEW_LINE> <INDENT> if self.the_grid and self.the_grid[0]: <NEW_LINE> <INDENT> ratio = self.size // (max(len(self.the_grid), len(self.the_grid[0])) + 1) <NEW_LINE> if 0 <= event.y // ratio - 1 < len(self.the_grid[0]) and 0 <= event.x // ratio - 1 < len(self.the_grid): <NEW_LINE> <INDENT...
event.x and event.y contain the position, compute the x, y location and then check if something needs to be done
625941c81f037a2d8b946274
def _get_script_links(self): <NEW_LINE> <INDENT> links = [] <NEW_LINE> for item in self.__script: <NEW_LINE> <INDENT> links.append('\n<script>\n%s\n</script>' % Settings.get('js').get(item)) <NEW_LINE> <DEDENT> return ''.join(links)
Return the html formatted javascript.
625941c80fa83653e4657032
def set_address(self, address: int, defer: bool = False): <NEW_LINE> <INDENT> self.address = address <NEW_LINE> self.backend.set_address(address, defer)
Updates the device's knowledge of its own address. Parameters: address -- The address to apply. defer -- If true, the address change should be deferred until the next time a control request ends. Should be set if we're changing the address before we ack the releva...
625941c8d7e4931a7ee9df93
def convert_pybites_chars(text): <NEW_LINE> <INDENT> result = ''.join([i.swapcase() if i.lower() in PYBITES else i for i in text]) <NEW_LINE> return result
Swap case all characters in the word pybites for the given text. Return the resulting string.
625941c81f5feb6acb0c4bc7
def test_ov_function_with_full_data(self): <NEW_LINE> <INDENT> self.assertTrue(ov(qualifiedov))
"all dictionary fields are well supplied with the required data
625941c84c3428357757c39e
def run_validator(pattern): <NEW_LINE> <INDENT> parseErrListener = STIXPatternErrorListener() <NEW_LINE> lexer = STIXPatternLexer(pattern) <NEW_LINE> lexer.removeErrorListeners() <NEW_LINE> stream = CommonTokenStream(lexer) <NEW_LINE> parser = STIXPatternParser(stream) <NEW_LINE> parser.removeErrorListeners() <NEW_LINE...
Validates a pattern against the STIX Pattern grammar. Error messages are returned in a list. The test passed if the returned list is empty.
625941c892d797404e304200
def add_piece(self, piece): <NEW_LINE> <INDENT> pid = piece.get_id() <NEW_LINE> if pid in self._pieces.keys(): <NEW_LINE> <INDENT> raise ValueError("Piece ID already exists") <NEW_LINE> <DEDENT> p_x_start = piece.get_x() <NEW_LINE> p_y_start = piece.get_y() <NEW_LINE> p_x_end = p_x_start + piece.get_width() <NEW_LINE> ...
Add a piece to the board :param piece: :return:
625941c824f1403a92600bdd
def get_contract_open_orders(self, symbol=None, page_index=None, page_size=50): <NEW_LINE> <INDENT> params = {} <NEW_LINE> if symbol: <NEW_LINE> <INDENT> params["symbol"] = symbol <NEW_LINE> <DEDENT> if page_index: <NEW_LINE> <INDENT> params["page_index"] = page_index <NEW_LINE> <DEDENT> if page_size: <NEW_LINE> <INDEN...
参数名称 是否必须 类型 描述 symbol false string "BTC","ETH"... page_index false int 第几页,不填第一页 page_size false int 不填默认20,不得多于50
625941c8d10714528d5ffd58
def evaluate(self, case: Any) -> None: <NEW_LINE> <INDENT> output = evaluate_cow( self.target.stream, self.get("input_file", default=None), self.geti("cow_timeout", default=1), ) <NEW_LINE> if output: <NEW_LINE> <INDENT> self.manager.register_data(self, output)
Evaluate the target. Run the target as Cow code and give the standard output results to Katana. :param case: A case returned by ``enumerate``. For this unit, the ``enumerate`` function is not used. :return: None. This function should not return any data.
625941c896565a6dacc8f742
def doi(self: BaseEntryExtension, dois: Dict[str, str]) -> None: <NEW_LINE> <INDENT> self.__arxiv_doi = dois
Assign the doi value to this entry. Parameters ---------- list The new list of DOI assignments.
625941c8d7e4931a7ee9df94
def create_papers_by_year_list(self): <NEW_LINE> <INDENT> _papers_by_year = self._references_by_year <NEW_LINE> _papers_by_year_str = "" <NEW_LINE> _previous_year = 0 <NEW_LINE> for paper in _papers_by_year: <NEW_LINE> <INDENT> if paper.year != _previous_year: <NEW_LINE> <INDENT> _papers_by_year_str += "\n### {0}\n\n"....
Create the "Papers by Year" section by sorting `self.references` by year. :return: A string representing the "Papers by Year" section.
625941c8187af65679ca5195
def test_buildBinaryCodeMEMR(self): <NEW_LINE> <INDENT> text = "MEMR [1] $B $C" <NEW_LINE> arglist = text.split()[1:] <NEW_LINE> instruction = self.parser._findInstructionCode("InsWidthRegReg", text.split()[0]) <NEW_LINE> instruction += self.parser._buildBinaryCode(STATE8, arglist) <NEW_LINE> self.assertEqual(instructi...
Tests the method: _buildBinaryCodeFromInstructionAndArguments(self, ins, state, arglist, instruction) for the MEMR instruction
625941c8711fe17d825423e4
def test_gas_timeout(dev, apdev): <NEW_LINE> <INDENT> hapd = start_ap(apdev[0]) <NEW_LINE> bssid = apdev[0]['bssid'] <NEW_LINE> dev[0].scan(freq="2412") <NEW_LINE> hapd.set("ext_mgmt_frame_handling", "1") <NEW_LINE> anqp_get(dev[0], bssid, 263) <NEW_LINE> ev = hapd.wait_event(["MGMT-RX"], timeout=5) <NEW_LINE> if ev is...
GAS timeout
625941c8566aa707497f45e1
def delta_consumption(m, utility, cons_tree, cost_tree, delta_m): <NEW_LINE> <INDENT> m_copy = m.copy() <NEW_LINE> m_copy[0] += delta_m <NEW_LINE> tree_dict = utility.utility(m_copy, return_trees=True) <NEW_LINE> new_cons_tree = tree_dict['Consumption'] <NEW_LINE> new_cost_tree = tree_dict['Cost'] <NEW_LINE> new_utilit...
Calculate the changes in consumption and the mitigation cost component of consumption when increasing period 0 mitigiation with `delta_m`. Parameters ---------- m : ndarray or list array of mitigation utility : `Utility` object object of utility class cons_tree : `BigStorageTree` object consumption storag...
625941c85e10d32532c5ef9d
def __init__(self): <NEW_LINE> <INDENT> self.Total = None <NEW_LINE> self.Items = None <NEW_LINE> self.RequestId = None
:param Total: Number of eligible entries. :type Total: int :param Items: List of returned results. Note: This field may return null, indicating that no valid values can be obtained. :type Items: list of DeployGroupInfo :param RequestId: The unique request ID, which is returned fo...
625941c8091ae35668666fd6
def island_perimeter(grid): <NEW_LINE> <INDENT> width = len(grid[0]) <NEW_LINE> height = len(grid) <NEW_LINE> edges = 0 <NEW_LINE> size = 0 <NEW_LINE> for i in range(height): <NEW_LINE> <INDENT> for j in range(width): <NEW_LINE> <INDENT> if grid[i][j] == 1: <NEW_LINE> <INDENT> size += 1 <NEW_LINE> if (j > 0 and grid[i]...
Return the perimiter of an island. The grid represents water by 0 and land by 1. Args: grid (list): A list of list of integers representing an island. Returns: The perimeter of the island defined in grid.
625941c8be7bc26dc91cd678
def _find_service(self, typ, authority): <NEW_LINE> <INDENT> geniutil = pm.getService('geniutil') <NEW_LINE> for service in self._delegate_tools.get_registry()['SERVICES']: <NEW_LINE> <INDENT> sauth, styp, sname = geniutil.decode_urn(service['service_urn']) <NEW_LINE> if (service['service_type'] == typ) and (sauth == a...
Returns the first service dictionary matching the {typ}e and {urn}. None if none is found.
625941c8bde94217f3682e68
def predict(self, X): <NEW_LINE> <INDENT> return self.results().predict(X)
Compute the predictions. Arguments: X: the features.
625941c80383005118ecf659
def find_regions(self): <NEW_LINE> <INDENT> class_for_each_edges = dict() <NEW_LINE> for edg in self.edges: <NEW_LINE> <INDENT> edge_class = edg.edge_class <NEW_LINE> class_for_each_edges[(edg.from_n, edg.to_n)] = edge_class <NEW_LINE> class_for_each_edges[(edg.to_n, edg.from_n)] = edge_class <NEW_LINE> <DEDENT> self.d...
Find regions - walk over edges in dfs order and fill in regions for each edge.
625941c8a17c0f6771cbe0c7
def load_config(config_name): <NEW_LINE> <INDENT> return importlib.import_module('configs.%s' % config_name).config
Load the config from its name.
625941c8046cf37aa974cdbf
@task <NEW_LINE> @timed <NEW_LINE> def restore(): <NEW_LINE> <INDENT> log.info('Restoring snapshots for lab %s' % LAB) <NEW_LINE> vms = local("virsh list --name --all | grep '%s'" % LAB_ID, capture=True) <NEW_LINE> for vm in vms.stdout.splitlines(): <NEW_LINE> <INDENT> local("virsh snapshot-revert {vm} original".format...
Restore all snapshotted VMs from current lab
625941c8925a0f43d2549eed
def redraw(): <NEW_LINE> <INDENT> global bar <NEW_LINE> bar.clear()
Invoked when redraw is needed, feel free to replace this completely
625941c8442bda511e8be490
def test_CurrentDipoleMoment_00(self): <NEW_LINE> <INDENT> cell = get_cell(n_seg=3) <NEW_LINE> cdm = lfp.CurrentDipoleMoment(cell) <NEW_LINE> M = cdm.get_transformation_matrix() <NEW_LINE> imem = np.array([[-1., 1.], [0., 0.], [1., -1.]]) <NEW_LINE> P = M @ imem <NEW_LINE> P_gt = np.array([[0., 0.], [0., 0.], [2., -2.]...
test CurrentDipoleMoment
625941c8a05bb46b383ec899
@with_setup(pretest, posttest) <NEW_LINE> @retry_on_except() <NEW_LINE> def test_iter_overhead_simplebar_hard(): <NEW_LINE> <INDENT> total = int(1e4) <NEW_LINE> with closing(MockIO()) as our_file: <NEW_LINE> <INDENT> a = 0 <NEW_LINE> with relative_timer() as time_tqdm: <NEW_LINE> <INDENT> for i in trange(total, file=ou...
Test overhead of iteration based tqdm vs simple progress bar (hard)
625941c80c0af96317bb825e
def OutliersMedian(df): <NEW_LINE> <INDENT> import pandas as pd <NEW_LINE> import numpy as np <NEW_LINE> for i in df.describe().columns: <NEW_LINE> <INDENT> Q1=df.describe().at['25%',i] <NEW_LINE> Q3=df.describe().at['75%',i] <NEW_LINE> IQR=Q3 - Q1 <NEW_LINE> LTV=Q1 - 1.5 * IQR <NEW_LINE> UTV=Q3 + 1.5 * IQR <NEW_LINE> ...
Calcualtes the IQR for each column then replaces any values outside that with the median
625941c850812a4eaa59c399
def test_creation_time(self, amplitude, amp_series): <NEW_LINE> <INDENT> assert amp_series["creation_time"] == to_datetime64( amplitude.creation_info.creation_time ) <NEW_LINE> assert amp_series["author"] == amplitude.creation_info.author <NEW_LINE> assert amp_series["agency_id"] == amplitude.creation_info.agency_id
Ensure creation time was included.
625941c8b5575c28eb68e076
def __call__(self, val): <NEW_LINE> <INDENT> lookup_tag = gdb.types.get_basic_type(val.type).tag <NEW_LINE> if not lookup_tag: <NEW_LINE> <INDENT> lookup_tag = val.type.name <NEW_LINE> <DEDENT> if not lookup_tag: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> index = find_match_brackets(lookup_tag) <NEW_LINE> if i...
Return matched printer type.
625941c8507cdc57c6306d50
@pytest.mark.parametrize( 'privileged_user', [{ None: ['edit_combatant_info']}], indirect=True ) <NEW_LINE> def test_authorizations_unauthorized(app, combatant, privileged_user): <NEW_LINE> <INDENT> pass
Test adding authorizations.
625941c85166f23b2e1a51d0
def _save_skill_opportunities(skill_opportunities): <NEW_LINE> <INDENT> skill_opportunity_models = [] <NEW_LINE> for skill_opportunity in skill_opportunities: <NEW_LINE> <INDENT> skill_opportunity.validate() <NEW_LINE> model = opportunity_models.SkillOpportunityModel( id=skill_opportunity.id, skill_description=skill_op...
Saves SkillOpportunity domain objects into datastore as SkillOpportunityModel objects. Args: skill_opportunities: list(SkillOpportunity). A list of SkillOpportunity domain objects.
625941c84e696a04525c94c2
def requires(self, *requirements): <NEW_LINE> <INDENT> if not self.jobs: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> self.jobs[0].requires(*requirements)
Adds requirements to the sequence, so that is to say, to the first job in the sequence. Parameters: requirements: each must be a ``Schedulable`` object.
625941c8a79ad161976cc1bc
def areAlmostEqual1(self, s1, s2): <NEW_LINE> <INDENT> if s1 == s2: return True <NEW_LINE> s1_diff = [] <NEW_LINE> s2_diff = [] <NEW_LINE> for i in range(len(s1)): <NEW_LINE> <INDENT> if s1[i] != s2[i]: <NEW_LINE> <INDENT> s1_diff.append(s1[i]) <NEW_LINE> s2_diff.append(s2[i]) <NEW_LINE> <DEDENT> if len(s1_diff)>2: ret...
:type s1: str :type s2: str :rtype: bool
625941c823e79379d52ee5db
def ensure_reverse_path_filtering(reason=''): <NEW_LINE> <INDENT> error_list = [] <NEW_LINE> command = "sysctl net.ipv4.conf.all.rp_filter 2> /dev/null" <NEW_LINE> output = _execute_shell_command(command, python_shell=True) <NEW_LINE> if output.strip() == '': <NEW_LINE> <INDENT> error_list.append("net.ipv4.conf.all.rp_...
Ensure Reverse Path Filtering is enabled
625941c807d97122c4178900
def test_chain_expected_transitions(self): <NEW_LINE> <INDENT> T = np.array([ [.1, .6, .3], [.1, .1, .8], [.8, .1, .1]]) <NEW_LINE> nstates = len(T) <NEW_LINE> nsteps = 5 <NEW_LINE> transition_object = TransitionMatrix.MatrixTransitionObject(T) <NEW_LINE> chain = Chain(transition_object) <NEW_LINE> for i_state, e_state...
Compare brute force results to dynamic programming results.
625941c85e10d32532c5ef9e
def hour_from_time(t): <NEW_LINE> <INDENT> return (t // MS_PER_HOUR) % HOURS_PER_DAY
The 0-based hour in the day the given time falls within. 15.9.1.10
625941c8ab23a570cc2501f9
def predict_labels(self, dists, k=1): <NEW_LINE> <INDENT> num_test = dists.shape[0] <NEW_LINE> y_pred = np.zeros(num_test) <NEW_LINE> for i in range(num_test): <NEW_LINE> <INDENT> closest_y = [] <NEW_LINE> pass <NEW_LINE> closest_y=self.y_train[np.argsort(dists[i])[:k]] <NEW_LINE> pass <NEW_LINE> y_pred[i]=np.argmax(np...
Given a matrix of distances between test points and training points, predict a label for each test point. Inputs: - dists: A numpy array of shape (num_test, num_train) where dists[i, j] gives the distance betwen the ith test point and the jth training point. Returns: - y: A numpy array of shape (num_test,) containi...
625941c8d99f1b3c44c67606
def __create_lake(self, ilat, ilon, zz): <NEW_LINE> <INDENT> lout = [] <NEW_LINE> limx, limy = zz.shape <NEW_LINE> invalid = [[ilat,ilon]] <NEW_LINE> pool = [[[ilat,ilon]]] <NEW_LINE> pring = 1.0 <NEW_LINE> pfill = .99 <NEW_LINE> pfactor = .7 <NEW_LINE> while True: <NEW_LINE> <INDENT> fillable = False <NEW_LINE> lpool ...
Create a lake around coordinate
625941c8287bf620b61d3adb
def _bias(self, x, name="bias"): <NEW_LINE> <INDENT> with tf.variable_scope(name): <NEW_LINE> <INDENT> params_shape = [x.get_shape()[-1]] <NEW_LINE> beta = tf.get_variable("beta", params_shape, tf.float32, initializer=tf.constant_initializer(0.0)) <NEW_LINE> self.variables_list.append(beta) <NEW_LINE> self.trainable_li...
Bias term.
625941c88e71fb1e9831d820
@contextmanager <NEW_LINE> def get_output(command=None, **kwargs): <NEW_LINE> <INDENT> if command is None: <NEW_LINE> <INDENT> command = TEST_COMMAND <NEW_LINE> <DEDENT> kwargs.setdefault('logger', LoggerReplacement()) <NEW_LINE> cmd = commands.Output(command, **kwargs) <NEW_LINE> try: <NEW_LINE> <INDENT> yield cmd <NE...
Create an Output for testing
625941c8f548e778e58cd5f4
def fallback_to_all(self, response, source, only_ids=False): <NEW_LINE> <INDENT> if len(response['products']) > 0: <NEW_LINE> <INDENT> response.update(source=source) <NEW_LINE> return response <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response = format_es_response( self.es_client.get_products_list([], 0, 10), only_...
fallback_to_all matches all products in elasticsearch
625941c8dc8b845886cb55ab
def parse(s, name=None): <NEW_LINE> <INDENT> tokens = lex(s, name=name) <NEW_LINE> result = [] <NEW_LINE> while tokens: <NEW_LINE> <INDENT> next, tokens = parse_expr(tokens, name) <NEW_LINE> result.append(next) <NEW_LINE> <DEDENT> return result
Parses a string into a kind of AST >>> parse('{{x}}') [('expr', (1, 3), 'x')] >>> parse('foo') ['foo'] >>> parse('{{if x}}test{{endif}}') [('cond', (1, 3), ('if', (1, 3), 'x', ['test']))] >>> parse('series->{{for x in y}}x={{x}}{{endfor}}') ['series->', ('for', (1, 11), ('x',), 'y', ['x...
625941c8097d151d1a222ed1
def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.id: <NEW_LINE> <INDENT> self.publish_date = datetime.today() <NEW_LINE> <DEDENT> self.modify_date = datetime.now() <NEW_LINE> self.slug = datetime.now() <NEW_LINE> super(Stakeholders, self).save(*args, **kwargs)
On save, update timestamps
625941c8d53ae8145f87a2e8
def testTruncate(self): <NEW_LINE> <INDENT> for size in range(0, self.TEST_FILE_SIZE + self.TEST_FILE_BLOCK_SIZE, self.TEST_FILE_BLOCK_SIZE): <NEW_LINE> <INDENT> sparse_file = self._clone_sparse_file() <NEW_LINE> ih = avbtool.ImageHandler(sparse_file.name) <NEW_LINE> ih.truncate(size) <NEW_LINE> unsparse_file = self._u...
Checks that we can truncate a sparse file correctly.
625941c8656771135c3eb8e5
def _get_not_configured_usage_tracker_path(): <NEW_LINE> <INDENT> return Path(get_cache_dir()).joinpath('thefuck.last_not_configured_run')
Returns path of special file where we store latest shell pid.
625941c821a7993f00bc7d65