code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def visit_children_decor(func): <NEW_LINE> <INDENT> @wraps(func) <NEW_LINE> def inner(cls, tree): <NEW_LINE> <INDENT> values = cls.visit_children(tree) <NEW_LINE> return func(cls, values) <NEW_LINE> <DEDENT> return inner
See Interpreter
625941e938b623060ff0b28f
def test_no_pusher(self, client): <NEW_LINE> <INDENT> profile = factories.ProfileFactory.create() <NEW_LINE> with mock.patch('portfoliyo.pusher.auth.allow') as mock_allow: <NEW_LINE> <INDENT> with mock.patch('portfoliyo.pusher.auth.get_pusher') as mock_get_p: <NEW_LINE> <INDENT> mock_get_p.return_value = None <NEW_LINE...
Returns 403 if Pusher not configured.
625941e9596a897236089f5c
def zero(grid): <NEW_LINE> <INDENT> return ZeroNode(grid)
The zero operator. :param Grid grid: The grid where the operator is defined.
625941e915baa723493c441b
def response_not_found(): <NEW_LINE> <INDENT> response = b"\r\n".join([ b"HTTP/1.1 404 NOT FOUND", b"", b"Requested item not found." ]) <NEW_LINE> return response
Returns a 404 Not Found response
625941e9b830903b967e9da8
def amexpos(n_points, t0=None, spread=None, kind="bilateral"): <NEW_LINE> <INDENT> if t0 is None: <NEW_LINE> <INDENT> t0 = np.round(n_points / 2) <NEW_LINE> <DEDENT> if spread is None: <NEW_LINE> <INDENT> spread = 2 * np.sqrt(n_points) <NEW_LINE> <DEDENT> if n_points <= 0: <NEW_LINE> <INDENT> raise TypeError <NEW_LINE>...
Exponential amplitude modulation. `amexpos` generates an exponential amplitude modulation starting at time `t0` and spread proportioanl to `spread`. :param n_points: Number of points. :param kind: "bilateral" (default) or "unilateral" :param t0: Time center. :param spread: Standard deviation. :type n_points: int :typ...
625941e982261d6c526ab949
def _search_for_edge_ids(path): <NEW_LINE> <INDENT> for label in os.listdir(path): <NEW_LINE> <INDENT> label_path = os.path.join(path, label) <NEW_LINE> if os.path.isfile(label_path): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> for each in os.listdir(label_path): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ident ...
Internal helper function to search for edges identity numbers based in the directories and the head and tail vertices identity numbers. :param path: Edges Path to find number directories. :type path: :class:`str` :return: Yields the integer number, head id, label, tail id and the properties file path if found. :rt...
625941e91f5feb6acb0c4feb
def get_type_set(self): <NEW_LINE> <INDENT> if self._kwargs['syntax'] not in ['TYPE']: <NEW_LINE> <INDENT> raise errors.IllegalState() <NEW_LINE> <DEDENT> return self._kwargs['type_set']
Gets the set of acceptable ``Types``. return: (osid.type.Type) - a set of ``Types`` or an empty array if not restricted raise: IllegalState - syntax is not a ``TYPE`` *compliance: mandatory -- This method must be implemented.*
625941e9cc40096d61595df0
def _check_density(density, n_features): <NEW_LINE> <INDENT> if density is 'auto': <NEW_LINE> <INDENT> density = min(1 / np.sqrt(n_features), 1 / 3.) <NEW_LINE> <DEDENT> elif density <= 0 or density > 1: <NEW_LINE> <INDENT> raise ValueError("Expected density in range ]0, 1], got: %r" % density) <NEW_LINE> <DEDENT> retu...
Factorize density check according to Li et al.
625941e9ec188e330fd5ac38
def test_bcl2fastq_2_17_1_14(self): <NEW_LINE> <INDENT> self.mockbcl2fastq.bcl2fastq_217() <NEW_LINE> self.mockbcl2fastq.set_path() <NEW_LINE> exe = self.mockbcl2fastq.exes[0] <NEW_LINE> path,name,version = bcl_to_fastq_info() <NEW_LINE> self.assertEqual(path,exe) <NEW_LINE> self.assertEqual(name,'bcl2fastq') <NEW_LINE...
Collect info for bcl2fastq 2.17.1.14
625941e9377c676e91272649
def addIdleToBox(self,pod): <NEW_LINE> <INDENT> for box in self.boxesContainingNodes: <NEW_LINE> <INDENT> if box.inBox(pod.x,pod.y): <NEW_LINE> <INDENT> box.currentPodsContained.append(pod) <NEW_LINE> pod.idleBox = box <NEW_LINE> return
loops through boxes to see if coordinate matches
625941e991f36d47f21ac99a
def test_empty_rsa_key(self): <NEW_LINE> <INDENT> empty_key_handler = PlatformKeyHandler(key_pem='') <NEW_LINE> with self.assertRaises(exceptions.RsaKeyNotSet): <NEW_LINE> <INDENT> empty_key_handler.encode_and_sign({}) <NEW_LINE> <DEDENT> self.assertEqual( empty_key_handler.get_public_jwk(), {'keys': []} )
Check that class doesn't fail instancing when not using a key.
625941e976e4537e8c351b18
def calculate_deviation(variance) : <NEW_LINE> <INDENT> return sqrt(variance)
Обчислює середнє квадратичне відхилення
625941e95f7d997b87174f3e
def put(self, service, agent_host): <NEW_LINE> <INDENT> if 'port_id' in service['loadbalancer']: <NEW_LINE> <INDENT> port_id = service['loadbalancer']['port_id'] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> port_id = None <NEW_LINE> <DEDENT> loadbalancer_id = service['loadbalancer']['id'] <NEW_LINE> tenant_id = servic...
Add a service to the cache.
625941e9a8ecb033257d356e
def delete(self, ids): <NEW_LINE> <INDENT> if not isinstance(ids, list): <NEW_LINE> <INDENT> ids = [ids]; <NEW_LINE> <DEDENT> for id in ids: <NEW_LINE> <INDENT> ds = [d for d in self.data if d[self.pk]==id] <NEW_LINE> for d in ds: <NEW_LINE> <INDENT> self.data.remove(d);
Deletes by id
625941e9d268445f265b5311
def public_key(self, keyid=None): <NEW_LINE> <INDENT> return self.convert_public_key(self.key(keyid))
Get RSAobj for the public key
625941e9ad47b63b2c50a421
def remove_empty_nodes(self): <NEW_LINE> <INDENT> self.children = [c for c in self.children if c.remove_empty_nodes()] <NEW_LINE> if not self.children: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return True
Removes empty nodes in the subtree recursively. Returns false if this node is empty after clearing the subtree, and true otherwise.
625941e9ab23a570cc250629
def sample_triple(self, dump=True, load_save=False): <NEW_LINE> <INDENT> sample_file_name = ( "triple_" + self.config["dataset"]["dataset"] + ( ("_" + str(self.config["dataset"]["percent"] * 100)) if "percent" in self.config else "" ) + "_" + str(self.config["model"]["n_sample"]) if "percent" in self.config else "" + "...
Sample triples or load triples samples from files. This method is only applicable for basket based Recommender. Returns: None
625941e97b180e01f3dc4c96
def get(self, request, team_id=None, event_id=None, vote_id=None): <NEW_LINE> <INDENT> user = request.user <NEW_LINE> event = Event.get_by_id(event_id) <NEW_LINE> if not vote_id: <NEW_LINE> <INDENT> votes = event.vote_set.all() <NEW_LINE> data = {'votes': [vote.to_dict() for vote in votes]} <NEW_LINE> return JsonRespon...
Method that handles GET request. :param request: the accepted HTTP request :type request: HttpRequest object :param team_id: id of the certain team :type team_id: int :param event_id: id of the certain event :type event_id: int :param vote_id: id of the certain vote :type vote_id: int :return: HttpResponse with st...
625941e9097d151d1a2232fa
def __init__(self, plotly_name, **kwargs): <NEW_LINE> <INDENT> self._process_kwargs(**kwargs) <NEW_LINE> self._plotly_name = plotly_name <NEW_LINE> self._validators = {} <NEW_LINE> self._compound_props = {} <NEW_LINE> self._compound_array_props = {} <NEW_LINE> self._orphan_props = {} <NEW_LINE> self._parent = None <NEW...
Construct a new BasePlotlyType Parameters ---------- plotly_name : str The lowercase name of the plotly object kwargs : dict Invalid props/values to raise on
625941e907d97122c4178d39
def test_table_count(): <NEW_LINE> <INDENT> number_of_messages = 45 <NEW_LINE> assert len(_SBP_TABLE) == number_of_messages
Test number of available messages to deserialize.
625941e997e22403b379d43e
def get_max_close(symbol): <NEW_LINE> <INDENT> df = pd.read_csv("data/{}.csv".format(symbol), ) <NEW_LINE> return df['Close'].max()
Return the maximum closing value for stock indicated by symbol
625941e91f037a2d8b94669f
def pc_noutput_items(self): <NEW_LINE> <INDENT> return _ccsds_swig.softbit_msg_source_f_sptr_pc_noutput_items(self)
pc_noutput_items(softbit_msg_source_f_sptr self) -> float
625941e930bbd722463cc26b
def dies_cinerum(self): <NEW_LINE> <INDENT> if self.__year == 1300 or self.__year == 1400 or self.__year == 1500: <NEW_LINE> <INDENT> return self.moveable_feast(self.easter(), 45, 0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.moveable_feast(self.easter(), 46, 0)
Ash Wednesday/popeleční středa
625941e945492302aab5e76b
def perturb(mcell, distance=0.02): <NEW_LINE> <INDENT> for site in mcell._sites: <NEW_LINE> <INDENT> vec = _get_rand_vec(distance) <NEW_LINE> vec = car_to_frac(mcell._lattice, vec) <NEW_LINE> site[0] = numpy.array(site[0]) + vec
对一个结构的所有原子进行扰动,扰动的距离是distance,单位是A distance默认为0.02A perturb sites one by one
625941e9cc0a2c11143dd335
def depthFirstSearch(problem): <NEW_LINE> <INDENT> closed = set() <NEW_LINE> fringe = util.Stack() <NEW_LINE> fringe.push( [problem.getStartState(), []] ) <NEW_LINE> while True: <NEW_LINE> <INDENT> if fringe.isEmpty(): return False <NEW_LINE> node = fringe.pop() <NEW_LINE> if problem.isGoalState( node[0] ): <NEW_LINE> ...
Search the deepest nodes in the search tree first. Returns a list of actions that reaches the goal.
625941e924f1403a92601005
def _get_customer(self, strip_id=False): <NEW_LINE> <INDENT> customer = Customer.deserialize({ 'chats': [], 'first_name': u'Test', 'last_name': u'User', 'phones': [], 'created_at': '2017-09-23T20:12:43Z', 'modified_at': '2017-12-13T22:39:59Z', 'websites': [], 'emails': [], 'full_name': u'Test User', 'gender': 'unknown'...
Return a Customer object.
625941e94f88993c3716c505
def t60_fitzroy(surfaces, alpha, volume, c=343): <NEW_LINE> <INDENT> Sx = np.sum(surfaces[0:2]) <NEW_LINE> Sy = np.sum(surfaces[2:4]) <NEW_LINE> Sz = np.sum(surfaces[4:6]) <NEW_LINE> St = np.sum(surfaces) <NEW_LINE> alpha = _is_1d(alpha) <NEW_LINE> a_x = np.average(alpha[:, 0:2], weights=surfaces[0:2], axis=1) <NEW_LIN...
Reverberation time according to Fitzroy. :param surfaces: Surfaces :math:`S`. :param alpha: Mean absorption coefficient :math:`\alpha` or by frequency bands :param volume: Volume of the room :math:`V`. :param c: Speed of sound :math:`c`.
625941e955399d3f05588b5a
def get_enabled_services(zone): <NEW_LINE> <INDENT> with ignore_dbus_error(dbus_error='ServiceUnknown'): <NEW_LINE> <INDENT> zone_proxy = _get_dbus_proxy(_FIREWALLD_OBJECT, _ZONE_INTERFACE) <NEW_LINE> return zone_proxy.getServices('(s)', zone) <NEW_LINE> <DEDENT> return []
Return the status of various services currently enabled
625941e950485f2cf553d23e
def appGet(*args, **kwargs): <NEW_LINE> <INDENT> print >> sys.stderr, "dxpy.appGet is deprecated; please use app_get instead." <NEW_LINE> return app_get(*args, **kwargs)
.. deprecated:: 0.42.0 Use :func:`app_get()` instead.
625941e9b57a9660fec33d2d
def reverse(input_list): <NEW_LINE> <INDENT> output_list = [] <NEW_LINE> list_length = len(input_list) <NEW_LINE> for index in range(list_length-1, -1, -1): <NEW_LINE> <INDENT> output_list.append(input_list[index]) <NEW_LINE> <DEDENT> return output_list
Reverses a list :param input_list: A list of strings (any list would work though) :return: A list, in reverse order
625941e90fa83653e465745b
def getProperties(self): <NEW_LINE> <INDENT> return { 'uuid': self.uuid, 'fqn': self.fqn, 'pluginType': self.pluginType }
Get plugin instance properties :rtype: dict[str:object]
625941e994891a1f4081bf4e
def __len__(self): <NEW_LINE> <INDENT> return len(self._queue)
Return size of queue with len.
625941e9fff4ab517eb2f8e2
def lsview(self, args): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> command = 'cleartool lsview' <NEW_LINE> for key in args: <NEW_LINE> <INDENT> if not key == 'command': <NEW_LINE> <INDENT> command += ' ' + key + ' ' + args[key] <NEW_LINE> <DEDENT> <DEDENT> response = self.cleartoolSsh.write(command) <NEW_LINE> if len...
Send lsview command.
625941e9d268445f265b5312
def __init__(self, brain_name, brain_param): <NEW_LINE> <INDENT> self.brain_name = brain_name <NEW_LINE> self.state_space_size = brain_param["stateSize"] <NEW_LINE> self.number_observations = 0 <NEW_LINE> self.action_space_size = brain_param["actionSize"] <NEW_LINE> self.action_space_type = brain_param["actionSpaceType...
Contains all brain-specific parameters. :param brain_name: Name of brain. :param brain_param: Dictionary of brain parameters.
625941e97b25080760e398f9
def slave(timeout=6): <NEW_LINE> <INDENT> radio.startListening() <NEW_LINE> buffer = b"World \x00" + bytes(counter) <NEW_LINE> radio.writeAckPayload(1, buffer) <NEW_LINE> start_timer = time.monotonic() <NEW_LINE> while (time.monotonic() - start_timer) < timeout: <NEW_LINE> <INDENT> has_payload, pipe_number = radio.avai...
Listen for any payloads and print the transaction :param int timeout: The number of seconds to wait (with no transmission) until exiting function.
625941e9d99f1b3c44c67a29
def get_posts_title(): <NEW_LINE> <INDENT> posts_path = "../_posts/" <NEW_LINE> for file_name in reversed(os.listdir(posts_path)): <NEW_LINE> <INDENT> if is_post_file(file_name): <NEW_LINE> <INDENT> with open(posts_path + file_name, "r", encoding = "utf-8") as post_file: <NEW_LINE> <INDENT> post_date = None <NEW_LINE> ...
获取文章的日期和标题 :return:
625941e929b78933be1e5b49
def start_thread(func, thread_args, pool_size = 5): <NEW_LINE> <INDENT> thread_list = [] <NEW_LINE> result_list = [] <NEW_LINE> i=0 <NEW_LINE> thead_args_list = tools.split_list(thread_args, pool_size) <NEW_LINE> for args_list in thead_args_list: <NEW_LINE> <INDENT> i+=1 <NEW_LINE> obj = CThread() <NEW_LINE> obj.setNam...
简单的线程池,函数内不能有竞争 分配pool个线程做执行同一个函数
625941e9cad5886f8bd2747c
def p_define_class(p): <NEW_LINE> <INDENT> if len(p) == 8: <NEW_LINE> <INDENT> p[0] = Statement(StatementType.CLASS_DEFINE, p.lineno(1), {'class_name': p[2], 'properties': [], 'methods': p[5]}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> p[0] = Statement(StatementType.CLASS_DEFINE, p.lineno(1), {'class_name': p[2], '...
define_class : CLASS IDENT LC newline define_class_properties newline define_methods newline RC | CLASS IDENT LC newline define_methods newline RC
625941e96e29344779a62ab3
def add_shooping_list(self, title, store_name): <NEW_LINE> <INDENT> shopping_service.add_shopping_list('test_title', 'test_store')
Helper method to add shopping list :param title: :param store_name: :return:
625941e996565a6dacc8fb6d
def ramaining(self): <NEW_LINE> <INDENT> return self.next - time.time()
Calculate remaining time in interval :return: float, remaining time before end of interval
625941e9f9cc0f698b140a9a
def _convert_array(self,X,max_len): <NEW_LINE> <INDENT> new_X=[] <NEW_LINE> for ele in X: <NEW_LINE> <INDENT> if len(ele)>=max_len: <NEW_LINE> <INDENT> s=ele[:max_len] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s=list(ele[:]) <NEW_LINE> ss=[0]*(max_len-len(ele)) <NEW_LINE> s.extend(ss) <NEW_LINE> <DEDENT> new_X.appe...
将样本的X转换为矩阵 :param X: :return:
625941e960cbc95b062c69e7
def set_gaze_output_frequency(self, gaze_output_frequency): <NEW_LINE> <INDENT> return tobii_pro.set_gaze_output_frequency(self.__address, gaze_output_frequency)
Sets the gaze output frequency of the eye tracker. See @ref find_all_eyetrackers or EyeTracker.__init__ on how to create an EyeTracker object. <CodeExample>gaze_output_frequencies.py</CodeExample> Args: gaze_output_frequency: The gaze output frequency as a float value. Raises: EyeTrackerConnectionFailedError EyeTrack...
625941e9bde94217f3683290
def sex2gol(grism='', config='', in_sex='', use_direct=True, direct=None, dir_hdu=None, spec_hdu=None, out_sex=None, silent=False): <NEW_LINE> <INDENT> from . import axeutils <NEW_LINE> from . import pysex2gol <NEW_LINE> axeutils.axe_setup() <NEW_LINE> sex2gol = pysex2gol.Sex2GolPy(grism, config, in_sex=in_sex, dirname...
Function for the aXe task SEX2GOL
625941e97d847024c06be763
def extractVars(*names,**kw): <NEW_LINE> <INDENT> depth = kw.get('depth',0) <NEW_LINE> callerNS = sys._getframe(depth+1).f_locals <NEW_LINE> return dict((k,callerNS[k]) for k in names)
Extract a set of variables by name from another frame. :Parameters: - `*names`: strings One or more variable names which will be extracted from the caller's frame. :Keywords: - `depth`: integer (0) How many frames in the stack to walk when looking for your variables. Examples: In [2]: def func(x): ...
625941e9be8e80087fb210df
def fac(n): <NEW_LINE> <INDENT> if n <=1: <NEW_LINE> <INDENT> return 1 <NEW_LINE> <DEDENT> return n * fac(n-1)
returns n*(n-1)*(n-2)...*1, n>1 1, n <=1
625941e9aad79263cf390eec
def test_read_dns_forwader(self): <NEW_LINE> <INDENT> pass
Test case for read_dns_forwader Retrieve a DNS forwarder # noqa: E501
625941e9e76e3b2f99f3aca8
def set_vcomh_deselect_level(self, level): <NEW_LINE> <INDENT> assert 0 <= level < 8, "Level must be between 0 (0.65*Vcc) and 7 (1.07*Vcc)" <NEW_LINE> value = (level << 4) <NEW_LINE> self.command([0xdb, value])
Sets the Vcomh deselect level.
625941e9b5575c28eb68e4a8
def interpret_output_filename(filename): <NEW_LINE> <INDENT> match = _output_file_re.search(filename) <NEW_LINE> fragment, cross_fold_index, seed = match.groups() <NEW_LINE> cross_fold_index = int(cross_fold_index) <NEW_LINE> seed = int(seed) <NEW_LINE> return fragment, cross_fold_index, seed
Parse the information in the filename.
625941e9167d2b6e31219038
@lD.log(logBase + '.commitDataList') <NEW_LINE> def commitDataList(logger, query, values, dbName=None): <NEW_LINE> <INDENT> val = True <NEW_LINE> try: <NEW_LINE> <INDENT> db = jsonref.load(open('../config/db.json')) <NEW_LINE> if (dbName is None) and ('defaultDB' in db): <NEW_LINE> <INDENT> dbName = db['defaultDB'] <NE...
query data from the database Query the data over here. If there is a problem with the data, it is going to return the value of None, and log the error. Your program needs to check whether there was an error with the query by checking for a ``None`` return value Parameters ---------- logger : {logging.logger} log...
625941e9de87d2750b86023b
def S(qubit): <NEW_LINE> <INDENT> s = np.matrix([ [1, 0], [o, i] ]) <NEW_LINE> O = reduce( np.kron, [s if i == qubit else self.I for i in range(self.numQubits)]) <NEW_LINE> self.stateVector = np.dot(self.stateVector, O)
S-gate is a R-phi gate with phi=PI/2. It essentials rotates the qubit by a quarter. params: qubit (Target qubit)
625941e92c8b7c6e89b35c61
def show_rta_route (rta, l): <NEW_LINE> <INDENT> rta_type = rta[1] <NEW_LINE> fieldname = rtatypes[rta_type] <NEW_LINE> if fieldname in ['RTA_DST', 'RTA_PREFSRC', 'RTA_GATEWAY']: <NEW_LINE> <INDENT> print (fieldname, bytes_to_ipaddr(l)) <NEW_LINE> <DEDENT> elif fieldname in ['RTA_OIF', 'RTA_TABLE', 'RTA_PRIORITY', 'RTA...
turns route rta data into human-readable form
625941e9a8370b7717052d41
def SetDisplayModeOverride(self,mode,rhinoViewportId=None): <NEW_LINE> <INDENT> pass
SetDisplayModeOverride(self: ObjectAttributes,mode: DisplayModeDescription,rhinoViewportId: Guid) -> bool By default,objects are drawn using the display mode of the viewport that the object is being drawn in. Setting a specific display mode,instructs Rhino to always use that display mode,regardless ...
625941e9d10714528d60018c
def destroy(self, supplier_invoice_number): <NEW_LINE> <INDENT> status_code, _, _ = self.http_client.delete("/supplierinvoiceaccruals/{supplier_invoice_number}".format( supplier_invoice_number=supplier_invoice_number)) <NEW_LINE> return status_code == 204
Delete a SupplierInvoiceAccrual Deletes an existing SupplierInvoiceAccrual If the specified SupplierInvoiceAccrual is assigned to any resource, we will remove this SupplierInvoiceAccrual from all such resources If the specified SupplierInvoiceAccrual does not exist, this query will return an error This operation canno...
625941e9fbf16365ca6f6672
def test_0005_create_convert_repository(self): <NEW_LINE> <INDENT> category = self.create_category(name=category_name, description=category_description) <NEW_LINE> self.login(email=common.test_user_1_email, username=common.test_user_1_name) <NEW_LINE> repository = self.get_or_create_repository(name=convert_repository_n...
Create and populate convert_chars_0050.
625941e921a7993f00bc819c
def __iter__(): <NEW_LINE> <INDENT> pass
Return an iterator for the keys in the container.
625941e94a966d76dd5514b7
def at_desc(self, looker=None, preposition=None): <NEW_LINE> <INDENT> pass
This is called whenever someone looks at this object. looker (Object): The object requesting the description.
625941e9ac7a0e7691ed4567
def get_connection(self, request): <NEW_LINE> <INDENT> protocol = request.protocol_override if request.protocol_override else self.protocol <NEW_LINE> target_host = request.host <NEW_LINE> target_port = HTTP_PORT if protocol == 'http' else HTTPS_PORT <NEW_LINE> if not self.use_httplib: <NEW_LINE> <INDENT> im...
Create connection for the request.
625941e9f7d966606f6aa4ad
def test_post_song_embedded_work_subtitle(self): <NEW_LINE> <INDENT> self.work1.subtitle = "returns" <NEW_LINE> self.work1.save() <NEW_LINE> self.authenticate(self.manager) <NEW_LINE> self.assertEqual(Song.objects.count(), 2) <NEW_LINE> self.assertEqual(Artist.objects.count(), 2) <NEW_LINE> self.assertEqual(SongTag.obj...
Test work is created even if similar exists with different subtitle.
625941e930c21e258bdfa946
def _print_document(self): <NEW_LINE> <INDENT> self.ensure_one() <NEW_LINE> action = self.invoice_ids.action_invoice_print() <NEW_LINE> action.update({'close_on_report_download': True}) <NEW_LINE> return action
to override for each type of models that will use this composer.
625941e9462c4b4f79d1db73
def pairwise_distances_argmin_min( X, Y, *, axis=1, metric="euclidean", metric_kwargs=None ): <NEW_LINE> <INDENT> X, Y = check_pairwise_arrays(X, Y) <NEW_LINE> if axis == 0: <NEW_LINE> <INDENT> X, Y = Y, X <NEW_LINE> <DEDENT> if metric_kwargs is None: <NEW_LINE> <INDENT> metric_kwargs = {} <NEW_LINE> <DEDENT> if Pairwi...
Compute minimum distances between one point and a set of points. This function computes for each row in X, the index of the row of Y which is closest (according to the specified distance). The minimal distances are also returned. This is mostly equivalent to calling: (pairwise_distances(X, Y=Y, metric=metric).ar...
625941e97cff6e4e81117e29
def execute(self, rule): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if(rule.type is not CODE_STR or rule.text_type is not CODE_HEXA): <NEW_LINE> <INDENT> if(self.next is not None): <NEW_LINE> <INDENT> return self.next.execute(rule) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return Random_gen.generate_hex_...
This function verify if the rule correspond to the generation of a hex Key Next, it generate and return the corresponding Key if the rule is not the right, the function put to the next cor
625941e97b25080760e398fa
def __init__(self, field_values=None, input_file_bytes=None): <NEW_LINE> <INDENT> self._field_values = None <NEW_LINE> self._input_file_bytes = None <NEW_LINE> self.discriminator = None <NEW_LINE> if field_values is not None: <NEW_LINE> <INDENT> self.field_values = field_values <NEW_LINE> <DEDENT> if input_file_bytes i...
SetPdfFormFieldsRequest - a model defined in Swagger
625941e9d53ae8145f87a70a
def Description(): <NEW_LINE> <INDENT> pass
Return a brief description of the criteria type.
625941e95e10d32532c5f3c9
def maxSubArray1(self, nums): <NEW_LINE> <INDENT> if not nums: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> max_sum = cur_sum = nums[0] <NEW_LINE> for each in nums[1:]: <NEW_LINE> <INDENT> cur_sum = max(each, cur_sum + each) <NEW_LINE> max_sum = max(max_sum, cur_sum) <NEW_LINE> <DEDENT> return max_sum
:type nums: List[int] :rtype: int
625941e9e64d504609d74ce4
def computeFraction(poi_messages, all_messages): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fraction = float(poi_messages / all_messages) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> fraction = 0. <NEW_LINE> <DEDENT> return fraction
given a number message to/from POI (numberator) and number of all messages to/from a person (denominator) return the fraction of messages to/from that person
625941e926238365f5f0f319
def run(self): <NEW_LINE> <INDENT> gui_scripts = self.distribution.entry_points.get('gui_scripts', []) <NEW_LINE> console_scripts = self.distribution.entry_points.get('console_scripts', []) <NEW_LINE> scripts = gui_scripts + console_scripts <NEW_LINE> if len(scripts) == 0: <NEW_LINE> <INDENT> self.warn('No scripts defi...
This method could be simpler by using the subprocess module, but the "correct" way to do things is to use the pkg_resources module to load the main method dynamically using the specification given by the `entry_points`. This means that if the `entry_points` is changed, then this method will still work.
625941e94c3428357757c7c9
def test_mid(self) -> None: <NEW_LINE> <INDENT> value_1 = 'var cadena:String = "abcdefg";\ncadena.mid(5, 2);' <NEW_LINE> self.assertEqual(qs2py(value_1), 'cadena: str = "abcdefg"\ncadena[5 : 5 + 2]\n') <NEW_LINE> value_2 = 'var cadena:String = "abcdefg";\ncadena.mid(5);' <NEW_LINE> self.assertEqual(qs2py(value_2), 'cad...
Test str.mid(5, 2).
625941e921bff66bcd684df2
def SetSortMode ( self, mode, clause='' ): <NEW_LINE> <INDENT> assert ( mode in [SPH_SORT_RELEVANCE, SPH_SORT_ATTR_DESC, SPH_SORT_ATTR_ASC, SPH_SORT_TIME_SEGMENTS, SPH_SORT_EXTENDED, SPH_SORT_EXPR] ) <NEW_LINE> assert ( isinstance ( clause, (str,text_type) ) ) <NEW_LINE> self._sort = mode <NEW_LINE> self._sortby = str_...
Set sorting mode.
625941e982261d6c526ab94a
def get_course_display_name(descriptor): <NEW_LINE> <INDENT> return ' '.join([ descriptor.display_org_with_default, descriptor.display_number_with_default ])
It would return display name from given course descriptor
625941e9293b9510aa2c3735
def remove_db_file(self) -> bool: <NEW_LINE> <INDENT> self._conn.close() <NEW_LINE> import os <NEW_LINE> import random <NEW_LINE> import string <NEW_LINE> tmp_name = ''.join(random.choice(string.ascii_lowercase) for _ in range(16)) <NEW_LINE> tmp_name = os.path.join(os.path.basename(self.db_path), tmp_name) <NEW_LINE> ...
Removes database file.
625941e9187af65679ca55c4
def pkcs7_padding(text, size): <NEW_LINE> <INDENT> pad = text[-1] <NEW_LINE> if any(text[-i] != pad for i in range(1, pad + 1)): <NEW_LINE> <INDENT> raise ValueError('PKCS#7 padding not valid') <NEW_LINE> <DEDENT> return text[:-pad]
:param text: text with padding as bytes :param size: block size :return: text without padding, throws ValueError
625941e963b5f9789fde758a
def __init__(self, iterations, stop_factor, n_scales, patch_size=512, stride=384, max_workers=8, downsampling_factor=1): <NEW_LINE> <INDENT> shearlet_system = psl.SLgetShearletSystem2D(1, int(patch_size/downsampling_factor), int(patch_size/downsampling_factor), n_scales) <NEW_LINE> self.patch_size = patch_size <NEW_LIN...
Constructor :param iterations: number of iterations :type iterations: int :param stop_factor: stop factor for thresholding (0<stop_factor<1) :type stop_factor: float :param n_scales: n_scales for shearlet system, as in shearlab.org :type nscales: int :param patch_size: size of patch must be >= 512 :type patch_size: int...
625941e9004d5f362079a7d4
def process_entries(self): <NEW_LINE> <INDENT> if self.reverse: <NEW_LINE> <INDENT> self.feed.entries.reverse() <NEW_LINE> <DEDENT> for entry in self.feed.entries: <NEW_LINE> <INDENT> self.process_entry(entry)
Start processing all feed entries. This must be called before calling any print_*-methods.
625941e9046cf37aa974d1e7
def addDiscipline(self, disciplineID, name): <NEW_LINE> <INDENT> discipline = Discipline(disciplineID, name) <NEW_LINE> self.__discipline_repository.save(discipline) <NEW_LINE> redo = FunctionCall(self.addDiscipline, disciplineID, name) <NEW_LINE> undo = FunctionCall(self.removeDiscipline, disciplineID) <NEW_LINE> oper...
Add a discipline to the repository :param args: the discipline arguments :return: None.
625941e910dbd63aa1bd3046
def translate_entity_type(old_type): <NEW_LINE> <INDENT> LOC = 'location' <NEW_LINE> ORG = 'organization' <NEW_LINE> EVT = 'event' <NEW_LINE> PER = 'person' <NEW_LINE> MON = 'money' <NEW_LINE> tr = { 'EVENT': EVT, 'FAC': LOC, 'FACILITY': LOC, 'GPE': LOC, 'LOC': LOC, 'LOCATION': LOC, 'MONEY': MON, 'NAT_REL_POL': ORG, 'N...
Translate from Spacy or Polyglot entity types into our types. Here are all the types: - location - organization - event - person - money Returns None if old type is not interesting and entity can be discarded.
625941e915baa723493c441d
def snu(nu, column, kappa, temperature): <NEW_LINE> <INDENT> snu = blackbody.modified_blackbody(nu, temperature, kappanu=kappa, column=column) <NEW_LINE> return snu
Compute the flux density for a given column of gas assuming some opacity kappa
625941e91d351010ab855fbf
def validate_plugin_config(self, path_to_plugin): <NEW_LINE> <INDENT> if path_to_plugin is None: <NEW_LINE> <INDENT> raise PluginValidationError( "Attempted to validate plugin config, " "but the plugin_path is None." ) <NEW_LINE> <DEDENT> path_to_config = join(path_to_plugin, self.CONFIG_NAME) <NEW_LINE> if not isfile(...
Validates that there is a beer.conf file in the path_to_plugin :param path_to_plugin: Path to the plugin :return: True if beer.conf exists :raises: PluginValidationError if beer.conf is not found
625941e956ac1b37e626466a
def queryset(self, request, queryset): <NEW_LINE> <INDENT> if self.value(): <NEW_LINE> <INDENT> return queryset.filter(event__cat=int(self.value()))
Returns the filtered queryset based on the value provided in the query string and retrievable via `self.value()`.
625941e901c39578d7e752e0
def generate_metadata_particle(self, particle_key_table): <NEW_LINE> <INDENT> particle = [] <NEW_LINE> field_index = 0 <NEW_LINE> fields = self.raw_data <NEW_LINE> self.set_internal_timestamp(unix_time=fields[FIELD_METADATA_TIMESTAMP]) <NEW_LINE> for x in range(0, len(particle_key_table)): <NEW_LINE> <INDENT> key = par...
Take something in the data format and turn it into an array of dictionaries defining the data in the particle with the appropriate tag. @throws SampleException If there is a problem with sample creation Parameters: particle_key_table - list of particle keywords to be matched against the raw_data which has t...
625941e96aa9bd52df03724b
def json_to_cli(func, *args, **kwargs): <NEW_LINE> <INDENT> exit_code = 0 <NEW_LINE> simplify_list = kwargs.pop("simplify_list", True) <NEW_LINE> try: <NEW_LINE> <INDENT> json_response = func(*args, **kwargs) <NEW_LINE> <DEDENT> except requests.exceptions.HTTPError as e: <NEW_LINE> <INDENT> json_response = getattr(e, "...
Converts a JSON response to a more appropriate CLI response. If JSON is preferred, the response will be returned as-is. Otherwise: - If the JSON is a list of scalars, the output will be simplified to a string of newline-separated values suitable for the command line (unless simplify_lists is False). - If the JSON is...
625941e91f5feb6acb0c4fee
def test_get_user(client, sample_user): <NEW_LINE> <INDENT> res = client.get(f"/users/{sample_user['data']['id']}") <NEW_LINE> loaded_data = json.loads(res.data) <NEW_LINE> clone = deepcopy(sample_user) <NEW_LINE> del clone['data']['id'] <NEW_LINE> verify_model(loaded_data['data'], clone['data'], 'user') <NEW_LINE> ass...
User sample_user fixture to assert that the results of the get are the same as the user that was posted.
625941e9d7e4931a7ee9e3c3
def strset2tor(strset, in_dim): <NEW_LINE> <INDENT> index_mat = jax2tor(strset.index_mat).T.long() <NEW_LINE> str_lens = jax2tor(strset.str_lens).long() <NEW_LINE> index_tens = torch.zeros(index_mat.shape + (in_dim,)) <NEW_LINE> index_tens = index_tens.scatter(2, index_mat[:, :, None], 1) <NEW_LINE> return index_tens,...
Convert a StrSet object to Pytorch onehot tensor and str_lens vector
625941e991f36d47f21ac99b
def _parse_version_file(version_file): <NEW_LINE> <INDENT> version_file_type = None <NEW_LINE> match = re.compile("^([a-z]+):(.*)$").search(version_file) <NEW_LINE> if match: <NEW_LINE> <INDENT> version_file = match.group(2) <NEW_LINE> version_file_type = match.group(1) <NEW_LINE> aliases = { "js": "javascript" } <NEW_...
Get version info from the given file. It can be any of: Supported version file types (i.e. types of files from which we know how to parse the version string/number -- often by some convention): - json: use the "version" key - javascript: look for a `var VERSION = "1.2.3";` - python: Python script/module with `__versio...
625941e9cc40096d61595df3
def _expand_deps(targets): <NEW_LINE> <INDENT> for target_id in targets.keys(): <NEW_LINE> <INDENT> targets[target_id]['deps'] = _find_all_deps(target_id, targets) <NEW_LINE> if targets[target_id]['options'].get('dynamic_link'): <NEW_LINE> <INDENT> for dep in targets[target_id]['deps']: <NEW_LINE> <INDENT> targets[dep]...
_expand_deps. Find out all the targets that certain target depeneds on them. Fill the related options according to different targets.
625941e9377c676e9127264b
def init_webinterface(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.mod_http = Modules.get_instance().get_module( 'http') <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> self.mod_http = None <NEW_LINE> <DEDENT> if self.mod_http == None: <NEW_LINE> <INDENT> self.logger.error("Plugin '{}': Not initializing the...
" Initialize the web interface for this plugin This method is only needed if the plugin is implementing a web interface
625941e930dc7b7665901e05
@subscriber(EntityPick) <NEW_LINE> def enemy_click(evt): <NEW_LINE> <INDENT> LOG.debug('Event subscriber: {}'.format(evt)) <NEW_LINE> context = evt.context <NEW_LINE> if isinstance(evt.entity, Enemy): <NEW_LINE> <INDENT> msg = Message(MessageType.attack, { MF.id: context.server_id(evt.entity.e_id), }) <NEW_LINE> contex...
Remove an enemy from the game. Gets all the relevant data from the event. :param evt: The event instance :type evt: :class:`game.events.ActorDisappear`
625941e96fece00bbac2dbe9
def quit(self): <NEW_LINE> <INDENT> self.window.destroy()
Destroys this object :return: None
625941e98e71fb1e9831dc4c
def handle_pythonfigure(self, tag: QqTag) -> str: <NEW_LINE> <INDENT> format = tag.get("imgformat", "svg") <NEW_LINE> path = self.make_python_fig(tag.text_content, exts=(format,)) <NEW_LINE> doc, html, text = Doc().tagtext() <NEW_LINE> with html( "img", klass="figure img-responsive", src=self.url_for_figure( path + "/"...
Uses tags: pythonfigure, style, imgformat :param tag: :return:
625941e930dc7b7665901e06
def make_idx_data(revs, word_idx_map, max_l=50): <NEW_LINE> <INDENT> train, dev, test13, test14, test15 = [], [], [], [], [] <NEW_LINE> for rev in revs: <NEW_LINE> <INDENT> sent = get_idx_from_sent(rev["words"], word_idx_map, max_l) <NEW_LINE> sent.append(rev["y"]) <NEW_LINE> if rev["split"]==0: <NEW_LINE> <INDENT> tra...
Transforms sentences into a 2-d matrix.
625941e9dc8b845886cb59db
def tri_from_edge(self, edge): <NEW_LINE> <INDENT> edge = tuple(edge) <NEW_LINE> p1 = self.edges_lookup.get(edge, None) <NEW_LINE> p2 = self.edges_lookup.get(edge[::-1], None) <NEW_LINE> if p1 is None: <NEW_LINE> <INDENT> if p2 is None: <NEW_LINE> <INDENT> raise RuntimeError("No tris connected to edge %r" % (edge,)) <N...
Return the only tri that contains *edge*. If two tris share this edge, raise an exception.
625941e91f037a2d8b9466a1
def remove_empty_categories ( self ): <NEW_LINE> <INDENT> catlist = list ( self._categories.items() ) <NEW_LINE> for cat in catlist: <NEW_LINE> <INDENT> cat[1].remove_empty() <NEW_LINE> if cat[1].empty(): <NEW_LINE> <INDENT> del self._categories [cat[0]] <NEW_LINE> try: <NEW_LINE> <INDENT> os.rmdir ( cat [1].physical_l...
Removes empty categories.
625941e9d6c5a102081444f3
def more_beds(self, numb): <NEW_LINE> <INDENT> for i in self.property_list: <NEW_LINE> <INDENT> if type(i) in [HousePurchase]: <NEW_LINE> <INDENT> if i.bedrooms >= numb: <NEW_LINE> <INDENT> i.display() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> return None
Shows hoses with beds which count is more than we put
625941e9bf627c535bc13674
def register(): <NEW_LINE> <INDENT> return ({"sparc": arch_sparc, "sparc64": arch_sparc64}, ("sparc", "sparc64"))
Inform main catalyst program of the contents of this plugin.
625941e966656f66f7cbc651
def add_field(self, field_name, dic, replace_existing=False): <NEW_LINE> <INDENT> if field_name in self.fields and replace_existing is False: <NEW_LINE> <INDENT> err = 'A field with name: %s already exists' % (field_name) <NEW_LINE> raise ValueError(err) <NEW_LINE> <DEDENT> if 'data' not in dic: <NEW_LINE> <INDENT> rai...
Add a field to the object. Parameters ---------- field_name : str Name of the field to add to the dictionary of fields. dic : dict Dictionary contain field data and metadata. replace_existing : bool True to replace the existing field with key field_name if it exists, loosing any existing data. False w...
625941e923849d37ff7b3530
def deleteUser(request, user_id): <NEW_LINE> <INDENT> if request.method == "POST": <NEW_LINE> <INDENT> user = User.objects.filter(user_id=user_id) <NEW_LINE> user_role = Userrole.objects.filter(user__in=user) <NEW_LINE> if user or user_role: <NEW_LINE> <INDENT> user.delete() <NEW_LINE> user_role.delete() <NEW_LINE> if ...
Method to delete a user :param request: :param user_id: User Id :return: redirects to home page.
625941e98da39b475bd6541e
def write_dooms(self, path): <NEW_LINE> <INDENT> with open(path, 'w') as dooms_file: <NEW_LINE> <INDENT> json.dump(self._dooms_dict, dooms_file, cls=PathJSONEncoder, indent=4)
Write current Dooms to json file :param path: path to file with dooms list :return:
625941e945492302aab5e76d
def read_hdf5(solution,frame,path='./',file_prefix='claw',read_aux=True, options={}): <NEW_LINE> <INDENT> option_defaults = {} <NEW_LINE> for (k,v) in option_defaults.iteritems(): <NEW_LINE> <INDENT> if options.has_key(k): <NEW_LINE> <INDENT> exec("%s = options['%s']" % (k,k)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDE...
Read in a HDF5 file into a Solution :Input: - *solution* - (:class:`~pyclaw.solution.Solution`) Pyclaw object to be output - *frame* - (int) Frame number - *path* - (string) Root path - *file_prefix* - (string) Prefix for the file name. ``default = 'claw'`` - *write_aux* - (bool) Boolean controlling whether ...
625941e9bde94217f3683291
def pos_counts(text, pos_list): <NEW_LINE> <INDENT> temp = [] <NEW_LINE> answer = [] <NEW_LINE> pos = [nltk.word_tokenize(s) for s in nltk.sent_tokenize(text)] <NEW_LINE> tagged = nltk.pos_tag_sents(pos, tagset="universal") <NEW_LINE> for tag in tagged: <NEW_LINE> <INDENT> for word in tag: <NEW_LINE> <INDENT> temp.appe...
Return the sorted list of distinct words with a given part of speech >>> emma = nltk.corpus.gutenberg.raw('austen-emma.txt') >>> pos_counts(emma, ['DET', 'NOUN']) [14352, 32029]
625941e94428ac0f6e5bac9b
def make_builder_instance(instance, class_name, inst_name=None): <NEW_LINE> <INDENT> if inst_name == None: <NEW_LINE> <INDENT> id = ctx.cur_context.make_builder_id(class_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> id = ctx.cur_context.make_builder_id(inst_name) <NEW_LINE> <DEDENT> binst = BuilderInst(id, instan...
Returns a new `BuilderId` referring to `instance` and updates the current context to contain a new `BuilderInstance`. Parmeters --------- inst_name (str): The actual string name of the instance, or `None` if this is an impicit instance instance (Module): The module instance just created class_nam...
625941e9460517430c39461d
def authenticate_user(user, password, password_is_hash=False): <NEW_LINE> <INDENT> if user.id == 1: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if password_is_hash: <NEW_LINE> <INDENT> return password == user.password <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return pun_hash(password) == user.password
Authenticate a user Args: user (FluxBBUser): Users instance of the user to authenticate password (str): Password (or password hash) to verify password_is_hash (bool): (Optional) If true, password is assumed to already be hashed. Defaults to ``False``. Returns: True if the password authenticate...
625941e9bd1bec0571d90ad3