code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def init_start(self, glyph_item: GlyphItem, text: str) -> bool: <NEW_LINE> <INDENT> text_pointer = ffi.new('char[]', text.encode('utf8')) <NEW_LINE> return bool(pango.pango_glyph_item_iter_init_start( self._pointer, glyph_item.get_pointer(), text_pointer ))
Initializes the :class:`GlyphItemIter` structure to point to the first cluster in a glyph item. See :class:`GlyphItemIter` for details of cluster orders. :return: ``False`` if there are no clusters in the glyph item
625941f091af0d3eaac9bfbc
def __init__(self,alignsegment,matchid,sentence_id,align_id=None, broadcontext=False, search=None): <NEW_LINE> <INDENT> self.context = alignsegment <NEW_LINE> self.matchedsentence = alignsegment[sentence_id] <NEW_LINE> self.matchedword = alignsegment[sentence_id].words[matchid] <NEW_LINE> self.sourcetextid = self.match...
Creates a match object. Variables: ----------- alignsegment = the segment the matching sentence is a part of matchid = the tokenid ('how manyth word/punct in the sentence?') of the word that matched
625941f0e5267d203edce233
def array_equivalent(left, right, strict_nan=False): <NEW_LINE> <INDENT> left, right = np.asarray(left), np.asarray(right) <NEW_LINE> if left.shape != right.shape: return False <NEW_LINE> if issubclass(left.dtype.type, np.object_) or issubclass(right.dtype.type, np.object_): <NEW_LINE> <INDENT> if not strict_nan: <NEW_...
True if two arrays, left and right, have equal non-NaN elements, and NaNs in corresponding locations. False otherwise. It is assumed that left and right are NumPy arrays of the same dtype. The behavior of this function (particularly with respect to NaNs) is not defined if the dtypes are different. Parameters --------...
625941f08e05c05ec3eea917
def serve_socket(port): <NEW_LINE> <INDENT> print('Server: running on port %d' % port) <NEW_LINE> signal.signal(signal.SIGALRM, client_not_found) <NEW_LINE> signal.alarm(20) <NEW_LINE> sock = None <NEW_LINE> while True: <NEW_LINE> <INDENT> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> try: <NEW_LI...
Serves a blcking socket on the specified port. Returns a new socket object representing the client, on which send() and recv() can be invoked.
625941f0293b9510aa2c382e
def countunder21grandslam(atpmatches): <NEW_LINE> <INDENT> matches=atpmatches[(atpmatches['tourney_level'] == 'G') & (atpmatches['round'] == 'R128')] <NEW_LINE> matches['w_under_21'] = matches.groupby(['tourney_id'])['winner_age'].transform(lambda x: x[x < 21].count()) <NEW_LINE> matches['l_under_21'] = matches.groupby...
calculates how many players under 21 were in a grand slam main draw
625941f0b5575c28eb68e5a3
def test_spectrum_espi(): <NEW_LINE> <INDENT> N = 4 <NEW_LINE> wc = wa = 1.0 * 2 * pi <NEW_LINE> g = 0.1 * 2 * pi <NEW_LINE> kappa = 0.75 <NEW_LINE> gamma = 0.25 <NEW_LINE> n_th = 0.01 <NEW_LINE> a = tensor(destroy(N), qeye(2)) <NEW_LINE> sm = tensor(qeye(N), destroy(2)) <NEW_LINE> H = wc * a.dag() * a + wa * sm.dag() ...
correlation: comparing spectrum from es and pi methods
625941f04f6381625f114fd9
@valid_cluster <NEW_LINE> def list_components(*, node, cluster): <NEW_LINE> <INDENT> if not nodes.check_node(cluster=cluster, node=node): <NEW_LINE> <INDENT> raise ex.LoadError('node', node, 'NotExist') <NEW_LINE> <DEDENT> if cluster != ss.svars['cluster']: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> with open(JUMBODI...
List the components installed on a node of a specified cluster. :param node: Machine name :type node: str :param cluster: Cluster name :type cluster: str :raises ex.LoadError: [description] :return: The list of the components installed on the node :rtype: list
625941f00c0af96317bb8785
def __init__(self, *args, **kwds): <NEW_LINE> <INDENT> if args or kwds: <NEW_LINE> <INDENT> super(GetPairingsResponse, self).__init__(*args, **kwds) <NEW_LINE> if self.pairings is None: <NEW_LINE> <INDENT> self.pairings = [] <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> self.pairings = []
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: pairings :param args: complete se...
625941f0a934411ee3751c33
def updateBoard(self, board, click): <NEW_LINE> <INDENT> if board[click[0]][click[1]] == 'M': <NEW_LINE> <INDENT> board[click[0]][click[1]] = 'X' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> count = 0 <NEW_LINE> for i in range(-1, 2): <NEW_LINE> <INDENT> for j in range(-1, 2): <NEW_LINE> <INDENT> if click[0] + i < 0 o...
:type board: List[List[str]] :type click: List[int] :rtype: List[List[str]]
625941f0379a373c97cfb0e5
def getIconByMarketGroup(self, mg): <NEW_LINE> <INDENT> if mg.icon: <NEW_LINE> <INDENT> return mg.icon.iconFile <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> while mg and not mg.hasTypes: <NEW_LINE> <INDENT> mg = mg.parent <NEW_LINE> <DEDENT> if not mg: <NEW_LINE> <INDENT> return "" <NEW_LINE> <DEDENT> elif self.market...
Return icon associated to marketgroup
625941f0fb3f5b602dac3c37
def bind_animation(self, anim): <NEW_LINE> <INDENT> self.anim = anim
Bind this maze to an animation. This is for communicating with an Animation object.
625941f0a4f1c619b28b05c9
def __rcontains__(self, superset): <NEW_LINE> <INDENT> return self.__eq__(superset)
:param superset: A FILTER (RETURNS BOOLEAN) :return: True IF superset RETURNS True WHEN self RETURNS True
625941f06e29344779a62baf
def test_mixed_tests_with_multiple_testplans_and_pkgs_perpackage(self): <NEW_LINE> <INDENT> distribution_model = "perpackage" <NEW_LINE> image_url = 'http://image/url/image.bin' <NEW_LINE> test_plan = StringIO("hulapaloo") <NEW_LINE> test_plan.name = "testplan.xml" <NEW_LINE> test_plan2 = StringIO("hulapaloo2") <NEW_LI...
Test host test plan based - one test plan
625941f0460517430c394713
def disruption_details(self, disruption_num, **endpoint_kwargs): <NEW_LINE> <INDENT> return self.request('disruptions/%s' % disruption_num, params=endpoint_kwargs)
Queries details about the specified disruption number. :param disruption_num: str :param endpoint_kwargs: parameters as accepted by the API endpoint :return:
625941f0004d5f362079a8cd
def on_click_height(pos_x: int, pos_y: int) -> None: <NEW_LINE> <INDENT> toggle_option("Height")
Handles the click in one of the options height button.
625941f0ab23a570cc250725
def start(self, single_run=False): <NEW_LINE> <INDENT> print('{0}: watching directory "{1}"'.format( self.__class__, self._dir)) <NEW_LINE> self.observer.schedule(self.event_handler, self._dir, recursive=True) <NEW_LINE> self.check_watch_limit(self._dir) <NEW_LINE> self.observer.start() <NEW_LINE> try: <NEW_LINE> <INDE...
Watch directory forever and execute test cases :param single_run: if True, only wait for a short time (testing)
625941f05fdd1c0f98dc07d3
def load(self, resource, resource_locator=None): <NEW_LINE> <INDENT> if resource_locator is not None: <NEW_LINE> <INDENT> resource = resource_locator.find(resource) <NEW_LINE> <DEDENT> return parse_file(resource)
Load some file source.
625941f007d97122c4178e37
def random_iterator(self, batch_size, train_val_split_ratio=0.2, window_length=None): <NEW_LINE> <INDENT> input_tuple = self._create_state_action_next_state(window_length=window_length) <NEW_LINE> output_tuple = train_test_split(*input_tuple, test_size=train_val_split_ratio) <NEW_LINE> train_tuple = output_tuple[0::2] ...
Create iterator over (s, a, s', r, d) Args: batch_size: batch size Returns:
625941f0ec188e330fd5ad31
def to_gnu_options(self): <NEW_LINE> <INDENT> args = [] <NEW_LINE> for key, value in self.iteritems(): <NEW_LINE> <INDENT> optname = re.sub(r'([A-Z]+)', r'-\1', key[1:-1]).lower() <NEW_LINE> opt = '--{k}={v}'.format(k=optname, v=value) <NEW_LINE> args.append(opt) <NEW_LINE> <DEDENT> return args
Returns the replacement dict's values as an array of GNU-style long options. This is primarily useful for passing options to FPR commands. For example: >>> rd = ReplacementDict({'%foo%': 'bar'}) >>> rd.to_gnu_options() ['--foo=bar']
625941f05fdd1c0f98dc07d4
@memoize <NEW_LINE> def get_pdf_support(edges, pos): <NEW_LINE> <INDENT> return edges[numpy.digitize(pos, edges).tolist()]
As far as the support is quantized this maps a continuous value to a quantized one :param edges: list of bins :param pos: position on the support :return: quantized position
625941f099cbb53fe6793183
def send(self, msg, number_size=5): <NEW_LINE> <INDENT> msg = self.client_token + msg.encode() <NEW_LINE> msg = Crypt.encrypt_aes(msg, self.aes_key) <NEW_LINE> leng = len(msg).to_bytes(number_size, "big") <NEW_LINE> try: <NEW_LINE> <INDENT> self.s.send(leng+msg) <NEW_LINE> <DEDENT> except BrokenPipeError: <NEW_LINE> <I...
Sends a message to the server :param msg: Message to send :param number_size: Size in bytes of integer representing the size of the message :raise DisconnectedServer :return: VOID
625941f0442bda511e8be9ae
def sendto_entry_handler(syscall_id, syscall_object, pid): <NEW_LINE> <INDENT> logging.debug('Entering sendto entry handler') <NEW_LINE> p = util.cint.peek_register(pid, util.cint.ECX) <NEW_LINE> params = util.extract_socketcall_parameters(pid, p, 3) <NEW_LINE> fd_from_trace = int(syscall_object.args[0].value) <NEW_LIN...
<Purpose> sendto call entry handler that replays based on fd from trace. It does several things: 1. Peek ECX for system call parameters 2. Validate sockfd and message length 3. Check if replay is necessary based on fd from trace Checks: 0: int sockfd 2: size_t len <Returns> None
625941f06fece00bbac2dce4
def make_indented_coord_entries_string(self, ordered_coord_list): <NEW_LINE> <INDENT> indented_entry_strings = [] <NEW_LINE> for coord in ordered_coord_list: <NEW_LINE> <INDENT> entry_string = ( self.make_coord_entry_string(coord)) <NEW_LINE> indented_entry_string = self.tab + entry_string <NEW_LINE> indented_entry_str...
Returns a string composed of indented coord entry strings: <tab><coord entry 1> ...
625941f032920d7e50b28773
def run(self, data, hold_off_ratio=0.3): <NEW_LINE> <INDENT> assert 'c' in self.search_dict_, "Missing parameter 'c'" <NEW_LINE> assert 'e' in self.search_dict_, "Missing parameter 'e'" <NEW_LINE> self.training_set_, self.validation_set_ = td.split_data(data, hold_off_ratio) <NEW_LINE> [self.worker({'c': c, 'e': e}) fo...
Run grid search :param data: training data, N x (d+1) array, where the last column is the target :param hold_off_ratio: ratio of hold_off validation set :return: dictionary of optimal parameter, optimal r2 score
625941f0a05bb46b383ecdba
def init_toggle(self, length=None, shortest=10, longest=10, lowest=0, highest=255, lower_bounds=None, upper_bounds=None): <NEW_LINE> <INDENT> low_gen = self.init_low(length, shortest, longest, lowest, highest, lower_bounds, upper_bounds) <NEW_LINE> high_gen = self.init_high(length, shortest, longest, lowest, highest, l...
Returns instances of `IntegerIndividual`. Every second individual (from the first one returned) is initialised with `highest`; the remainder with `lowest`. Parameters are the same as for `init_random`.
625941f04d74a7450ccd4763
@APP.route("/message/edit", methods=['PUT']) <NEW_LINE> def message_edit(): <NEW_LINE> <INDENT> payload = request.get_json() <NEW_LINE> token = payload['token'] <NEW_LINE> message_id = payload['message_id'] <NEW_LINE> message_edited = payload['message'] <NEW_LINE> message_id = message.message_edit(token, message_id, me...
Route that edits a message specified by the message ID
625941f0a8370b7717052e3b
@csrf_exempt <NEW_LINE> @require_GET <NEW_LINE> def edna_get_sample_otu(request): <NEW_LINE> <INDENT> sample_contextual_ids = [] <NEW_LINE> contextual_params = request.GET.getlist('q', None) <NEW_LINE> password = None <NEW_LINE> for param in contextual_params: <NEW_LINE> <INDENT> if "password" in param: <NEW_LINE> <IND...
Returns sample_otu entries from otu table combination-keys
625941f021a7993f00bc8299
def run_meta_batch(self, meta_batch, meta_train): <NEW_LINE> <INDENT> loss, results = self.meta(meta_batch, return_predictions=False, return_results=True, create_graph=meta_train) <NEW_LINE> if meta_train: <NEW_LINE> <INDENT> loss.backward() <NEW_LINE> self.meta_optimizer.step() <NEW_LINE> self.meta_optimizer.zero_grad...
Run on meta-batch. Arguments: meta_batch (list): list of task-specific dataloaders meta_train (bool): meta-train on batch.
625941f026068e7796caf286
def checkout_page(): <NEW_LINE> <INDENT> driver = webdriver.Chrome() <NEW_LINE> driver.maximize_window() <NEW_LINE> driver.get("https://weathershopper.pythonanywhere.com/") <NEW_LINE> cheap_products = take_me_to_cart(driver) <NEW_LINE> result = verify_cart(driver, cheap_products) <NEW_LINE> if result: <NEW_LINE> <INDEN...
takes you to the checkout page
625941f09b70327d1c4e1376
def print_time(dt): <NEW_LINE> <INDENT> if dt: <NEW_LINE> <INDENT> secs = time.mktime(dt.timetuple()) <NEW_LINE> return secs * 1000 <NEW_LINE> <DEDENT> return None
Returns milliseconds since the epoch
625941f04527f215b584c9f0
def __gt__(self, other): <NEW_LINE> <INDENT> if self.number == 'A' and other.number != 'A': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.number in 'JQK' and other.number not in 'AJQK': <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif self.number in 'JQK' and other.number in 'JQK' and 'JQK'.find...
C.__gt__(C2) <==> C > C2 --> bool Returns True if the number value of C is greater than that of C2, False otherwise
625941f085dfad0860c3b3fb
def test_string1(self): <NEW_LINE> <INDENT> abox = AnswerBox('type="string" expect="Michigan" size="20"') <NEW_LINE> xmlstr = abox.xmlstr <NEW_LINE> print(xmlstr) <NEW_LINE> self.assertIn('<textline size="20"/>', xmlstr) <NEW_LINE> self.assertIn('<stringresponse answer="Michigan" type="">', xmlstr)
Test a string response with default settings
625941f050485f2cf553d33a
def handle(req): <NEW_LINE> <INDENT> data = json.loads(req) <NEW_LINE> return json.dumps({'command': get_command(data)})
{ matchId: string, // unik kamp-ID mapWidth: int, mapHeight: int, suddenDeath: int, // antall runder til sudden death starter wallDamage: int, // hvor mye skade som pingvinen tar av å gå inn i veggen penguinDamage: int, // hvor mye skade pingvinen tar av å krasje med en annen pingvin -- også hvor mye skade ...
625941f04d74a7450ccd4764
def create_license_list(row: int, column: int, colspan=0, rowspan=0): <NEW_LINE> <INDENT> APP.startFrame("License List Frame", row, column, colspan, rowspan) <NEW_LINE> APP.setSticky("nsew") <NEW_LINE> APP.addListBox("License List", get_license_list()) <NEW_LINE> APP.setListBoxChangeFunction("License List", change_lice...
Creates a Frame with a ListBox in which the list of licenses is shown.
625941f03eb6a72ae02eca8b
def __get_transaction_inputs(self, trans_id): <NEW_LINE> <INDENT> sql = 'SELECT * FROM transaction_input WHERE id_transaction = {}'.format(trans_id) <NEW_LINE> return self.__query(sql)
Retrieves transaction inputs from a transaction in the database.
625941f0377c676e91272745
def unfreeze(label, pop=False, environ=None): <NEW_LINE> <INDENT> environ = os.environ if environ is None else environ <NEW_LINE> diff = _get_diff(environ, label, pop=pop) <NEW_LINE> original = _apply_diff(environ, diff) <NEW_LINE> return _refreezer(environ, diff, original)
Reset the environment to its state before it was frozen by :func:`freeze`. :param str label: The name for the frozen environment. :param bool pop: Destroy the freeze after use; only allow unfreeze once. :param dict environ: The environment to work on; defaults to ``os.environ``. :returns: A context manager to re-freez...
625941f0b5575c28eb68e5a4
def get_accuracy(cm: npt.NDArray) -> float: <NEW_LINE> <INDENT> return float(sum(cm[i][i] for i in range(len(cm)))) / float(cm.sum())
Get the accuaracy by the confusion matrix cm. Parameters ---------- cm : ndarray Returns ------- accuracy : float Examples -------- >>> import numpy as np >>> cm = np.array([[10, 20], [30, 40]]) >>> get_accuracy(cm) 0.5 >>> cm = np.array([[20, 10], [30, 40]]) >>> get_accuracy(cm) 0.6
625941f0283ffb24f3c55e99
def check_credential_exists(name): <NEW_LINE> <INDENT> return Credential.credential_exist(name)
function that checks if the credential exists with that site name :return: boolean
625941f03eb6a72ae02eca8c
def on_failed(self, status_code: int, request: Request): <NEW_LINE> <INDENT> self.update_rate_limit(request) <NEW_LINE> data = request.response.json() <NEW_LINE> error = data["error"] <NEW_LINE> msg = f"请求失败,状态码:{status_code},类型:{error['name']}, 信息:{error['message']}" <NEW_LINE> self.gateway.write_log(msg)
Callback to handle request failed.
625941f04f88993c3716c5ff
def Retrieve(self, request, context): <NEW_LINE> <INDENT> context.set_code(grpc.StatusCode.UNIMPLEMENTED) <NEW_LINE> context.set_details('Method not implemented!') <NEW_LINE> raise NotImplementedError('Method not implemented!')
Missing associated documentation comment in .proto file.
625941f0236d856c2ad44d81
def getSkySeperationFromPixel(self, x1, y1, x2, y2, cd11, cd12, cd21, cd22): <NEW_LINE> <INDENT> ra1, dec1 = self.computeDeltaRaDec(x1, y1, cd11, cd12, cd21, cd22) <NEW_LINE> ra2, dec2 = self.computeDeltaRaDec(x2, y2, cd11, cd12, cd21, cd22) <NEW_LINE> return self.computeSkySeperation(ra1, dec1, ra2, dec2)
Compute the distance on the sphere from x2, y1 to x1, y1. Parameters ---------- x1 : `pandas.Series` X pixel coordinate. y1 : `pandas.Series` Y pixel coordinate. x2 : `pandas.Series` X pixel coordinate. y2 : `pandas.Series` Y pixel coordinate. cd11 : `pandas.Series` [1, 1] element of the local Wcs ...
625941f030c21e258bdfaa42
def remove_item(self, item): <NEW_LINE> <INDENT> self.items.remove(item)
Remove item from the entity's inventory.
625941f073bcbd0ca4b2c614
def sign_input(self, input_index, hash_type, private_key, sub_script): <NEW_LINE> <INDENT> if input_index < 0 or input_index >= len(self.inputs): <NEW_LINE> <INDENT> raise ValueError("Invalid input index.") <NEW_LINE> <DEDENT> inp = self.inputs[input_index] <NEW_LINE> multisig = False <NEW_LINE> if sub_script.is_multis...
Signs an input. Args: input_index (int): The index of the input to sign. hash_type (int): What kind of signature hash to do. private_key (crypto.PrivateKey): private key with which to sign the transaction. sub_script (Script): the scriptPubKey of the corresponding utxo being spent if th...
625941f0796e427e537b0b69
def create_a_record(self, name, values, ttl=60, weight=None, region=None, set_identifier=None, alias_hosted_zone_id=None, alias_dns_name=None): <NEW_LINE> <INDENT> self._halt_if_already_deleted() <NEW_LINE> values = locals() <NEW_LINE> del values['self'] <NEW_LINE> return self._add_record(AResourceRecordSet, **values)
Creates and returns an A record attached to this hosted zone. :param str name: The fully qualified name of the record to add. :param list values: A list of value strings for the record. :keyword int ttl: The time-to-live of the record (in seconds). :keyword int weight: *For weighted record sets only*. Among resource r...
625941f05fc7496912cc3f1c
def get_channel(self, name): <NEW_LINE> <INDENT> channel_object = None <NEW_LINE> for obj in self._channel_list: <NEW_LINE> <INDENT> if obj.name == name: <NEW_LINE> <INDENT> channel_object = obj <NEW_LINE> break <NEW_LINE> <DEDENT> <DEDENT> return channel_object
Gets a Channel by name. :param name: Channel name. :return: The channel object if exists, otherwise None.
625941f0eab8aa0e5d26e0f9
def __init__(self, mob, dest_tile, timed_event_dispatcher): <NEW_LINE> <INDENT> super(WalkToAdjacentTileAction, self).__init__() <NEW_LINE> self.mob = mob <NEW_LINE> self.dest_tile = dest_tile <NEW_LINE> self.source_tile = mob.tile <NEW_LINE> self.timed_event_dispatcher = timed_event_dispatcher <NEW_LINE> self.warmup_t...
:param mob: The mob who is moving :param dest_tile: The Tile the mob is moving to :param timed_event_dispatcher: To register the callbacks :return:
625941f0fbf16365ca6f676f
def create_standard_urls(model, views, view_types=('list', 'add', 'detail', 'update', 'delete')): <NEW_LINE> <INDENT> model_slug = slugify(model._meta.verbose_name) <NEW_LINE> view_pattern = '%s{}%s' % (model.__name__, 'View') <NEW_LINE> urlpatterns = [] <NEW_LINE> if 'top_list' in view_types: <NEW_LINE> <INDENT> urlpa...
Create standard urls based on slugified model name :param model: actual model :param views: views :param view_types: list or tuple ('list', 'add', 'detail', 'update', 'delete') :return:
625941f066656f66f7cbc74b
def delete_bucket(self, bucket): <NEW_LINE> <INDENT> obj = self._buckets.get(bucket) <NEW_LINE> if obj and not obj.empty(): <NEW_LINE> <INDENT> raise S3ResponseError('Bucket %s not empty' % bucket) <NEW_LINE> <DEDENT> self._buckets.pop(bucket, None)
Delete a bucket
625941f016aa5153ce362a17
def merge_morning_evening_data(morning, evening): <NEW_LINE> <INDENT> morning['merge'] = morning['hour_min'].astype(str).str[:5].str.replace(':', '.').astype(float) + 8 <NEW_LINE> evening['merge'] = evening['hour_min'].astype(str).str[:5].str.replace(':', '.').astype(float) <NEW_LINE> merged = pd.merge(morning, evening...
Merges morning and evening data, returns the merged data set, and plots the 95% intervals for total commute time given departure times at 8 hour spreads
625941f0d10714528d600289
def test_was_published_recently_with_future_question(self): <NEW_LINE> <INDENT> time = timezone.now() + datetime.timedelta(days=30) <NEW_LINE> future_question = Question(pub_date=time) <NEW_LINE> self.assertIs(future_question.was_published_recently(), False)
在未来发布的Question应该返回False
625941f00a366e3fb873edbe
def _create_p_layer(mol, auxinfo): <NEW_LINE> <INDENT> p_layer = [] <NEW_LINE> for i, at in enumerate(mol.atoms): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> exp = elements.PeriodicSystem.lone_pairs[at.symbol] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise Exception("Unrecognized element: {}".format(at...
Creates a string with the positions of the atoms that bear an unexpected number of lone pairs. The string can be used to complement the InChI with an additional layer that allows for the differentiation between structures with lone pairs. The string is composed of a prefix ('P_LAYER_PREFIX') followed by the positions ...
625941f007f4c71912b11a24
def test_login(self): <NEW_LINE> <INDENT> r = self.wsgi_fixture.wsgi.get("/asset_manager/asset_manager") <NEW_LINE> self.assertEqual(r.status_code, 302)
测试登录
625941f0c4546d3d9de72fd8
def weight_lattice_realization(self): <NEW_LINE> <INDENT> return self._weight.parent()
Return a realization of the lattice containing the weights of ``self``. EXAMPLES:: sage: La = RootSystem(['C',12]).weight_lattice().fundamental_weights() sage: T = crystals.elementary.T(['C',12], La[9]) sage: T.weight_lattice_realization() Ambient space of the Root system of type ['C', 12] sage: ...
625941f0b830903b967e9ea3
def __init__(self, ip, port): <NEW_LINE> <INDENT> print('new') <NEW_LINE> self.ip = ip <NEW_LINE> self.port = port <NEW_LINE> self.connect()
Constructor method. This method create a TCP/IP client Arguments: ip: the IP adress to be used to connect to the epuck Server. port: the TCP IP port.
625941f02eb69b55b151ce56
def cancel(self, cr, uid, ids, context=None): <NEW_LINE> <INDENT> assert context, 'no context defined' <NEW_LINE> wiz_obj = self.pool.get('wizard') <NEW_LINE> return wiz_obj.open_wizard(cr, uid, context['active_ids'], w_type='back', context=context)
return to picking creation wizard
625941f0627d3e7fe0d693f0
def update_source_hashes(self, instance): <NEW_LINE> <INDENT> self.init_instance(instance) <NEW_LINE> instance._ik['source_hashes'] = dict( (attname, hash(getattr(instance, attname))) for attname in self.get_source_fields(instance)) <NEW_LINE> return instance._ik['source_hashes']
Stores hashes of the source image files so that they can be compared later to see whether the source image has changed (and therefore whether the spec file needs to be regenerated).
625941f05f7d997b8717503c
def create(executor, thread_pool=None, io_loop=None, max_workers=0): <NEW_LINE> <INDENT> if max_workers is None: <NEW_LINE> <INDENT> max_workers = multiprocessing.cpu_count() <NEW_LINE> <DEDENT> io_loop = io_loop or IOLoop.instance() <NEW_LINE> thread_pool = thread_pool or ThreadPoolExecutor(max_workers) <NEW_LINE>...
Factory function for Thread-based Aurora executor objects
625941f00a50d4780f667436
def test_has_key(self): <NEW_LINE> <INDENT> self.assertFalse(self.flash.has_key('error')) <NEW_LINE> self.assertTrue(self.flash.has_key('info'))
FlashScope: Should check if there's a value related with the given key.
625941f0dd821e528d63b743
def _trychar(char, fallback, asciimode=None): <NEW_LINE> <INDENT> if asciimode is True: <NEW_LINE> <INDENT> return fallback <NEW_LINE> <DEDENT> if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> char.encode(sys.stdout.encoding) <NEW_LINE> <DEDENT> except Exception: ...
Logic from IPython timeit to handle terminals that cant show mu Args: char (str): character, typically unicode, to try to use fallback (str): ascii character to use if stdout cannot encode char asciimode (bool): if True, always use fallback Example: >>> char = _trychar('µs', 'us') >>> print('char ...
625941f01f037a2d8b94679b
def __init__(self, ty): <NEW_LINE> <INDENT> StorageType.__init__(self) <NEW_LINE> self.type = ty
Initializes the property type (the C/Cython name for this type), as well as the properties described in the documentation for StorageType.__init__. EXAMPLES:: sage: from sage_setup.autogen.interpreters import * sage: ty_double.class_member_declarations '' sage: ty_double.class_member_initializations ...
625941f0baa26c4b54cb16b8
def test_start_with_device_connected(self): <NEW_LINE> <INDENT> event = Event() <NEW_LINE> event.clear() <NEW_LINE> def _add_handler(): <NEW_LINE> <INDENT> self._logger.debug('Invoked') <NEW_LINE> event.set() <NEW_LINE> <DEDENT> mock_monitor = mock() <NEW_LINE> mock_device = mock() <NEW_LINE> when(mock_device).get_vend...
Test that the add event gets invoked on start-up.
625941f0a05bb46b383ecdbb
def write_script(self, dirname="", fname=""): <NEW_LINE> <INDENT> mylines = self.print_input_options() <NEW_LINE> if dirname == "": <NEW_LINE> <INDENT> dirname = os.getcwd() <NEW_LINE> <DEDENT> if fname == "": <NEW_LINE> <INDENT> fname = 'input.py' <NEW_LINE> <DEDENT> filename = os.path.join(dirname, fname) <NEW_LINE> ...
Write the python input script, created from the *.inp input file. Args: dirname <str>: directory in which to write fname <str>: filename to write Returns: filename <str>: Full file name of the input script created.
625941f08a349b6b435e8711
def add_parameters(params): <NEW_LINE> <INDENT> params.copy_rotation_axes = bpy.props.BoolVectorProperty( size=3, description="Automation axes", default=tuple([i == 0 for i in range(0, 3)]) ) <NEW_LINE> params.tweak_extra_layers = bpy.props.BoolProperty( name="tweak_extra_layers", default=True, description="" ) <NEW_LI...
Add the parameters of this rig type to the RigifyParameters PropertyGroup
625941f0e1aae11d1e74a25c
def get_resource_rules(self): <NEW_LINE> <INDENT> resource_rules = [] <NEW_LINE> for resource_rule in self.resource_rules_map: <NEW_LINE> <INDENT> resource_rules.append(self.resource_rules_map[resource_rule]) <NEW_LINE> <DEDENT> return resource_rules
Get all the resource rules for (resource, RuleAppliesTo.*). Returns: list: A list of ResourceRules.
625941f0167d2b6e31219133
def __init__(self, xknx, group_address=None, group_address_state=None, device_name=None, after_update_cb=None): <NEW_LINE> <INDENT> super(RemoteValueColorRGBW, self).__init__( xknx, group_address, group_address_state, device_name=device_name, after_update_cb=after_update_cb) <NEW_LINE> self.previous_value = (0, 0, 0, 0...
Initialize remote value of KNX DPT 251.600 (DPT_Color_RGBW).
625941f0507cdc57c6307288
def checkParameters(self): <NEW_LINE> <INDENT> self.DEBUG("EDPluginExecMtz2Variousv1_0.checkParameters") <NEW_LINE> self.checkMandatoryParameters(self.dataInput,"Data Input is None")
Checks the mandatory parameters.
625941f0ff9c53063f47c78f
def run(self, qt_name, qt_id): <NEW_LINE> <INDENT> rc = self.tcl("ixNet exec run [ixNet getRoot]/quickTest/{0}:{1}".format(qt_name, qt_id)) <NEW_LINE> return rc
Run QuickTest until completion. Args: qt_name(str): QuickTest name qt_id(int): QuickTest id Returns: str: Result of execution
625941f063f4b57ef00016a7
def Reduction(self): <NEW_LINE> <INDENT> if len(self.d1.house)==1: <NEW_LINE> <INDENT> self.d2.house = list(set(self.d2.house)-set(self.d1.house)) <NEW_LINE> <DEDENT> elif len(self.d2.house)==1: <NEW_LINE> <INDENT> self.d1.house = list(set(self.d1.house)-set(self.d2.house)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT>...
removes value in x or y domain depending on which object has only one value
625941f015fb5d323cde10b7
def testBinaryFramerPopulate(self): <NEW_LINE> <INDENT> request = ModbusRequest() <NEW_LINE> self._binary.populateResult(request) <NEW_LINE> self.assertEqual(0x00, request.unit_id)
Test a binary frame packet build
625941f0d164cc61757832ee
def parse(self, filename): <NEW_LINE> <INDENT> with abiinspect.YamlTokenizer(filename) as r: <NEW_LINE> <INDENT> doc = r.next_doc_with_tag("!Autoparal") <NEW_LINE> try: <NEW_LINE> <INDENT> d = yaml.load(doc.text_notag) <NEW_LINE> return ParalHints(info=d["info"], confs=d["configurations"]) <NEW_LINE> <DEDENT> except: <...
Read the AutoParal section (YAML format) from filename. Assumes the file contains only one section.
625941f02eb69b55b151ce57
def gef_accurate(self,omegac): <NEW_LINE> <INDENT> energystates = self.eigenstates_logical_states(omegac) <NEW_LINE> energies = [energystates[0][0], energystates[1][0]] <NEW_LINE> return (energies[0]-energies[1])/2
The more accurate effective coupling constant between qubits 1 and 2. When used, it is assumed that the eigenstates of the system don't change when changing omegac, just the eigenenergies. Otherwise should be accurate if the computational states used are the ones derived from the eigenstates.
625941f03617ad0b5ed68495
def do_print(self, args): <NEW_LINE> <INDENT> self.model.print()
Print the game
625941f03c8af77a43ae3d46
def check_df_image_size(df: pd.DataFrame, target_column: str) -> None: <NEW_LINE> <INDENT> col_indx = list(df.columns).index(target_column) <NEW_LINE> for i, row in df.iterrows(): <NEW_LINE> <INDENT> im = Image.open(row[col_indx]) <NEW_LINE> w, h = im.size <NEW_LINE> df.at[i, 'width'] = w <NEW_LINE> df.at[i, 'height'] ...
Checks image sizes from Pandas DataFrame and adds two additional columns to it with sizes :param df: Pandas dataFrame where you have info. :param target_column: Column where paths to images are defined :return: None
625941f0cad5886f8bd27577
def regex_type(arg_value): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> arg_value = re.compile(arg_value) <NEW_LINE> <DEDENT> except re.error as error: <NEW_LINE> <INDENT> raise argparse.ArgumentTypeError( "'{}' isn't a valid regular expression: {}".format( arg_value, error ) ) <NEW_LINE> <DEDENT> return arg_value
Checks whether an argument compiles to a valid regex and returns the compiled regex.
625941f0ad47b63b2c50a51f
def setUp(self): <NEW_LINE> <INDENT> self._mock_host_conn = mock.Mock(spec_set=SshClient) <NEW_LINE> self._mock_shell = mock.Mock(spec_set=SshShell) <NEW_LINE> self._mock_host_conn.open_shell.return_value = self._mock_shell <NEW_LINE> patcher = mock.patch.object(utils, 'sleep', autospec=True) <NEW_LINE> patcher.start()...
Create the mock objects used in the initialization of the DiskFcp.
625941f023e79379d52eeafb
def marshal(self): <NEW_LINE> <INDENT> return [Published.MESSAGE_TYPE, self.request, self.publication]
Marshal this object into a raw message for subsequent serialization to bytes. :returns: list -- The serialized raw message.
625941f07cff6e4e81117f24
def __retrieve_results_async(self): <NEW_LINE> <INDENT> while not self.__shutdown_result_thread: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.__retrieve_result.wait() <NEW_LINE> if self.__shutdown_result_thread: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> responses = self.__proxy.transp...
The method running in a separate thread which is responsible for retrieving the result of the service call and invoking the callback methods.
625941f08a43f66fc4b545fe
def make_call(self, url, expected_status=200, method='get', data=None, content_type=None, **kwargs): <NEW_LINE> <INDENT> user = kwargs.pop('user', 'student_enrolled_not_on_team') <NEW_LINE> if user: <NEW_LINE> <INDENT> self.login(user) <NEW_LINE> <DEDENT> func = getattr(self.client, method) <NEW_LINE> if content_type: ...
Makes a call to the Team API at the given url with method and data. If a user is specified in kwargs, that user is first logged in.
625941f0e8904600ed9f24d6
def agencies_id_get_with_http_info(self, id, **kwargs): <NEW_LINE> <INDENT> all_params = ['id'] <NEW_LINE> all_params.append('callback') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LINE> params = locals() <...
Récupérer une agence Récupérer une agence par son identifiant This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. >>> def callback_function(response): >>> pprint(response) >>> >>> thread = api.a...
625941f0796e427e537b0b6a
def set_params(self, *args, **kwargs): <NEW_LINE> <INDENT> return _iio_swig.fmcomms2_source_f32c_set_params(self, *args, **kwargs)
set_params(fmcomms2_source_f32c self, unsigned long long frequency, unsigned long samplerate, unsigned long bandwidth, bool quadrature, bool rfdc, bool bbdc, char const * gain1, double gain1_value, char const * gain2, double gain2_value, char const * rf_port_select, char const * filter, bool auto_filter=True)
625941f02c8b7c6e89b35d5b
def get_list_anagrams_v2(words): <NEW_LINE> <INDENT> anagram_groups = {} <NEW_LINE> for word in words: <NEW_LINE> <INDENT> group = anagram_groups.setdefault("".join(sorted(list(word))), set([word])) <NEW_LINE> group.add(word) <NEW_LINE> <DEDENT> return list(anagram_groups.values())
The solution is the same as v1 but is less verbose and takes advantage of setdefault method
625941f0b57a9660fec33e2c
def perform_skel_and_cell_analysis(self, groups_dict): <NEW_LINE> <INDENT> if self.output_anal_path is None: <NEW_LINE> <INDENT> print("Error!") <NEW_LINE> morphious_gui.error_box(title='Error!', message='Select a location to save your analysis file to') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('running anal...
perform skeleton and cell analysis Args: groups_dict (dictionary): file : group dictionary to regroup analysis
625941f0925a0f43d254a41c
def get_ise_anc_policies( host=ISE.get("host"), port=ISE.get("port"), username=ISE.get("username"), password=ISE.get("password"), ): <NEW_LINE> <INDENT> print(blue("\n==> Getting ISE ANC policies")) <NEW_LINE> headers = { 'Content-Type': "application/json", 'Accept': "application/json" } <NEW_LINE> authentication = HTT...
Get a list of configured ISE Adaptive Network Control (ANC) policies.
625941f066673b3332b92630
def flush(self): <NEW_LINE> <INDENT> indices = np.arange(0, self.index) <NEW_LINE> if self.size == self.capacity: <NEW_LINE> <INDENT> indices = np.concatenate([np.arange(self.index, self.capacity), indices]) <NEW_LINE> <DEDENT> data = self.get_records_at_indices(indices) <NEW_LINE> self.clear() <NEW_LINE> return data
Empties the buffer and returns all records in FIFO-order. Returns: any: All records of this buffer in the correct FIFO-order.
625941f08da39b475bd6551b
def setValue_InCorrect0(self): <NEW_LINE> <INDENT> self.assertRaises(ATOM3BadAssignmentValue, self.atc.setValue, 'StateName')
Tries setting the incorrect value 'StateName'
625941f0442bda511e8be9af
def new_vertical(self, size, pad=None, hpad=None, hpad_left=True, pack_start=False, **kwargs): <NEW_LINE> <INDENT> if pad: <NEW_LINE> <INDENT> if not isinstance(pad, Size._Base): <NEW_LINE> <INDENT> pad = Size.from_any(pad, fraction_ref=self._yref) <NEW_LINE> <DEDENT> if pack_start: <NEW_LINE> <INDENT> self._vertical.i...
similar to new_vertical but adds a horizontal pad
625941f07c178a314d6efa09
def create_project_dashboard(self, owner, project, body, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> return self.create_project_dashboard_with_http_info(owner, project, body, **kwargs)
Create project dashboard # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_project_dashboard(owner, project, body, async_req=True) >>> result = thread.get() :param owner: Owner of the namespace (required) :t...
625941f0de87d2750b860339
def repl_view(self, view): <NEW_LINE> <INDENT> repl_id = view.settings().get("repl_id") <NEW_LINE> if repl_id not in self.repl_views: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> rv = self.repl_views[repl_id] <NEW_LINE> rv.update_view(view) <NEW_LINE> return rv
Returns the rview associated with a Sublime view, if any Causes the found rview to update
625941f0236d856c2ad44d82
def retrieval_acc(output, target, instances=4): <NEW_LINE> <INDENT> _, pred = output.topk(instances, 1, True, False) <NEW_LINE> d_mat -= torch.eye(d_mat.size(0)) <NEW_LINE> _, pred = torch.sort(d_mat, dim=1) <NEW_LINE> d_mats = [get_distance_matrix(f) for f in features] <NEW_LINE> preds = [torch.sort(d.cpu(), dim=1)[1]...
UKB-like accuracy criterion. Must be applied to the whole dataset.
625941f01b99ca400220b053
def testRemoveClass2ClassName(self): <NEW_LINE> <INDENT> c1name = self.layer.getClass(0).name <NEW_LINE> c = self.layer.removeClass(1) <NEW_LINE> assert self.layer.getClass(0).name == c1name
RemoveClassTestCase.testRemoveClass2ClassName: confirm removing the layer's second class reverts the name of the first class
625941f06aa9bd52df037347
def role_required(role): <NEW_LINE> <INDENT> def decorator(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def wrapper(*args, **kwargs): <NEW_LINE> <INDENT> if not current_user.is_authenticated or current_user.role < role: <NEW_LINE> <INDENT> abort(404) <NEW_LINE> <DEDENT> return func(*args, **kwargs) <NEW_LINE> <DE...
带参数的装饰器,用它来保护路由函数只被特定的用户访问
625941f060cbc95b062c6ae3
def init_app(self, app): <NEW_LINE> <INDENT> app.config.setdefault('RELOADED_TEMP_FILE', '.reloaded') <NEW_LINE> app.config.setdefault('RELOADED_URL_PREFIX', '/_reloaded') <NEW_LINE> app.config.setdefault('RELOADED_EXTENSIONS', self.default_extensions) <NEW_LINE> blueprint = Blueprint( 'reloaded', __name__, static_fold...
Should somehow support a factory... but probably won't
625941f03cc13d1c6d3c7917
def random_sentence_and_predicates(): <NEW_LINE> <INDENT> nb_sentences = len(param.SENTENCE_TO_PREDICATE.items()) <NEW_LINE> rand_sentence_id_1 = np.random.choice(nb_sentences) <NEW_LINE> sentence_1, predicate_1 = param.SENTENCE_TO_PREDICATE.items()[rand_sentence_id_1] <NEW_LINE> if np.random.rand() < 0.5: <NEW_LINE> <...
Returns a ranodm sentence and predicates it contains. 50% of the sentences concern one object only, 50% two.
625941f04f6381625f114fda
def validate(config): <NEW_LINE> <INDENT> vstatus = True <NEW_LINE> vmsg = "Valid beacon configuration" <NEW_LINE> if not isinstance(config, list): <NEW_LINE> <INDENT> vstatus = False <NEW_LINE> vmsg = "Configuration for btmp beacon must be a list." <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> config = salt.utils.beac...
Validate the beacon configuration
625941f0be7bc26dc91cdb94
def test_get_release_info(self): <NEW_LINE> <INDENT> self.cluster.release.version = '2014.2.2-6.0.1' <NEW_LINE> release = self.plugin_adapter.get_release_info(self.cluster.release) <NEW_LINE> self.assertEqual(release, self.plugin_metadata['releases'][0])
Should return 1st plugin release info which matches release
625941f0435de62698dfe1ed
def collect_consecutive_tags(self, codes, start=0, end=None): <NEW_LINE> <INDENT> codes = frozenset(codes) <NEW_LINE> index = int(start) <NEW_LINE> if end is None: <NEW_LINE> <INDENT> end = len(self) <NEW_LINE> <DEDENT> bag = self.__class__() <NEW_LINE> while index < end: <NEW_LINE> <INDENT> tag = self[index] <NEW_LINE...
Collect all consecutive tags with code in codes, start and end delimits the search range. A tag code not in codes ends the process. Args: codes: iterable of group codes start: start index as int end: end index as int, if None end index = len(self) Returns: collected tags as Tags().
625941f00383005118ecfb80
def _get_subnets_from_network(self, context, network, vif, instance_host=None): <NEW_LINE> <INDENT> ipam_subnets = self.ipam.get_subnets_by_net_id(context, network['project_id'], network['uuid'], vif.uuid) <NEW_LINE> subnets = [] <NEW_LINE> for subnet in ipam_subnets: <NEW_LINE> <INDENT> subnet_dict = {'cidr': subnet['...
Returns the 1 or 2 possible subnets for a nova network.
625941f056ac1b37e6264763
def split_image(image, split_seq=None): <NEW_LINE> <INDENT> if split_seq is None: <NEW_LINE> <INDENT> split_seq = get_split_seq(get_projection_x(image)) <NEW_LINE> <DEDENT> length = len(split_seq) <NEW_LINE> imgs = [[] for i in range(length)] <NEW_LINE> res = [] <NEW_LINE> for w in range(image.size[1]): <NEW_LINE> <IND...
分割后的图片,x轴分割后,同时去掉y轴上线多余的空白 :param image: :param split_seq: :return:
625941f0d99f1b3c44c67b24
def test_GetCandle_candleisexists(self): <NEW_LINE> <INDENT> createdf.connectandsave() <NEW_LINE> duration = "h" <NEW_LINE> api_key = key.api_key <NEW_LINE> api_secret = key.api_secret <NEW_LINE> c = get_data.Candle(api_key, api_secret) <NEW_LINE> now_time = c.TruncateDateTime(duration=duration, time=datetime.datetime....
[summary] create new_candle in Candle_1h, then candle=GetCandle('h') is equal to new_candle
625941f0c432627299f051ea
def draw_credit_menu(self, mx, my, mb, event): <NEW_LINE> <INDENT> if not self._credits_page_running(): <NEW_LINE> <INDENT> self.credits_reset() <NEW_LINE> return "menu" <NEW_LINE> <DEDENT> if mb[0] == 1 and event.type == pygame.MOUSEBUTTONUP: <NEW_LINE> <INDENT> self.credits_reset() <NEW_LINE> return "menu" <NEW_LINE>...
Draw credit scroll - exit on click :return: return what page game need to go next
625941f04527f215b584c9f1