code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def test_document_fallback_with_translation(self): <NEW_LINE> <INDENT> r = revision(save=True, content='Test', is_approved=True) <NEW_LINE> d2 = document(parent=r.document, locale='fr', slug='french', save=True) <NEW_LINE> revision(document=d2, is_approved=False, save=True) <NEW_LINE> url = reverse('wiki.document', arg...
The document template falls back to English if translation exists but it has no approved revisions.
625941d126068e7796caee81
def value_from_resource(value, adminUser): <NEW_LINE> <INDENT> if str(value) == 'resourceid:admin': <NEW_LINE> <INDENT> value = str(adminUser['_id']) <NEW_LINE> <DEDENT> elif str(value).startswith('resourceid:'): <NEW_LINE> <INDENT> resource = path_util.lookUpPath(value.split(':', 1)[1], force=True)['document'] <NEW_LI...
If a value is a string that startwith 'resource:', it is a path to an existing resource. Fetch it an return the string of the _id. :param value: a value :returns: the original value it is not a resource, or the string id of the resource.
625941d1d164cc6175782eef
def test_company_2_addresses(self): <NEW_LINE> <INDENT> with mock_api(company_2_addresses): <NEW_LINE> <INDENT> import_record(self.session, 'magento.res.partner', self.backend_id, '9999257') <NEW_LINE> <DEDENT> partner = self.model.search([('magento_id', '=', '9999257'), ('backend_id', '=', self.backend_id)]) <NEW_LINE...
Import an company (b2b) with 2 addresses
625941d1eab8aa0e5d26dcf9
def establish_connection(self): <NEW_LINE> <INDENT> conninfo = self.client <NEW_LINE> for name, default_value in items(self.default_connection_params): <NEW_LINE> <INDENT> if not getattr(conninfo, name, None): <NEW_LINE> <INDENT> setattr(conninfo, name, default_value) <NEW_LINE> <DEDENT> <DEDENT> if conninfo.ssl: <NEW_...
Establish connection to the AMQP broker.
625941d17047854f462a15a9
def get_multiple_days_of_minute_bars_as_list_of_bt_data_feeds(self, symbol, date_list, use_rth=1): <NEW_LINE> <INDENT> data_list = [] <NEW_LINE> for date in date_list: <NEW_LINE> <INDENT> print("calling get_a_date for: {}".format(date)) <NEW_LINE> df = self.get_a_day_of_minute_bars_as_a_dataframe(symbol, date.year, dat...
:param symbol: :param date_list: list. list of datetimes :param use_rth: 1 if data from only regular trading hours should be returned. 0 if before/ after market hours data should be returned. :return: A list of pandas dataframes (DF), one per year. Each DF contains columns: 'Date', 'Open', 'High', 'Low', 'Close', 'Volu...
625941d1498bea3a759b9c4f
def isSymmetric(self, root): <NEW_LINE> <INDENT> que = deque() <NEW_LINE> que.append(root) <NEW_LINE> while len(que): <NEW_LINE> <INDENT> level = [] <NEW_LINE> for i in range(len(que)): <NEW_LINE> <INDENT> popNode = que.popleft() <NEW_LINE> if popNode != None: <NEW_LINE> <INDENT> level.append(popNode.val) <NEW_LINE> <D...
:type root: TreeNode :rtype: bool
625941d107d97122c4178a2e
def test_create_error(new_session): <NEW_LINE> <INDENT> from .views.default import home <NEW_LINE> result = home(dummy_http_request_post('', '', '', new_session)) <NEW_LINE> assert result['error_msg'] == "Can't submit empry entry"
Test if an error msg shows up on the page in case an empty entry on the new_entry page is submitted.
625941d176d4e153a657ecd2
def _vhost_ready_event(self, iface): <NEW_LINE> <INDENT> LOG.debug("vhost online: %s", str(iface)) <NEW_LINE> self._notify_connected(iface.sw_if_index)
Callback from VPP interface on vhostuser socket connection
625941d1b5575c28eb68e1a1
def export_data(self, save_location): <NEW_LINE> <INDENT> selection = self.layer_view.get_selection() <NEW_LINE> model, row_list = selection.get_selected_rows() <NEW_LINE> def iterate_over_planes(model, path, itr): <NEW_LINE> <INDENT> r = model[path] <NEW_LINE> writer.writerow({"dip-direction": r[0], "dip": r[1], "stra...
Exports data to a location that is passes by the FileExportDialog. This method receives a save_location from the FileExportDialog class. A CSV file is created at that location. Depending on the layer type a different header is written to the file and it then iterates over all rows.
625941d1a934411ee3751834
def p_equality(self, p): <NEW_LINE> <INDENT> if len(p) > 2: <NEW_LINE> <INDENT> p[0] = self.factory.createCall(p[2], self.factory.createTuple([ p[1], p[3] ])) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p[0] = p[1]
equality : equality EQ cmp | equality NE cmp | cmp
625941d132920d7e50b28372
def is_running(args, programs, timeout=300, sleep_before_retry=1): <NEW_LINE> <INDENT> print("Looking for programs to appear in the VM (timeout: " + str(timeout) + "): " + ", ".join(programs)) <NEW_LINE> ssh_works = False <NEW_LINE> end = time.monotonic() + timeout <NEW_LINE> last_try = 0 <NEW_LINE> while last_try < en...
Simple check that looks for program names in the output of "ps ax". This is error-prone, only use it with programs that have a unique name. With defaults timeout and sleep_before_retry values, it will try keep trying for 5 minutes, but not more than once per second. :param programs: list of programs to check for, e.g....
625941d1b57a9660fec33a25
@require_http_methods(["GET"]) <NEW_LINE> @protect_view("indexview", required_level=Browser.L_STRONG, admin_only=True) <NEW_LINE> def indexview(request, **kwargs): <NEW_LINE> <INDENT> custom_log(request, "Admin: frontpage") <NEW_LINE> ret = {} <NEW_LINE> ret["users"] = User.objects.all().count() <NEW_LINE> ret["browser...
Main page. If keyword argument body_only is set, returns only main content, excluding menus.
625941d18c3a87329515855c
def run_training(datasets): <NEW_LINE> <INDENT> with tf.Graph().as_default(): <NEW_LINE> <INDENT> placeholders = placeholder_inputs(FLAGS.batch_size, datasets.emb_size) <NEW_LINE> inputs_placeholder, labels_placeholder, mask_placeholder = placeholders <NEW_LINE> logits = ops.inference(inputs_placeholder, datasets.emb_s...
Train the autoencoder for a number of steps.
625941d13eb6a72ae02ec680
def remove_tokens(page, tokens): <NEW_LINE> <INDENT> for token in tokens: <NEW_LINE> <INDENT> page = list(filter((token).__ne__, page)) <NEW_LINE> <DEDENT> if ' ' in ''.join(page): <NEW_LINE> <INDENT> text_aux = '' <NEW_LINE> for pag in ''.join(page).split(' '): <NEW_LINE> <INDENT> if pag: <NEW_LINE> <INDENT> text_aux...
Remove tokens from the page.
625941d1377c676e91272349
def orbit(self, f, N, **kwds): <NEW_LINE> <INDENT> from sage.misc.superseded import deprecation <NEW_LINE> deprecation(23479, "use f.orbit(P, N, **kwds) instead") <NEW_LINE> return f.orbit(self, N, **kwds)
Returns the orbit this point by ``f``. If ``N`` is an integer it returns `[P, self(P), \ldots,self^N(P)]`. If ``N`` is a list or tuple `N=[m,k]` it returns `[self^m(P),\ldots,self^k(P)`]. Automatically normalize the points if ``normalize == True``. Perform the checks on point initialization if ``check==True`` INPUT:...
625941d1be383301e01b5625
def __init__(self, parent = None): <NEW_LINE> <INDENT> QtGui.QDialog.__init__(self, parent) <NEW_LINE> self.width = 300 <NEW_LINE> self.height = 300 <NEW_LINE> self.setFixedSize(self.width, self.height); <NEW_LINE> self.setWindowTitle("Create a new study subject") <NEW_LINE> rootLayout = QtGui.QVBoxLayout(self) <NEW_LI...
Default constructor
625941d163d6d428bbe44690
def check_statement(self, *statement) -> bool: <NEW_LINE> <INDENT> if len(statement) == 1: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else : <NEW_LINE> <INDENT> varname, symbol, threshold = statement <NEW_LINE> <DEDENT> if symbol not in ('=', '<', '>'): <NEW_LINE> <INDENT> raise TypeError("The symbol given in ...
Checks a statement like 'active','<',3, returns a boolean
625941d1bd1bec0571d907d0
def congruencep(a, b, divisor): <NEW_LINE> <INDENT> return a%divisor == b%divisor
Check given numbers are congruence or not congruence.
625941d15166f23b2e1a52fa
def entropy(collection): <NEW_LINE> <INDENT> s = float(reduce(lambda a, b: a + b, collection)) <NEW_LINE> entropy = [] <NEW_LINE> for i in collection: <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> entropy.append(-((i / s) * math.log(i / s, 2))) <NEW_LINE> <DED...
Accepts list of counts for each classification class, returns entropy as expected encoding length in bits. collection: int list
625941d1f9cc0f698b14079c
def custom_score_3(game, player): <NEW_LINE> <INDENT> if game.is_loser(player): <NEW_LINE> <INDENT> return float("-inf") <NEW_LINE> <DEDENT> if game.is_winner(player): <NEW_LINE> <INDENT> return float("inf") <NEW_LINE> <DEDENT> w, h = game.width / 2., game.height / 2. <NEW_LINE> y, x = game.get_player_location(player) ...
Calculate the heuristic value of a game state from the point of view of the given player. Note: this function should be called from within a Player instance as `self.score()` -- you should not need to call this function directly. Parameters ---------- game : `isolation.Board` An instance of `isolation.Board` enco...
625941d18c0ade5d55d3eb5c
def searchWikipedia(query): <NEW_LINE> <INDENT> speak('Searching Wikipedia...') <NEW_LINE> search_string = query.replace('wikipedia', '') <NEW_LINE> results = wikipedia.summary(search_string, sentences=2) <NEW_LINE> speak(f"According to Wikipedia, {results}")
Search in wikipedia for a given query string
625941d124f1403a92600d06
def wavelength(self,filterset,band): <NEW_LINE> <INDENT> return self._filtersets[filterset][band].wave()
Return all the mean wavelength of a given Band and FilterSet, as astropy Quantity
625941d101c39578d7e74fdc
def describe_ndframe( *, obj: NDFrameT, include: str | Sequence[str] | None, exclude: str | Sequence[str] | None, datetime_is_numeric: bool, percentiles: Sequence[float] | np.ndarray | None, ) -> NDFrameT: <NEW_LINE> <INDENT> percentiles = refine_percentiles(percentiles) <NEW_LINE> describer: NDFrameDescriberAbstract <...
Describe series or dataframe. Called from pandas.core.generic.NDFrame.describe() Parameters ---------- obj: DataFrame or Series Either dataframe or series to be described. include : 'all', list-like of dtypes or None (default), optional A white list of data types to include in the result. Ignored for ``Series...
625941d1f8510a7c17cf989d
def __init__(self, inputArray): <NEW_LINE> <INDENT> maxsize = eval(inputArray[1]) <NEW_LINE> initialsize = eval(inputArray[2]) <NEW_LINE> goal = eval(inputArray[3]) <NEW_LINE> self.heuristicfn = dict() <NEW_LINE> self.heuristicf = self.getEuclideanHeuristic <NEW_LINE> self.nodesList = [] <NEW_LINE> self.maxJug1 = maxsi...
Constructor
625941d16aa9bd52df036f46
def event_history_update(self, event): <NEW_LINE> <INDENT> mco = Vector((event.mouse_x, event.mouse_y)) <NEW_LINE> values = {key: getattr(event, key) for key in ("shift", "ctrl", "alt", "oskey")} <NEW_LINE> values["mco"] = mco <NEW_LINE> if event.value == 'PRESS': <NEW_LINE> <INDENT> if event.type in self.event_history...
:type event: bpy.types.Event
625941d155399d3f05588856
def insert_string_in_middle(): <NEW_LINE> <INDENT> string_in_insert = input('Enter the string inside which to be inserted: ') <NEW_LINE> string_to_insert = input("Enter the string to be inserted: ") <NEW_LINE> length_of_string_in_insert = len(string_in_insert)//2 <NEW_LINE> print(f"Final Output: {string_in_insert[:leng...
Ques no.15: Write a Python function to insert a string in the middle of a string.
625941d12c8b7c6e89b35961
def get_serializer_class(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self.serializer_action_classes[self.action] <NEW_LINE> <DEDENT> except (KeyError, AttributeError): <NEW_LINE> <INDENT> return super().get_serializer_class()
Look for serializer class in self.serializer_action_classes, which should be a dict mapping action name (key) to serializer class (value), i.e.: class MyViewSet(MultiSerializerViewSetMixin, ViewSet): serializer_class = MyDefaultSerializer serializer_action_classes = { 'list': MyListSerializer, 'm...
625941d17b180e01f3dc499d
def on_mouse_press(self, x, y, button, modifiers): <NEW_LINE> <INDENT> if self.exclusive: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.set_exclusive_mouse(True)
Called when a mouse button is pressed. See pyglet docs for button amd modifier mappings. Parameters ---------- x, y : int The coordinates of the mouse click. Always center of the screen if the mouse is captured. button : int Number representing mouse button that was clicked. 1 = left button, 4 = right ...
625941d1498bea3a759b9c50
def seal(self): <NEW_LINE> <INDENT> self.counts = None
Make the probability table final. A sealed probability table can't be retrained but it uses much less RAM.
625941d18c3a87329515855d
def download_pic(complete_link, pic_complete_destination, url, nom_image): <NEW_LINE> <INDENT> if len(complete_link) > 50: <NEW_LINE> <INDENT> lien = complete_link[0:50] + ' (...)' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> lien = complete_link <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> urllib.request.urlretrieve(...
Download the pic from Internet (complete_link) to a local place (pic_complete_destination) url: the url where you want do download pictures (provided by the user) nom_image: the name which the pic will be saved with
625941d13617ad0b5ed68099
def YesterdayAt(hour): <NEW_LINE> <INDENT> now = datetime.now() <NEW_LINE> yesterday = now - timedelta(days=1) <NEW_LINE> return datetime.combine(yesterday, time(hour=hour))
Makes a datetime object with yesterday's date and the given time. hour: int 0-24
625941d1097d151d1a222ffa
def __init__(self, host='', user='', passwd='', acct='', timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None): <NEW_LINE> <INDENT> self.source_address = source_address <NEW_LINE> self.timeout = timeout <NEW_LINE> if host: <NEW_LINE> <INDENT> self.connect(host) <NEW_LINE> if user: <NEW_LINE> <INDENT> self.login(user, p...
Initialization method (called by class instantiation). Initialize host to localhost, port to standard ftp port. Optional arguments are host (for connect()), and user, passwd, acct (for login()).
625941d11f5feb6acb0c4cf0
def make_stun(action): <NEW_LINE> <INDENT> def stunned(duration): <NEW_LINE> <INDENT> def effect(colony): <NEW_LINE> <INDENT> nonlocal duration <NEW_LINE> if duration > 0: <NEW_LINE> <INDENT> duration -=1 <NEW_LINE> return <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return action(colony) <NEW_LINE> <DEDENT> <DEDENT> ...
Return a new action method that does nothing. action -- An action method of some Bee
625941d17047854f462a15aa
def configure_global(self): <NEW_LINE> <INDENT> bake_options = PyNode('vrayDefaultBakeOptions') <NEW_LINE> bake_options.setAttr('filenamePrefix', self.cur_version_string) <NEW_LINE> bake_options.setAttr('outputTexturePath', self.output_texture_path) <NEW_LINE> bake_options.setAttr('resolutionX', self.image_width)
Configure V-Ray global baking options
625941d1925a0f43d254a019
def approve(worker_responses): <NEW_LINE> <INDENT> approvals = [get_article_stance(response) is not None and len(get_article_stance(response)) > 0 for response in worker_responses] <NEW_LINE> return approvals
The approve callback is called when work is complete; it receives a list of worker responses. Return a list of True (approve) and False (reject) values. Approved tasks are passed on to the completed callback, and rejected tasks are automatically relaunched.
625941d15fc7496912cc3b1f
def compare_shapes( proto, input_key_values, expected_outputs, use_cpu_only=False, pred=None ): <NEW_LINE> <INDENT> if _IS_MACOS: <NEW_LINE> <INDENT> if not pred: <NEW_LINE> <INDENT> pred = run_core_ml_predict(proto, input_key_values, use_cpu_only) <NEW_LINE> <DEDENT> for o, expected in expected_outputs.items(): <NEW_L...
Inputs: - proto: MLModel proto. - input_key_values: str -> np.array. Keys must match those in input_placeholders. - expected_outputs: dict[str, np.array]. - use_cpu_only: True/False. - pred: Prediction to use, if it has already been computed.
625941d18e71fb1e9831d94a
def filter_ids(self, id_list: []): <NEW_LINE> <INDENT> if not id_list: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> id_set = set(filter(None, id_list)) <NEW_LINE> return self.filter(id__in=id_set)
No Trust in Humanity
625941d115baa723493c4117
def test_str_param_checker(): <NEW_LINE> <INDENT> arg = mockups.Arguments() <NEW_LINE> arg.infile = "smalldata/Reduced_dataset.structure" <NEW_LINE> arg.params = "mainparams" <NEW_LINE> sw.str_param_checker(arg) <NEW_LINE> assert arg.params == ["-m", "mainparams", "-e", "extraparams"]
Tests if the STRUCTURE parameter file checker is working.
625941d1a219f33f34628b0a
def getByPerson(self, person): <NEW_LINE> <INDENT> return EmailAddress.selectBy(person=person, orderBy='email')
See `IEmailAddressSet`.
625941d144b2445a33932237
def normalisesym(self, label): <NEW_LINE> <INDENT> if label[1:] == "''": <NEW_LINE> <INDENT> end = '"' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> end = label[1:].replace("U", "u").replace("G", "g") <NEW_LINE> <DEDENT> return label[0] + end
Normalise the symmetries used by GAMESS. To normalise, two rules need to be applied: (1) Occurences of U/G in the 2/3 position of the label must be lower-cased (2) Two single quotation marks must be replaced by a double
625941d1293b9510aa2c3437
def remove_null_questions(data_frame, points_list): <NEW_LINE> <INDENT> list_index = range(len(points_list)) <NEW_LINE> kill_list = [x for x in list_index if points_list[x] == 0] <NEW_LINE> if kill_list: <NEW_LINE> <INDENT> points_list = [points_list[x] for x in list_index if x not in kill_list] <NEW_LINE> data_frame =...
Removes questions that have 0 score from the database NOTE: Questions with 0 score are still usefull if they have a good amount of answers
625941d1956e5f7376d7100e
def moveZeroes(self, nums: List[int]) -> None: <NEW_LINE> <INDENT> zeroes = 0 <NEW_LINE> try: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> nums.remove(0) <NEW_LINE> zeroes += 1 <NEW_LINE> <DEDENT> <DEDENT> except ValueError: <NEW_LINE> <INDENT> nums += [0] * zeroes
Do not return anything, modify nums in-place instead.
625941d1c4546d3d9de72bd6
def __init__(self, hash_funct, chunk_len): <NEW_LINE> <INDENT> self._hash_func = hash_funct <NEW_LINE> self._chunk_len = chunk_len
Initialize Merkle Hash Tree using given hash function and file
625941d1d4950a0f3b08c4ef
def __init__(self): <NEW_LINE> <INDENT> self.VpnGatewayIds = None <NEW_LINE> self.Filters = None <NEW_LINE> self.Offset = None <NEW_LINE> self.Limit = None <NEW_LINE> self.OrderField = None <NEW_LINE> self.OrderDirection = None
:param VpnGatewayIds: VPN网关实例ID。形如:bmvpngw-f49l6u0z。每次请求的实例的上限为100。参数不支持同时指定VpnGatewayIds和Filters。 :type VpnGatewayIds: list of str :param Filters: 过滤条件,参数不支持同时指定VpnGatewayIds和Filters。 <li>vpc-id - String - (过滤条件)VPC实例ID形如:vpc-f49l6u0z。</li> <li>state - String - (过滤条件 VPN状态:creating,available,cr...
625941d1ec188e330fd5a93f
def download_image_list(urllist, label='default'): <NEW_LINE> <INDENT> DOWNLOADS_DIR = 'images' <NEW_LINE> for url in urllist: <NEW_LINE> <INDENT> if url[-1] == '/': <NEW_LINE> <INDENT> url = url[:-1] <NEW_LINE> <DEDENT> name = url.rsplit('/', 1)[-1] <NEW_LINE> directory = os.path.join(DOWNLOADS_DIR, label) <NEW_LINE> ...
Given a list of url downloads into specified dir
625941d101c39578d7e74fdd
def test_scale_world_origin(): <NEW_LINE> <INDENT> pts = (Point3D(1, 1, 2), Point3D(2, 1, 2), Point3D(2, 2, 2), Point3D(1, 2, 2)) <NEW_LINE> pline = Polyline3D(pts) <NEW_LINE> new_pline = pline.scale(2) <NEW_LINE> assert new_pline[0] == Point3D(2, 2, 4) <NEW_LINE> assert new_pline[1] == Point3D(4, 2, 4) <NEW_LINE> asse...
Test the Polyline3D scale method with None origin.
625941d18e05c05ec3eea517
@pytest.fixture(scope='session') <NEW_LINE> def app(request): <NEW_LINE> <INDENT> app = create_app(TestConfig) <NEW_LINE> ctx = app.app_context() <NEW_LINE> ctx.push() <NEW_LINE> def teardown(): <NEW_LINE> <INDENT> ctx.pop() <NEW_LINE> <DEDENT> request.addfinalizer(teardown) <NEW_LINE> return app
Create test app
625941d123e79379d52ee705
def GetAnnotatedTests(self, annotation_filter_list): <NEW_LINE> <INDENT> return [test for test, annotations in self._GetAnnotationMap().iteritems() if self._IsTestMethod(test) and self._AnnotationsMatchFilters( annotation_filter_list, annotations)]
Returns a list of all tests that match the given annotation filters.
625941d19c8ee82313fbb918
def LogNormal(loc, scale, value="value"): <NEW_LINE> <INDENT> loc, scale = to_funsor(loc), to_funsor(scale) <NEW_LINE> y = to_funsor(value, output=loc.output) <NEW_LINE> t = ops.exp <NEW_LINE> x = t.inv(y) <NEW_LINE> log_abs_det_jacobian = t.log_abs_det_jacobian(x, y) <NEW_LINE> backend_dist = import_module(BACKEND_TO_...
Wraps backend `LogNormal` distributions. :param Funsor loc: Mean of the untransformed Normal distribution. :param Funsor scale: Standard deviation of the untransformed Normal distribution. :param Funsor value: Optional real observation.
625941d13cc13d1c6d3c751b
def _get_weights_from_features(weight_key_name, features): <NEW_LINE> <INDENT> weights = None <NEW_LINE> if weight_key_name is not None: <NEW_LINE> <INDENT> if weight_key_name in features: <NEW_LINE> <INDENT> weights = features.pop(weight_key_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError( 'Cannot...
Pop and return feature for weights, possibly None.
625941d176e4537e8c351815
def save(self, fn=None): <NEW_LINE> <INDENT> if fn is None: <NEW_LINE> <INDENT> fn = self.display.getFileName("Save Game To:", exists=False) <NEW_LINE> if not fn: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> <DEDENT> with open(fn , 'w') as otf: <NEW_LINE> <INDENT> xn = xp.xmlNode('<blocks ver="%s" round="%d" state="%...
save the game to a file
625941d10a366e3fb873e9bc
def create_figs(self): <NEW_LINE> <INDENT> from bokeh.models.widgets import Panel, Tabs <NEW_LINE> from bokeh.plotting import figure <NEW_LINE> fig1 = figure(tools="pan, lasso_select, box_select, tap, wheel_zoom," " box_zoom, crosshair, hover, resize, reset", plot_width=600, plot_height=400) <NEW_LINE> fig1.circle(x='x...
Create Bokeh figures. There shouldn't be problem using any types of Bokeh plots. Just remember to import the required modules at the beginning.
625941d1d99f1b3c44c6772e
def authenticate(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> keystone = ksclient.Client(auth_url=environ.get('OS_AUTH_URL'), username=environ.get('OS_USERNAME'), password=environ.get('OS_PASSWORD'), tenant_name=environ.get('OS_TENANT_NAME'), region_name=environ.get('OS_REGION_NAME')) <NEW_LINE> nova = nvclient.Clie...
This function returns authenticated nova and glance objects
625941d1de87d2750b85ff35
def pack(self): <NEW_LINE> <INDENT> raise NotImplementedError
Remove obsolete records from the storage.
625941d110dbd63aa1bd2d45
def search(self, nums, target): <NEW_LINE> <INDENT> if not nums: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> lo = 0 <NEW_LINE> hi = len(nums) - 1 <NEW_LINE> while lo + 1 < hi: <NEW_LINE> <INDENT> mid = lo + (hi - lo) // 2 <NEW_LINE> if nums[mid] == target: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> if...
:type nums: List[int] :type target: int :rtype: bool
625941d14a966d76dd5511b2
def test_pop(): <NEW_LINE> <INDENT> from priority import Priority <NEW_LINE> new_p_q = Priority([("monkey", 1), ("cat", 2), ("dog", 1)]) <NEW_LINE> assert new_p_q.pop() == ("monkey")
Test pop function on populated queue.
625941d163d6d428bbe44691
def to_h5( record_file, annotation_files, h5_target_directory, signals, crop_record=True, force=False, ): <NEW_LINE> <INDENT> description = [] <NEW_LINE> events_description = [] <NEW_LINE> with pyedflib.EdfReader(record_file) as data: <NEW_LINE> <INDENT> if force or not os.path.exists(h5_target_directory): <NEW_LINE> <...
Format a MASS EDF record and its annotation to a standardized h5 record_file :(str) annotation_files :(list of str) the hypnogram has to be in the first annotation file h5_target :(str) crop_record : (bool)
625941d199fddb7c1c9de532
def selectChild(self, accessible, child_index): <NEW_LINE> <INDENT> procedurelogger.action('selected child_index %s in "%s"' % (child_index, accessible)) <NEW_LINE> accessible.selectChild(child_index)
Use the AtkSelection interface to select the child of the accessible at child_index
625941d1a79ad161976cc2e7
def perimeter_of_square(self): <NEW_LINE> <INDENT> perimeter_v = 4 * super().distance_between_2_points() <NEW_LINE> print('perimeter ',perimeter_v) <NEW_LINE> print(' Perimeter of the square is ',round(perimeter_v,1))
This method is used to find the perimeter of the Square.
625941d110dbd63aa1bd2d46
def almost(a, b, decimal=6, fill_value=True): <NEW_LINE> <INDENT> m = mask_or(getmask(a), getmask(b)) <NEW_LINE> d1 = filled(a) <NEW_LINE> d2 = filled(b) <NEW_LINE> if d1.dtype.char == "O" or d2.dtype.char == "O": <NEW_LINE> <INDENT> return np.equal(d1,d2).ravel() <NEW_LINE> <DEDENT> x = filled(masked_array(d1, copy=Fa...
Returns True if a and b are equal up to decimal places. If fill_value is True, masked values considered equal. Otherwise, masked values are considered unequal.
625941d194891a1f4081bc4c
def js_scroll_totop(self): <NEW_LINE> <INDENT> js = "window.scrollTo(0,0)"
通过js移动滚动条到最上面 :return:
625941d22ae34c7f2600d2d3
def generate_stats(self, request, response): <NEW_LINE> <INDENT> pass
Write panel logic related to the response there. Post-process data gathered while the view executed. Save data with :meth:`record_stats`. Called after :meth:`process_request <debug_toolbar.panels.Panel.process_request>`. Does not return a value.
625941d11b99ca400220ac53
def test_powerview_list_normal_authorized_user(self): <NEW_LINE> <INDENT> user = User() <NEW_LINE> p1 = factories.PowerView(user=user, private=True) <NEW_LINE> factories.PowerView(private=False) <NEW_LINE> factories.PowerView(private=False) <NEW_LINE> context = {'user': user['name']} <NEW_LINE> powerview_list = toolkit...
Calling powerview_list with a normal user, who is authorized to view a private powerviews, will have it listed.
625941d13d592f4c4ed1d20e
def string_to_number(text): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return int(text) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return float(text) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return text
try to convert string to int or float. if failure, return same string
625941d2e1aae11d1e749e5a
def _add_placeholders(self): <NEW_LINE> <INDENT> hps = self._hps <NEW_LINE> self._enc_batch = tf.placeholder(tf.int32, [hps.batch_size, None], name='enc_batch') <NEW_LINE> self._rel_scores_batch = tf.placeholder(tf.float32, [hps.batch_size, None], name='rel_scores_batch') <NEW_LINE> self._enc_lens = tf.placeholder(tf.i...
Add placeholders to the graph. These are entry points for any input data.
625941d28a43f66fc4b54206
def recon_sp(tauI, dm, data): <NEW_LINE> <INDENT> Nmax = len(data) - (dm - 1) * tauI <NEW_LINE> v = np.zeros([Nmax, dm]) <NEW_LINE> for j in range(Nmax): <NEW_LINE> <INDENT> for i in range(dm): <NEW_LINE> <INDENT> datindex = j + i * tauI <NEW_LINE> v[j, i] = data[datindex] <NEW_LINE> <DEDENT> <DEDENT> return v
This function reconstructs the attractor of a time series through time delay embedding tauI: int number of time delay steps to use dm: int number of embedding dimensions data: np.array np.array of the original 1 dimensional time series data
625941d28e05c05ec3eea518
def performUpdate(self): <NEW_LINE> <INDENT> if not self.checkShared(): <NEW_LINE> <INDENT> super(DisplayManager, self).performUpdate()
Update object to newest version
625941d20c0af96317bb838a
@Client.on_message(filters.command('help') & filters.private) <NEW_LINE> def info_and_help(_, m: Message): <NEW_LINE> <INDENT> user = get_user(m.from_user.id) <NEW_LINE> lang = user.language <NEW_LINE> if user.is_admin: <NEW_LINE> <INDENT> return m.reply(MSG('admins_help', lang), disable_web_page_preview=True, reply_ma...
send the help message. :param _: pyrogram Client, unused argument :param m: the `/help` command message.
625941d28a349b6b435e8316
def decode_type(t): <NEW_LINE> <INDENT> typ = None <NEW_LINE> if t == 'K': <NEW_LINE> <INDENT> typ = "package" <NEW_LINE> <DEDENT> elif t == 't': <NEW_LINE> <INDENT> typ = "task object" <NEW_LINE> <DEDENT> elif t == 'V': <NEW_LINE> <INDENT> typ = "function" <NEW_LINE> <DEDENT> elif t == 'U': <NEW_LINE> <INDENT> typ = '...
verbose type from ALI symbol. See lib-xref.ads Only handles those with would appear in *.spark files Bodies of functions will not appear in SPARK, only specs. Task types will not appear in SPARK, only objects packages will appear
625941d2baa26c4b54cb12c1
def get_templates_metadata(request): <NEW_LINE> <INDENT> scenario_id = request.GET.get('scenario_id', None) <NEW_LINE> if not scenario_id: <NEW_LINE> <INDENT> return JsonResponse({'error': 'Need to provide scenario_id'}) <NEW_LINE> <DEDENT> scenario = Scenario.objects.filter(id=int(scenario_id)).first() <NEW_LINE> if s...
Get the templates for a project from a lookup on the scenario id. This is because we only have access to the scenario id param from the sim page.
625941d2be8e80087fb20de4
def setup_queue(self, queue_name): <NEW_LINE> <INDENT> LOGGER.debug('Declaring queue %s', queue_name) <NEW_LINE> self._channel.queue_declare(self.on_queue_declareok, queue_name)
Setup the queue on RabbitMQ by invoking the Queue.Declare RPC command. When it is complete, the on_queue_declareok method will be invoked by pika. :param str|unicode queue_name: The name of the queue to declare.
625941d25fc7496912cc3b20
def info_server(self, server): <NEW_LINE> <INDENT> LOG.info('info_server(server=%s)', server) <NEW_LINE> self._connect() <NEW_LINE> domain = self._get_domain(server) <NEW_LINE> info = self._info_domain(domain) <NEW_LINE> LOG.info('info = %s', info) <NEW_LINE> return info
Return the server info
625941d2283ffb24f3c55aa2
def delete(self, *args, **kwargs): <NEW_LINE> <INDENT> for attachment in self.attachments.all(): <NEW_LINE> <INDENT> attachment.delete() <NEW_LINE> <DEDENT> return super().delete(*args, **kwargs)
Delete this message and all stored attachments.
625941d2bde94217f3682f92
@api_v3_app.route('/workflow/repos/<owner>/<repo>/alert/dingtalk/watch/watcher/<user>', methods=['DELETE']) <NEW_LINE> def delete_dingtalk_watcher(owner, repo, user): <NEW_LINE> <INDENT> user_query = db.session.query(DingtalkUser). filter(Owner.owner_name == user). filter(DingtalkUser.user_id == Owner.own...
取消user对owner/repo项目的关注 DELETE /repos/<owner>/<repo>/alert/dingtalk/watch/watcher/<user> Input: none Response: { 'data': { 'status': 'ok' } }
625941d231939e2706e4d00b
def test_class_kwargs(self): <NEW_LINE> <INDENT> dictonary = { 'id': '662a23b3-abc7-4f43-81dc-64c000001c00', 'name': 'New York'} <NEW_LINE> city1 = City(**dictonary) <NEW_LINE> self.assertTrue(hasattr(city1, "id")) <NEW_LINE> self.assertEqual(city1.id, '662a23b3-abc7-4f43-81dc-64c000001c00') <NEW_LINE> self.assertTrue(...
Test the class passing kwargs
625941d2fbf16365ca6f6369
def event_m20_21_x25(z201=_, z202=_, z203=_): <NEW_LINE> <INDENT> if CompareObjStateId(z201, z203, 0): <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 0
[Condition] Elevator lever_use judgment z201: OBJ instance ID of the elevator z202: Lever OBJ instance ID z203: Elevator state ID on the opposite side of the lever
625941d2a8ecb033257d326f
def __init__(self, nusc, config, mode = "train"): <NEW_LINE> <INDENT> self.nusc = nusc <NEW_LINE> self.radar_sensors = config['radar_sensors'] <NEW_LINE> self.camera_sensors = config['camera_sensors'] <NEW_LINE> self.radar_cover_shape = config["radar_cover_shape"] <NEW_LINE> self.image_min_side = 450 <NEW_LINE> self.im...
:param nusc: 数据集用来取数据的数据库 :param config: 产生数据的参数 :param mode: 因为有train和test,val分为两大类模式,所以数据增广不太一样!
625941d2f9cc0f698b14079d
def returnSwitchConnections(mn_topo, switches, operSwNames): <NEW_LINE> <INDENT> def returnConnections(sw, swID): <NEW_LINE> <INDENT> global mplsVal <NEW_LINE> switchtable = [] <NEW_LINE> switchtable.append(int(swID)) <NEW_LINE> switchtable.append('openflow:' + str(int(sw.dpid,16))) <NEW_LINE> switchtable.append(sw.nam...
Dump connections to/from nodes.
625941d257b8e32f5248363e
def create_select_all_form(question, dbsession, user_choices): <NEW_LINE> <INDENT> answers = dbsession.query(Answer).filter( Answer.question_id==question.id).all() <NEW_LINE> choices = [] <NEW_LINE> for answer in answers: <NEW_LINE> <INDENT> answer_text = options[answers.index(answer)]+". "+answer.answer <NEW_LINE> cho...
create form to take a multiple choice form
625941d215fb5d323cde0cb3
def __init__(self, order_number, product_id, item_type, name, product_details, factory, quantity, holiday): <NEW_LINE> <INDENT> self._order_number = order_number <NEW_LINE> self._product_id = product_id <NEW_LINE> self._item_type = item_type <NEW_LINE> self._name = name <NEW_LINE> self._product_details = product_detail...
Construct a new order :param order_number: str :param product_id: str :param item_type: str :param name: str :param product_details: str :param factory: Factory :param quantity: int :param holiday: str
625941d2c432627299f04de9
def _ExtractSentinelTileCoords(self, mgrsversion): <NEW_LINE> <INDENT> for locus in self.process.srcLayerD: <NEW_LINE> <INDENT> if len(self.process.srcLayerD[locus]) == 0: <NEW_LINE> <INDENT> exitstr = 'EXITING, no dates defined in Sentinel._ExtractSentinelTileCoords' <NEW_LINE> exit(exitstr) <NEW_LINE> <DEDENT> for da...
Extracts MGRS tile corners from MGRS polygons
625941d2c4546d3d9de72bd7
def encrypt(self): <NEW_LINE> <INDENT> if os.path.isfile(self.filename): <NEW_LINE> <INDENT> pyAesCrypt.encryptFile( self.filename, self.aesname, self.device_id(), 64*1024) <NEW_LINE> os.remove(self.filename) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Original file", self.filename, "not found.") <NEW_LINE> <D...
Converts any file to .aes using pyAesCrypt
625941d2ff9c53063f47c396
def cal_item_popularity(mongo_train_user_collection, item_id, stoptime_str='2014-12-19 00'): <NEW_LINE> <INDENT> if data_dict['item_data'].has_key(item_id): <NEW_LINE> <INDENT> return data_dict['item_data'][item_id]['popularity'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> train_user = mongo_train_user_collection <NE...
计算商品热门度,由于被除数都一样所以不再除以被购买商品总数,改为count的sigmoid形式 :param item_id: :param stoptime:格式例如:'2014-12-18 00' :return:float类型的商品热度
625941d25f7d997b87174c3b
def frombytes(mode, size, data, decoder_name="raw", *args): <NEW_LINE> <INDENT> if len(args) == 1 and isinstance(args[0], tuple): <NEW_LINE> <INDENT> args = args[0] <NEW_LINE> <DEDENT> if decoder_name == "raw" and args == (): <NEW_LINE> <INDENT> args = mode <NEW_LINE> <DEDENT> im = new(mode, size) <NEW_LINE> im.frombyt...
Creates a copy of an image memory from pixel data in a buffer. In its simplest form, this function takes three arguments (mode, size, and unpacked pixel data). You can also use any pixel decoder supported by PIL. For more information on available decoders, see the section **Writing Your Own File Decoder**. Note tha...
625941d2596a897236089c62
def text_add(radius=1.0, view_align=False, enter_editmode=False, location=(0.0, 0.0, 0.0), rotation=(0.0, 0.0, 0.0), layers=(False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False)): <NEW_LINE> <INDENT> pass
Add a text object to the scene :param radius: Radius :type radius: float in [0, inf], (optional) :param view_align: Align to View, Align the new object to the view :type view_align: boolean, (optional) :param enter_editmode: Enter Editmode, Enter editmode when adding this object :type enter_editmode: boolean, (opt...
625941d2566aa707497f470a
def model(self): <NEW_LINE> <INDENT> for user, ratings in self.data.u_rating.items(): <NEW_LINE> <INDENT> self.u_mean[user] = sum([rate[1] for rate in ratings])+0.0 <NEW_LINE> self.u_mean[user] /= len(ratings)
building model
625941d27d43ff24873a2e43
def leaveEvent (self, event): <NEW_LINE> <INDENT> event.accept()
On mouse move event
625941d2a05bb46b383ec9c4
def exec_(self): <NEW_LINE> <INDENT> self.setDefaults() <NEW_LINE> return QtGui.QWizard.exec_(self)
Run the wizard.
625941d232920d7e50b28373
def __init__(self, data_models, video, parent=None): <NEW_LINE> <INDENT> super(MainApp, self).__init__(parent) <NEW_LINE> self.video = video <NEW_LINE> pyqtgraph.setConfigOption('background', 'w') <NEW_LINE> self.resize(1280, 640) <NEW_LINE> self.setup_ui(data_models, video)
Initializes the Main window Args: data_models: List of DataModels video_models: List of VideoModels
625941d2379a373c97cface8
def add_bar(self): <NEW_LINE> <INDENT> bar = '-' * self.n * 2 + '|' <NEW_LINE> coord = curses.getsyx() <NEW_LINE> num_bars = min(self.m, self.x_max // len(bar)) <NEW_LINE> tune_width = max((len(s) for s in self.tuning)) <NEW_LINE> for i, string in enumerate(reversed(self.tuning)): <NEW_LINE> <INDENT> self.stdscr.addstr...
prints another bar to the curses display for editing
625941d285dfad0860c3affe
def check_personalized_menu_match(self, user_id): <NEW_LINE> <INDENT> data = { "user_id": user_id } <NEW_LINE> access_token = self.settings.GET_GLOBAL_ACCESS_TOKEN(self) <NEW_LINE> url = "https://api.weixin.qq.com/cgi-bin/menu/trymatch?access_token=" + access_token <NEW_LINE> data = requests.post(url, data=json.dumps(d...
Check whether personalized menu match is correct. :param data:user_id :return:Raw data that wechat returns.
625941d2090684286d50ee89
def build_command(self, action, args=None): <NEW_LINE> <INDENT> arguments = self.wrap_arguments(args) <NEW_LINE> body = self.soap_body_template.format( arguments=arguments, action=action, service_type=self.service_type, version=self.version) <NEW_LINE> soap_action_template = "urn:schemas-upnp-org:service:{se...
Build a SOAP request. Given the name of an action (a string as specified in the service description XML file) to be sent, and the relevant arguments as a list of (name, value) tuples, return a tuple containing the POST headers (as a dict) and a string containing the relevant SOAP body. Does not set content-length, or ...
625941d216aa5153ce36261a
def on_prev_image_clicked(self, _: Any, _diag_fun: Callable = None) -> None: <NEW_LINE> <INDENT> prev_i = self.prev_img_name <NEW_LINE> if prev_i is not None: <NEW_LINE> <INDENT> ps = PhotoShow(self, prev_i) <NEW_LINE> if _diag_fun is not None: <NEW_LINE> <INDENT> wx.CallAfter(_diag_fun, ps) <NEW_LINE> <DEDENT> ps.Show...
Enlarges the preview image.
625941d215fb5d323cde0cb4
def make_connections(self): <NEW_LINE> <INDENT> inputs, outputs = {}, {} <NEW_LINE> for compname in self.list_components(): <NEW_LINE> <INDENT> comp_inputs = self.get(compname).list_inputs() <NEW_LINE> for input_name in comp_inputs: <NEW_LINE> <INDENT> if input_name not in inputs: <NEW_LINE> <INDENT> inputs[input_name]...
Collects the names of all input and output variables for all components within the assembly (drivers excluded). Then establishes connections between any output variable and input variable that has the same name, so long as the variable name does not exist as an output to more than a single component (so excludes defau...
625941d221a7993f00bc7e94
def get_peer(hostname: ip_address) -> Optional[Peer]: <NEW_LINE> <INDENT> peers = peer_list() <NEW_LINE> if peers.is_err(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> for peer in peers.value: <NEW_LINE> <INDENT> if peer.hostname == hostname: <NEW_LINE> <INDENT> return peer <NEW_LINE> <DEDENT> <DEDENT> return N...
This will query the Gluster peer list and return a Peer class for the peer :param hostname: String. Name of the peer to get :return Peer or None in case of not found
625941d276d4e153a657ecd4
def _check_val(val): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if val.find('\x00') >= 0: <NEW_LINE> <INDENT> raise ValueError(repr(val) + ' contains a NUL byte') <NEW_LINE> <DEDENT> <DEDENT> except AttributeError: <NEW_LINE> <INDENT> pass
Checks whether a minusconf value contains any NUL bytes.
625941d24f6381625f114bde
def AddConnectedVPCMutexGroup(parser): <NEW_LINE> <INDENT> mutex_group = parser.add_group(mutex=True) <NEW_LINE> mutex_group.add_argument( '--connected-vpc', help='Specifies the VPC network to connect the function to.', hidden=True ) <NEW_LINE> mutex_group.add_argument( '--vpc-connector', help='The VPC Network Connecto...
Add mutex group for --connected-vpc and --vpc-connector.
625941d273bcbd0ca4b2c219
def scan_invited_accounts(log, org_client): <NEW_LINE> <INDENT> response = org_client.list_handshakes_for_organization( Filter={'ActionType': 'INVITE'}) <NEW_LINE> handshakes = response['Handshakes'] <NEW_LINE> while 'NextToken' in response: <NEW_LINE> <INDENT> response = org_client.list_handshakes_for_organization( Fi...
Return a list of handshake IDs
625941d2283ffb24f3c55aa3
def testV1ObjectMeta(self): <NEW_LINE> <INDENT> model = lib_openshift.models.v1_object_meta.V1ObjectMeta()
Test V1ObjectMeta
625941d2fb3f5b602dac3837
def raise_if_blocked(self, url): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> blocked = self.check_url( url, allow_all=self._request.registry.settings["checkmate_allow_all"], blocked_for=self._request.params.get("via.blocked_for"), ignore_reasons=self._request.registry.settings[ "checkmate_ignore_reasons" ], ) <NEW_LIN...
Raise a redirect to Checkmate if the URL is blocked. This will sensibly apply all ignore reasons and other configuration for Checkmate. :param url: The URL to check :raise HTTPTemporaryRedirect: If the URL is blocked
625941d2b830903b967e9aad