code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def subscriptions_template(self, template_id): <NEW_LINE> <INDENT> return self.db_handler.filter_data({'template_id': template_id})
Return subscriptions with specific template id
625941ddd486a94d0b98e459
def markdown_unescape(string): <NEW_LINE> <INDENT> to_escape = [ "\\", "`", "*", "_", "{", "}", "[", "]", "(", ")", "#", "|", "+", "-", ".", "!" ] <NEW_LINE> for item in to_escape: <NEW_LINE> <INDENT> string = string.replace(f"\\{item}", item) <NEW_LINE> <DEDENT> return string
Un-escape markdown special symbols
625941dd0fa83653e46572cb
def get_notebooks( o, of_signed_user, is_public, offset_n, limit_n): <NEW_LINE> <INDENT> q=db.Query(NoteBook, projection=('user_name', 'user_network', 'access', 'notebook_name', 'version')) <NEW_LINE> if of_signed_user : <NEW_LINE> <INDENT> user_name_network_id = get_user_name_network_id(o) <NEW_LINE> q.filter ( 'user_...
returns list of notebooks, starting with offset_n record, returning max limit_n records :param o: self of caller :param of_signed_user: if True returns notebooks of signed in user :param is_public: if True public notebooks only :param offset_n: offset :param limit_n: number of notebooks to return
625941dd377c676e912724b9
def plot_results(self): <NEW_LINE> <INDENT> sns.set_palette("deep", desat=.6) <NEW_LINE> sns.set_context(rc={"figure.figsize": (8, 4)}) <NEW_LINE> fig = plt.figure() <NEW_LINE> fig.patch.set_facecolor('white') <NEW_LINE> df = self._get_equity_df() <NEW_LINE> print("Plotting equity curve and drawdowns...") <NEW_LINE> ax...
A simple script to plot the balance of the portfolio, or "equity curve", as a function of time.
625941dd91f36d47f21ac807
def mag2flux(ABmag, band): <NEW_LINE> <INDENT> fnu = 10**(-(ABmag + 48.6)/2.5) <NEW_LINE> flambda = fnu_to_flambda(band.effective_wa, fnu) <NEW_LINE> return flambda
Converts given AB magnitude into flux in the given band, in erg/s/cm^2/Angstrom. Returns the flux in the given band.
625941dd377c676e912724ba
def get_slots(self, slot_definitions): <NEW_LINE> <INDENT> return {}
get slots
625941dd5f7d997b87174dad
def missing_video_view(request): <NEW_LINE> <INDENT> glosses = missing_video_list() <NEW_LINE> return render(request, "dictionary/missingvideo.html", {'glosses': glosses})
A view for the above list
625941ddd164cc6175783061
@register.filter(name='is_checkbox') <NEW_LINE> def is_checkbox(field): <NEW_LINE> <INDENT> return field.field.widget.__class__.__name__ == CheckboxInput().__class__.__name__
To check the field is checkbox or not Args: { field - request from the page which should be a field } Returns: Returns response to the html template
625941ddbf627c535bc134e1
def add_rand_horizontal_line_to_image(self, image, line_width=5, line_color="notSet"): <NEW_LINE> <INDENT> x0 = randint(0, int(0.2*image.width)) <NEW_LINE> y0 = randint(0, image.height) <NEW_LINE> x1 = image.width - x0 <NEW_LINE> y1 = randint(y0, image.height) <NEW_LINE> if line_color == "notSet": <NEW_LINE> <INDENT> l...
Draw a random line to a PIL image.
625941dd8da39b475bd65289
def __init__(self, main): <NEW_LINE> <INDENT> self.text = self.textlabel(main, 'By Teerawat And Mongkol') <NEW_LINE> self.text2 = self.textlabel(main, 'CAUTION : Fill "," between data for divide from group of data') <NEW_LINE> self.fill = self.textfill(values.filltext) <NEW_LINE> self.fill.config(width=30, font = ('', ...
part of edit gui
625941dd15baa723493c4289
def test_desc(self): <NEW_LINE> <INDENT> values = [ EnumItem(u'foo', u'Foo', hidden=True), EnumItem(u'bar', u'Bar')] <NEW_LINE> enum = Enum('doc', values) <NEW_LINE> self.assertThat( [e.desc for e in enum], Equals([enum.desc(e.value) for e in enum])) <NEW_LINE> self.assertThat(enum.desc(u'DOES_NOT_EXIST'), Equals(u''))
Getting an enumeration item's description by value returns the description or an empty `unicode` string if no item is represented by the given value.
625941dd07d97122c4178ba4
def __init__(self, block_cache, block_sender, state_view_factory, transaction_executor, chain_head_lock, on_chain_updated, squash_handler, chain_id_manager, identity_signing_key, data_dir, config_dir, permission_verifier, chain_observers, thread_pool=None, metrics_registry=None): <NEW_LINE> <INDENT> self._lock = RLock(...
Initialize the ChainController Args: block_cache: The cache of all recent blocks and the processing state associated with them. block_sender: an interface object used to send blocks to the network. state_view_factory: The factory object to create transaction_executor: The TransactionExec...
625941ddd18da76e235327eb
def select(self, space_name, key, offset=0, limit=0xffffffff, index=0, key_type=None, **kwargs): <NEW_LINE> <INDENT> logger.debug('Select data from space {space} by key {key}'.format( space=space_name, key=key) ) <NEW_LINE> if key_type: <NEW_LINE> <INDENT> key = self._modify_key_type(key=key, key_type=key_type) <NEW_LI...
Select and retrieve data from the database. *Args:* _space_name_: space id to insert a record; _key_: values to search over the index; _offset_: offset in the resulting tuple set; _limit_: limits the total number of returned tuples. Deafult is max of unsigned int32; _index_: specifies which in...
625941dd15baa723493c428a
def p_subject_variable(p): <NEW_LINE> <INDENT> p[0] = Argument(p[1], False)
subject : VARIABLE
625941dd7b25080760e3976a
def test_create_property_single_blob(): <NEW_LINE> <INDENT> init_graph() <NEW_LINE> body = { "name": "blob", "data_type": "BLOB", "cardinality": "SINGLE" } <NEW_LINE> code, res = Schema().create_property(body, auth=auth) <NEW_LINE> print(code, res) <NEW_LINE> assert code == 201 <NEW_LINE> assert res['data_type'] == 'BL...
blob类型的属性创建
625941dd9b70327d1c4e10e8
def __str__(self): <NEW_LINE> <INDENT> return unicode(self.path).encode('utf-8')
Return a string representation of the File Object.
625941dd498bea3a759b9dc1
def model_pipelines(argv): <NEW_LINE> <INDENT> import re <NEW_LINE> import apache_beam as beam <NEW_LINE> from apache_beam.options.pipeline_options import PipelineOptions <NEW_LINE> class MyOptions(PipelineOptions): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def _add_argparse_args(cls, parser): <NEW_LINE> <INDENT> par...
A wordcount snippet as a simple pipeline example.
625941dd99fddb7c1c9de6a2
def get_encoding_dict(): <NEW_LINE> <INDENT> a={chr(65+i):i+1 for i in range(26)} <NEW_LINE> for i in range(26): <NEW_LINE> <INDENT> a[chr(97+i)]=i+1 <NEW_LINE> <DEDENT> return a
returns a dict which maps a -> 1, b -> 2 ... z->26 and A -> 1, B ->2 ... Z->26
625941dd3cc13d1c6d3c768b
def load_data(self, data, size=None): <NEW_LINE> <INDENT> if isinstance(data, str): <NEW_LINE> <INDENT> data = data.split("\n") <NEW_LINE> <DEDENT> if not size: <NEW_LINE> <INDENT> size = V2(len(data[0]), len(data)) <NEW_LINE> <DEDENT> self.width = w = size[0] <NEW_LINE> self.height = h = size[1] <NEW_LINE> if len(data...
Sets internal data from an initial value structure. Args: - data: data structure containing the elements that will be set to inicial pixel values. Can be a single sequence width x height in size containing all elements to be assig...
625941dd097d151d1a22316a
def apply(self, image): <NEW_LINE> <INDENT> layer = np.dstack((self._buffer, self._buffer, self._buffer)) <NEW_LINE> return cv2.addWeighted(image, 1, layer, self.TRANSPARENCY, 0)
Combines layer content with the target image
625941dd925a0f43d254a18c
def InitOutgoingAttributes (self): <NEW_LINE> <INDENT> super(Note, self).InitOutgoingAttributes () <NEW_LINE> self.processingStatus = 'processing'
Init any attributes on ourself that are appropriate for a new outgoing item.
625941dd4428ac0f6e5bab06
def colinear(p, q, r): <NEW_LINE> <INDENT> return signed_area(p, q, r) == 0
True if p,q,r are colinear
625941ddbe7bc26dc91cd90d
def dispatch_realtime_region_watching(self): <NEW_LINE> <INDENT> if self.region_realtime_watching_q: <NEW_LINE> <INDENT> client_ip = '123.133.157.27' <NEW_LINE> ip_lookup_obj = ip_lookup.IPLookup(ip_db_data=self.ip_db_data) <NEW_LINE> lookup_res = ip_lookup_obj.lookpup(client_ip) <NEW_LINE> if lookup_res: <NEW_LINE> <I...
先检测有没有区域开启了实时监测,如果有,就对所有汇报过来的数据进行分析 ,把属于指定区域的数据放到相应的queue :return:
625941dd287bf620b61d3d74
def p_tween(p): <NEW_LINE> <INDENT> commands.append((p[1:],))
command : TWEEN NUMBER NUMBER SYMBOL SYMBOL
625941dd71ff763f4b5499a3
def test_has_page_method_true_index_method(self): <NEW_LINE> <INDENT> class TestPage(object): <NEW_LINE> <INDENT> def index(self): <NEW_LINE> <INDENT> return '' <NEW_LINE> <DEDENT> <DEDENT> self.assertTrue(interfaces.has_page_method(TestPage()))
``has_page_method()`` should return ``True`` if its argument has an ``index()`` bound method.
625941ddbe383301e01b5793
@numba.jit(nopython=True) <NEW_LINE> def to_angular_velocity(w: np.ndarray, q_dot: np.ndarray): <NEW_LINE> <INDENT> return 2 * w @ q_dot
Calculate angular velocity (body or world) from quaternion rate :param w: quaternion rate matrix (body or world) :param q_dot: quaternion rate :return: angular velocity in body or world frame
625941dd9f2886367277ab9e
def GetOutputMaximum(self): <NEW_LINE> <INDENT> return _itkRescaleIntensityImageFilterPython.itkRescaleIntensityImageFilterID2IUL2_GetOutputMaximum(self)
GetOutputMaximum(self) -> unsigned long
625941dd31939e2706e4d178
def traverse(self, node_factory, prefix=_SENTINEL): <NEW_LINE> <INDENT> node, _ = self._get_node(prefix) <NEW_LINE> return node.traverse(node_factory, self._key_from_path, list(self.__path_from_key(prefix)))
Traverses the tree using node_factory object. node_factory is a callable function which accepts (path_conv, path, children, value=...) arguments, where path_conv is a lambda converting path representation to key, path is the path to this node, children is an iterable of children nodes constructed by node_factory, opti...
625941dd4527f215b584c766
def is_mirror(self, other): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self_action_data = operand_data[self.type] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self_action_mirror = None <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self_action_mirror = self_action_data.mirror <NEW_LINE> <DEDENT> if self_ac...
Check if passed action is mirrored version of self. Required arguments: other -- action to check against Return value: True if both actions do the same, with the exception that one of them applies something and another one undoes it, else false
625941dd66673b3332b923a4
def index_queryset(self, using=None): <NEW_LINE> <INDENT> return TriangleArticle.objects.all()
Used when the entire index for model is updated.
625941ddc432627299f04f5b
def get_capture(self): <NEW_LINE> <INDENT> game_image = self._game_image_from_screen('capture') <NEW_LINE> if game_image is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> board = self._board_from_game_image(game_image) <NEW_LINE> if board is None: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> if board.is_empty()...
Return the capture board or None if can't find it.
625941dd76e4537e8c351988
def select(self, nodeset): <NEW_LINE> <INDENT> return ServerGroup((srv for srv in self if srv.hostname in nodeset))
Return a ServerGroup containing only server which hostname are present in provided nodeset.
625941dd442bda511e8be727
def truncatable_prime(n): <NEW_LINE> <INDENT> if n < 10 or not is_prime(n): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> truncate_left_number = n <NEW_LINE> while(len(str(truncate_left_number)) != 1): <NEW_LINE> <INDENT> truncate_left_number = truncate_left(truncate_left_number) <NEW_LINE> if not is_prime(trunc...
returns whether n is a truncatable prime
625941dd4e696a04525c975f
def test_asadpour_tsp(): <NEW_LINE> <INDENT> pytest.importorskip("numpy") <NEW_LINE> pytest.importorskip("scipy") <NEW_LINE> edge_list = [ (0, 1, 100), (0, 2, 100), (0, 5, 1), (1, 2, 100), (1, 4, 1), (2, 3, 1), (3, 4, 100), (3, 5, 100), (4, 5, 100), (1, 0, 100), (2, 0, 100), (5, 0, 1), (2, 1, 100), (4, 1, 1), (3, 2, 1)...
Test the complete asadpour tsp algorithm with the fractional, symmetric Held Karp solution. This test also uses an incomplete graph as input.
625941dd56b00c62f0f1496e
def download(self, url): <NEW_LINE> <INDENT> def cleanup_url(url): <NEW_LINE> <INDENT> tmp = url.rstrip('/') <NEW_LINE> filename = tmp.split('/')[-1] <NEW_LINE> if url.endswith('/'): <NEW_LINE> <INDENT> display_url = tmp + '/' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> display_url = url <NEW_LINE> <DEDENT> return fi...
Downloads the given URL and returns the file name.
625941dde1aae11d1e749fcd
def parameter_grid(parameters): <NEW_LINE> <INDENT> keys, values = list(zip(*parameters.items())) <NEW_LINE> mesh = np.meshgrid(*values) <NEW_LINE> flat_mesh = map(np.ravel, mesh) <NEW_LINE> grid = [] <NEW_LINE> for params in zip(*flat_mesh): <NEW_LINE> <INDENT> d = {key: params[i] for i, key in enumerate(keys)} <NEW_L...
Full parameter space combinations from a dict with iterables. parameters = {'A': [34, 56, 567], 'C': [12, 0], 'G': [1245]} This format is similar to sklearn ParameterGrid
625941dd3cc13d1c6d3c768c
def my_bet_handler(bot, update, chat_data, args): <NEW_LINE> <INDENT> chat_id = update.message.chat.id <NEW_LINE> user = update.message.from_user <NEW_LINE> username = get_username(user) <NEW_LINE> if chat_data.get("current_bet") is None: <NEW_LINE> <INDENT> send_message(bot, chat_id, "No bet currently exists!") <NEW_L...
Input the correlation bet of the user for the current bet. :param bot: The Telegram bot for handling messages. :param update: The update data from the message, including the chat and user that sent it. :param chat_data: The dictionary of data for the chat. :param args: A list containing the R^2 value to bet.
625941dd91af0d3eaac9bd2e
def session_for_reply_channel(reply_channel): <NEW_LINE> <INDENT> reply_name = reply_channel <NEW_LINE> hashed = hashlib.sha1(reply_name.encode("utf8")).hexdigest() <NEW_LINE> session_key = "chn" + hashed[:29] <NEW_LINE> session_engine = import_module(getattr(settings, "CHANNEL_SESSION_ENGINE", settings.SESSION_ENGINE)...
Returns a session object tied to the reply_channel unicode string passed in as an argument.
625941dd6fece00bbac2da54
def describe_secondary_ip( self, req: typing.Optional[dict] = None, **kwargs ) -> dict: <NEW_LINE> <INDENT> d = { "ProjectId": self.config.project_id, "Region": self.config.region, } <NEW_LINE> req and d.update(req) <NEW_LINE> d = apis.DescribeSecondaryIpRequestSchema().dumps(d) <NEW_LINE> resp = self.invoke("DescribeS...
DescribeSecondaryIp - 查询SecondaryIp(uk8s使用) **Request** - **ProjectId** (str) - (Config) 项目ID。不填写为默认项目,子帐号必须填写。 请参考 `GetProjectList接口 <https://docs.ucloud.cn/api/summary/get_project_list.html>`_ - **Region** (str) - (Config) 地域。 参见 `地域和可用区列表 <https://docs.ucloud.cn/api/summary/regionlist.html>`_ - **SubnetId** (str)...
625941dd0383005118ecf8f4
def update_prev_response(r, endpoint): <NEW_LINE> <INDENT> global prev_response <NEW_LINE> prev_response = r.headers <NEW_LINE> prev_response['Status-Code'] = r.status_code <NEW_LINE> prev_response['Endpoint'] = endpoint
Sets the prev_response attribute to contain a dict that includes the response status code and headers of the most recent HTTP request. Arguments: r -- The response object (of the latest HTTP request). endpoint -- The endpoint used (in the latest HTTP request).
625941ddd99f1b3c44c6789d
def _set_token(self): <NEW_LINE> <INDENT> auth_response = requests.post( self._auth_url, data="grant_type=client_credentials", auth=(self._client_id, self._client_secret) ).json() <NEW_LINE> self._token = auth_response['access_token'] <NEW_LINE> self._decoded_token = jwt.decode(self._token, verify=False)
setter method to fetch a new token from AD tenant
625941dd60cbc95b062c6856
@app.route("/api/delete_favorite", methods=['POST']) <NEW_LINE> def delete_stock_json(): <NEW_LINE> <INDENT> if "user" in session: <NEW_LINE> <INDENT> user_id = session['user'] <NEW_LINE> stock_id= request.form.get("stock_id") <NEW_LINE> print(stock_id) <NEW_LINE> crud.delete_stock_user(user_id, stock_id) <NEW_LINE> <D...
Deletes user favorite from db if unfavortied
625941dd796e427e537b08db
def aggregation(train: pd.DataFrame, col_definition: dict): <NEW_LINE> <INDENT> print(train.shape) <NEW_LINE> groupby = GroupbyTransformer(param_dict=col_definition['nunique_dict']) <NEW_LINE> train = groupby.transform(train) <NEW_LINE> print(train.shape) <NEW_LINE> groupby = GroupbyTransformer(param_dict=col_definitio...
col_definition: groupby_dict, nunique_dict
625941dd9b70327d1c4e10e9
def fizzBuzz(self, n): <NEW_LINE> <INDENT> ret_list = [] <NEW_LINE> for i in range(1,n+1): <NEW_LINE> <INDENT> if i%3 == 0 and i %5 == 0: <NEW_LINE> <INDENT> ret_list.append("FizzBuzz") <NEW_LINE> <DEDENT> elif i%3 == 0: <NEW_LINE> <INDENT> ret_list.append("Fizz") <NEW_LINE> <DEDENT> elif i%5 == 0: <NEW_LINE> <INDENT> ...
:type n: int :rtype: List[str]
625941dd71ff763f4b5499a4
def get_content_elem(self, classname): <NEW_LINE> <INDENT> selector = "div.content-active .%s" % classname <NEW_LINE> return self.selenium.find_element_by_css_selector(selector)
Tries to get elements which are within content section
625941dd99fddb7c1c9de6a3
def test_address_space_is_dataclass(self): <NEW_LINE> <INDENT> self.assertTrue( dataclasses.is_dataclass(AddressSpace), "AddressSpace expected to be a dataclass" )
Validate if AddressSpace is a dataclass.
625941ddfff4ab517eb2f751
def func(self, nums, target): <NEW_LINE> <INDENT> from collections import Counter <NEW_LINE> s=[t for t in Counter(s).items()] <NEW_LINE> s.sort(key=lambda t:t[1], reverse=True) <NEW_LINE> res = [k*v for k,v in s] <NEW_LINE> return ''.join(res)
Solution function description
625941dd7b25080760e3976b
def check_array(self, array): <NEW_LINE> <INDENT> if isinstance(array, np.ndarray): <NEW_LINE> <INDENT> return self.shape == array.shape and self.dtype == array.dtype <NEW_LINE> <DEDENT> elif isinstance(array, numbers.Number): <NEW_LINE> <INDENT> return self.shape == tuple() and self.dtype == np.dtype(type(array)) <NEW...
Return whether the given NumPy array conforms to the spec. Args: array: A NumPy array or a scalar. Tuples and lists will not be converted to a NumPy array automatically; they will cause this function to return false, even if a conversion to a conforming array is trivial. Returns: True if the array conforms...
625941ddcc40096d61595c62
def OnOptions(self, event): <NEW_LINE> <INDENT> if len(self._optionsPanels) == 0: <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> optionsDialog = OptionsDialog(wx.GetApp().GetTopWindow(), self._optionsPanels, self._docManager) <NEW_LINE> optionsDialog.CenterOnParent() <NEW_LINE> if optionsDialog.ShowModal() == wx.ID_OK:...
Shows the options dialog, called when the "Options" menu item is selected.
625941dda79ad161976cc458
@profile <NEW_LINE> def plot_spectrum(array_energia,tx,asic): <NEW_LINE> <INDENT> x =np.linspace(0,1000,200) <NEW_LINE> for sel_tx in tx: <NEW_LINE> <INDENT> for sel_ic in asic: <NEW_LINE> <INDENT> for pixel in range(0,T_ASIC_CHANNELS): <NEW_LINE> <INDENT> plt.figure() <NEW_LINE> plt.title('Spettro energetico TX = {}, ...
Function that plots the energy spectrum for every pixel. Parameters ---------- array_energia : numpy.array array with the energy values tx : int tx identification number asic : int asic identification number+ Returns ------- None : None
625941dd004d5f362079a645
def test_learner_post(self): <NEW_LINE> <INDENT> learner = Learner() <NEW_LINE> response = self.client.open( '/v1/learner', method='POST', data=json.dumps(learner), content_type='application/json') <NEW_LINE> self.assert200(response, 'Response body is : ' + response.data.decode('utf-8'))
Test case for learner_post 创建一个Learner
625941ddf9cc0f698b14090c
def representative_elementary_volume(im, npoints=1000): <NEW_LINE> <INDENT> im_temp = np.zeros_like(im) <NEW_LINE> crds = np.array(np.random.rand(npoints, im.ndim) * im.shape, dtype=int) <NEW_LINE> pads = np.array(np.random.rand(npoints) * np.amin(im.shape) / 2 + 10, dtype=int) <NEW_LINE> im_temp[tuple(crds.T)] = True ...
Calculates the porosity of an image as a function subdomain size. This function extracts a specified number of subdomains of random size, then finds their porosity. Parameters ---------- im : ndarray The image of the porous material npoints : int The number of randomly located and sized boxes to sample. The ...
625941dd3617ad0b5ed68209
def _initialize(self): <NEW_LINE> <INDENT> n = 80 <NEW_LINE> s = 1 <NEW_LINE> y = 0 <NEW_LINE> for x in range(-n, n + 1, s): <NEW_LINE> <INDENT> for z in range(-n, n + 1, s): <NEW_LINE> <INDENT> self.add_block((x, y - 3, z), stone, immediate=False) <NEW_LINE> if x in (-n, n) or z in (-n, n): <NEW_LINE> <INDENT> for dy ...
Initialize the world by placing all the blocks.
625941dd67a9b606de4a81ca
def append(self, line): <NEW_LINE> <INDENT> data = line.split('#') <NEW_LINE> if self.front is None: <NEW_LINE> <INDENT> new_node = Node(data[0], None, data[1]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_node = Node(data[0], data[1], data[2]) <NEW_LINE> <DEDENT> if self.front is None: <NEW_LINE> <INDENT> self.fr...
Insert a new Node with value after self.back. :type self: List :type line: str Line of text :rtype: None >>> l = List() >>> l.append("Liam#20") >>> l.append("Emma#Liam#32") >>> l.append("Mason#Emma#14") >>> print(l) Liam: 20, sponsor: None, mentor: None, children: ['Emma'] Emma: 32, sponsor: Liam, mentor: Liam, c...
625941ddfbf16365ca6f64dc
def to_code(self): <NEW_LINE> <INDENT> import converter_helper <NEW_LINE> my_data = dict() <NEW_LINE> my_data['pas_lib_identifier'] = self._name <NEW_LINE> my_data['c_lib_identifier'] = converter_helper.lower_name(self._name) <NEW_LINE> for (name, module) in converter_helper.converters.items(): <NEW_LINE> <INDENT> if s...
Creates a _code entry for each of the converter modules
625941dd2c8b7c6e89b35ad2
def authenticate_credentials(self, userid, password): <NEW_LINE> <INDENT> user = authenticate(username=userid, password=password) <NEW_LINE> if user is None or not user.is_active: <NEW_LINE> <INDENT> raise exceptions.AuthenticationFailed('Invalid username/password') <NEW_LINE> <DEDENT> return (user, None)
Authenticate the userid and password against username and password.
625941dd97e22403b379d2ae
def test_parameterDict_getter_notCached(self): <NEW_LINE> <INDENT> unit = GcodeParser() <NEW_LINE> unit._parameters = "A1 B2" <NEW_LINE> with mock.patch.object(unit, 'parameterItems') as mockParameterItems: <NEW_LINE> <INDENT> mockParameterItems.return_value = [("A", 1), ("B", 2)] <NEW_LINE> result = unit.parameterDict...
Test the parameterDict getter when the result is not cached.
625941dd7c178a314d6ef777
def test_Stack_identify5(): <NEW_LINE> <INDENT> stacks = [con.Stack(Geo).StackTuple for Geo in Geos_symmetric] <NEW_LINE> actual = stacks <NEW_LINE> expected = [({1: ['middle',2000.0]}, 1, '1-ply', 'Monolith'), ({1: ['outer', 600.0], 2: ['middle',800.0, ], 3: ['outer',600.0,]}, 3, '3-ply', 'Trilayer'), ({1: [ 'outer', ...
Check identifying for symmetric geometry.
625941ddb57a9660fec33b9b
def get_open_orders(self): <NEW_LINE> <INDENT> pass
获得当天的所有未完成的订单 参数: 无 返回: 返回一个dict, key是order_id, value是Order对象
625941ddd53ae8145f87a57e
def distanceToPoint(self, point): <NEW_LINE> <INDENT> return np.sum(np.power(point - np.array(list(self.centroid)), 2))
Computes the distance between the point and the eye centroid Args: point (np.array 2): 2d coordinates of the given point Returns: float: Distance to the eye centroid
625941dd627d3e7fe0d69164
def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, GetCharactersCharacterIdWalletTransactions200Ok): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__
Returns true if both objects are equal
625941dd566aa707497f4878
def __init__(self, random_seed): <NEW_LINE> <INDENT> self.random_seed = random_seed
Return a Quirky object
625941dd7047854f462a171a
def addPair(self,x,f): <NEW_LINE> <INDENT> self.X.append(x) <NEW_LINE> self.F.append(f) <NEW_LINE> self.Fmp.append( f - self.prior(x) ) <NEW_LINE> self.matricesReady = False <NEW_LINE> self.limitsReady = False
add a location, its log likelihood and the log-likelihood minus the prior to the lists
625941ddadb09d7d5db6caa1
def _updateResults(self): <NEW_LINE> <INDENT> lastQueryKwargs = self.nodeKwargsFromQuery.copy() <NEW_LINE> queryBody, self.nodeKwargsFromQuery = self.parseQueryString(self.query) <NEW_LINE> if lastQueryKwargs != self.nodeKwargsFromQuery: <NEW_LINE> <INDENT> self._updateCachedNodeList() <NEW_LINE> <DEDENT> if queryBody ...
Perform a simple string-contains search on the cached node list and store as results
625941dda8370b7717052bb1
def get_orders(self, po): <NEW_LINE> <INDENT> script_path = os.path.join(settings.PROJECT_ROOT, 'soapclient.php') <NEW_LINE> arg1 = cjson.encode(po) <NEW_LINE> arg2 = cjson.encode({ 'login': settings.SOAP_LOGIN, 'passwd': settings.SOAP_PASSWORD }) <NEW_LINE> cmd = "php -f %s %s '%s' '%s'" % (script_path, 'getOrderStatu...
Calls remote soap-method "getOrderStatus" from automototrade.com and returns dict with data of order. @po string. ponumber
625941dde8904600ed9f2244
def get_preferred_email_addresses(): <NEW_LINE> <INDENT> pass
Get Preferred Email Addresses DESCRIPTION Get a list of the all the user's preferred email addresses that are visible to the requesting user. ARGUMENTS None. RETURNS A list of strings.
625941dd851cf427c661a820
def get_interpolator(self): <NEW_LINE> <INDENT> from abipy.tools.numtools import BlochRegularGridInterpolator <NEW_LINE> return BlochRegularGridInterpolator(self.structure, self.ur)
Return an interpolator object that interpolates periodic functions in real space.
625941dd507cdc57c6306ff5
def save_results_csv(dest_csv, target_obj_list): <NEW_LINE> <INDENT> with open(dest_csv, "w", newline="") as csvfile: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> writer = csv.writer(csvfile) <NEW_LINE> writer.writerow(["Target", "Type", "Data"]) <NEW_LINE> c.good_news("Writing to CSV") <NEW_LINE> for t in target_obj_l...
Outputs CSV from target object list. Dumps the target.data object variable into CSV file.
625941dd92d797404e30449e
def complete_softwareupdate(self, install_data): <NEW_LINE> <INDENT> success = 'false' <NEW_LINE> error = "Failed to install: " + install_data.name <NEW_LINE> try: <NEW_LINE> <INDENT> app_plist_data = self._get_app_plist_data(install_data) <NEW_LINE> for i in range(1, 3): <NEW_LINE> <INDENT> remove_success = self._remo...
Removes the product key directory if it exists, and lets softwareupdate download and install on its own.
625941ddd7e4931a7ee9e232
def _check(self, string): <NEW_LINE> <INDENT> if isinstance(string, str): <NEW_LINE> <INDENT> return str(string) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return str("")
Check the type of string :param obj string: a string, it should be as UnicodeType or StringType
625941dd01c39578d7e7514f
def test_extended_version(self): <NEW_LINE> <INDENT> v1 = VersionNumber("v1") <NEW_LINE> v2 = VersionNumber("v1-2") <NEW_LINE> self.assertTrue( cmp(v1, v2) < 0 ) <NEW_LINE> self.assertTrue( cmp(v2, v1) > 0 )
Test that a version with a sub-build number is compared later
625941dd4f6381625f114d4f
@raises(ValueError) <NEW_LINE> def test_check_ss2_line_regex_nomatch_0(): <NEW_LINE> <INDENT> line = ' 35SER ( 40A)A 0 ' <NEW_LINE> check_ss2_line_regex(line)
Test proper positioning of ss2 vars.
625941dd29b78933be1e59bb
def prep_obs(self, obs): <NEW_LINE> <INDENT> if not isinstance(obs, list): return obs <NEW_LINE> obs = np.asarray(obs[0]) <NEW_LINE> info = [*obs[1:]] <NEW_LINE> return obs, info
obs: list or ndarray the observation returned by the environment
625941dd8a349b6b435e8487
def channel_addowner(token: str, channel_id: int, u_id: int) -> dict: <NEW_LINE> <INDENT> token_operation = TokenJwt() <NEW_LINE> if check_valid(token) is False: <NEW_LINE> <INDENT> raise AccessError(description='error occurred: token is not valid') <NEW_LINE> <DEDENT> authorised_uid = token_operation.get_uid(token) <N...
Make user with user id u_id an owner of this channel :param token: user's token :param channel_id: channel's id :param u_id: user's id :return: an empty dictionary
625941dd4f88993c3716c378
def setPlayer(self, playerIndex, x0, y0, x, y): <NEW_LINE> <INDENT> if x0<0 and y0<0: <NEW_LINE> <INDENT> for i in range(self.width): <NEW_LINE> <INDENT> for j in range(self.height): <NEW_LINE> <INDENT> if isinstance(self.memory[i][j], PlayerTrace): <NEW_LINE> <INDENT> trace = self.memory[i][j] <NEW_LINE> if trace.inde...
Store the given player and all associated informations. Notice we distinguish between the active player and its trace: Player object is set in the players list, and player trace is dropped on memory
625941dd627d3e7fe0d69165
def test_hash_for(doctest): <NEW_LINE> <INDENT> pass
! (require racket/private/for) > (define ht (make-hash)) > (hash-set! ht 'a 1) > (hash-set! ht 'b 2) > (hash-set! ht 'c 3) > (for/sum ([(k v) (in-hash ht)]) v) 6 > (for/sum ([(k v) ht]) v) 6
625941ddb830903b967e9c1c
def ascii_tree(): <NEW_LINE> <INDENT> global ASCII_TREE <NEW_LINE> if not ASCII_TREE: <NEW_LINE> <INDENT> ASCII_TREE = filter_tree(unicode_tree(), max_codepoint=127) <NEW_LINE> <DEDENT> return ASCII_TREE
Returns tree for ASCII characters.
625941dd63d6d428bbe44803
def Draw(self, dc, rect): <NEW_LINE> <INDENT> right = rect.GetTopRight() <NEW_LINE> points = [wx.Point(right.x-5, right.y), right, wx.Point(right.x, right.y+5)] <NEW_LINE> dc.SetBrush(wx.RED_BRUSH) <NEW_LINE> dc.SetPen(wx.RED_PEN) <NEW_LINE> dc.DrawPolygon(points)
Actually draws a small red triangle in the top-right corder of the cell to indicate that a comment is present. :param `dc`: an instance of :class:`wx.DC`; :param `rect`: an instance of :class:`wx.Rect`, representing the cell rectangle.
625941ddbaa26c4b54cb1430
def join(sep, iterable, preSep='', postSep='', toStr=str): <NEW_LINE> <INDENT> s = sep.join(map(toStr, iterable)) <NEW_LINE> if not s: return '' <NEW_LINE> return f'{preSep}{s}{postSep}'
this function adds features on to sep.join(iterable) if iterable is not empty, preSep is prepended and postSep is appended also, all items of iterable are turned to strings using toStr, which can be customized ex: join(', ', [1,2,3]) => '1, 2, 3' ex: join('.', ['foo', 'bar'], preSep='.') => '.foo.bar'
625941dd956e5f7376d71180
def _changePressure(self, p): <NEW_LINE> <INDENT> now = time.time() <NEW_LINE> duration = abs(self._position - p) / SPEED_PUMP <NEW_LINE> self._time_start = now <NEW_LINE> self._time_goal = now + duration <NEW_LINE> self._goal = p <NEW_LINE> time.sleep(duration) <NEW_LINE> self._position = p <NEW_LINE> self._updatePosi...
Synchronous change of the pressure p (float): target pressure
625941dd090684286d50effc
def step(self, epoch=None): <NEW_LINE> <INDENT> if epoch is None: <NEW_LINE> <INDENT> self.last_epoch += 1 <NEW_LINE> self.last_lr = self.get_lr() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.last_epoch = epoch <NEW_LINE> if hasattr(self, "_get_closed_form_lr"): <NEW_LINE> <INDENT> self.last_lr = self._get_closed...
``step`` should be called after ``optimizer.step`` . It will update the learning rate in optimizer according to current ``epoch`` . The new learning rate will take effect on next ``optimizer.step`` . Args: epoch (int, None): specify current epoch. Default: None. Auto-increment from last_epoch=-1. Returns: Non...
625941dd45492302aab5e5da
def get_ride_details(api_client, ride_id): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ride_details = api_client.get_ride_details(ride_id) <NEW_LINE> <DEDENT> except (ClientError, ServerError) as error: <NEW_LINE> <INDENT> fail_print(error) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> success_print(ride_details.json)
Use an UberRidesClient to get ride details and print the results. Parameters api_client (UberRidesClient) An authorized UberRidesClient with 'request' scope. ride_id (str) Unique ride identifier.
625941dd66673b3332b923a5
def _compute_invoice_saloon_ids(self): <NEW_LINE> <INDENT> for orders in self: <NEW_LINE> <INDENT> orders.count = self.env['account.move']. search_count([('invoice_origin', '=', self.name)])
getting saloon invoice count
625941dd8c3a8732951586d1
def visit_or(self, or_node, env): <NEW_LINE> <INDENT> return Or( or_node.cond1.accept(self, env), or_node.cond2.accept(self, env) ).add_code_reference(or_node.s_expr)
:param or_node: ast.Or :param env: Environment
625941dd3eb6a72ae02ec7f8
def __init__(self, rating_condition=None, actual_rating=None): <NEW_LINE> <INDENT> self._rating_condition = None <NEW_LINE> self._actual_rating = None <NEW_LINE> self.discriminator = None <NEW_LINE> if rating_condition is not None: <NEW_LINE> <INDENT> self.rating_condition = rating_condition <NEW_LINE> <DEDENT> if actu...
RatingComponents - a model defined in Swagger
625941dd1f5feb6acb0c4e5f
def fit(self, X, y=None): <NEW_LINE> <INDENT> n_clusters, labels = gapstat(X, clusterer=self.base_clusterer, max_k=self.max_k, B1=self.B1, B2=self.B2) <NEW_LINE> if ((n_clusters is None) | (labels is None)): <NEW_LINE> <INDENT> msg = "The estimated optimal number of clusters is greater than " ...
Compute the clustering. The gap statistic method is used to estimate the optimal number of clusters. TO DO: allow optional fit parameters to be passed to the base clusterer Parameters ---------- X : array-like, sparse matrix or dataframe,shape=[n_samples,n_features] The observations to cluster. y : Ignored not...
625941dd236d856c2ad44af2
def _load_drivers(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.driver = importutils.import_object( cfg.CONF.LBAAS.driver_fqn, self ) <NEW_LINE> <DEDENT> except ImportError: <NEW_LINE> <INDENT> LOG.exception(_("Error loading LBaaS driver %s"), cfg.CONF.LBAAS.driver_fqn)
Loads plugin-driver from configuration. That method will later leverage service type framework
625941dd4f88993c3716c379
def Uocp_interp(Uocp_neg_interp, Uocp_pos_interp, cse, csmax, utilities): <NEW_LINE> <INDENT> eref_neg = utilities.fenics_interpolate(Uocp_neg_interp) <NEW_LINE> eref_pos = utilities.fenics_interpolate(Uocp_pos_interp) <NEW_LINE> soc = fem.Expression("cse/csmax", cse=cse, csmax=csmax, degree=1) <NEW_LINE> Uocp_neg = ut...
Create an interpolator expression for the open circuit potential.
625941ddd10714528d5ffffa
def get_days_active(success, end=datetime.now()): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> start_date = datetime.strptime(success['start_date'], '%Y-%m-%dT%H:%M:%S.%f') <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> start_date = datetime.strptime(success['start_date'], '%Y-%m-%dT%H:%M:%SZ') <NEW_LINE> <...
Gets the days success has been active. Based on how often it has occurred and the selected end date. Args: success (dict): A single success. end (datetime): Results up to and including this end date. Returns int: Days this success was active.
625941dd32920d7e50b284e6
def _authenticate(self, username, password, force_auth=False): <NEW_LINE> <INDENT> if not force_auth: <NEW_LINE> <INDENT> success = self._authenticate_from_file() <NEW_LINE> if success: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not (username and password): <NEW_LINE> <INDENT> rais...
Tries to authenticate. Raises RuntimeError if it fails.
625941ddd4950a0f3b08c65f
def update_hal_data(in_dict, out_dict=hal_data): <NEW_LINE> <INDENT> for k, v in in_dict.items(): <NEW_LINE> <INDENT> if isinstance(v, dict): <NEW_LINE> <INDENT> update_hal_data(v, out_dict[k]) <NEW_LINE> <DEDENT> elif isinstance(v, list): <NEW_LINE> <INDENT> v_out = out_dict[k] <NEW_LINE> for i, vv in enumerate(v): <N...
Given a dictionary of inputs, update the hal_data
625941dd0fa83653e46572cd
def build_sources(self): <NEW_LINE> <INDENT> self.fetch_books_by_title() <NEW_LINE> self.fetch_books_by_author() <NEW_LINE> self.fetch_bookmarks() <NEW_LINE> if self.opts.generate_descriptions: <NEW_LINE> <INDENT> self.generate_thumbnails() <NEW_LINE> self.generate_html_descriptions() <NEW_LINE> <DEDENT> if self.opts.g...
Generate catalog source files. Assemble OPF, HTML and NCX files reflecting catalog options. Generated source is OEB compliant. Called from gui2.convert.gui_conversion:gui_catalog() Args: Exceptions: AuthorSortMismatchException EmptyCatalogException Results: error: problems reported during build
625941dd462c4b4f79d1d9e4
def setContext(self, Qt_ShortcutContext): <NEW_LINE> <INDENT> pass
QShortcut.setContext(Qt.ShortcutContext)
625941dd5e10d32532c5f23a
def test_can_rate_article_rate_value_less_than_1(self): <NEW_LINE> <INDENT> response = self.client.post( self.SIGN_UP_URL, self.user_cred, format='json') <NEW_LINE> response = self.client.post( reverse('authentication:user_login'), self.user_cred, format='json') <NEW_LINE> token = response.data['token'] <NEW_LINE> arti...
Tests whether a user can delete an article when not author Method registers a user, logs in the user, creates an article, then updates the article
625941dd56ac1b37e62644df
def getDownloadList(self, ep_id: int): <NEW_LINE> <INDENT> data = BiliWebApi.mangaImageIndex(self, ep_id)["data"]["images"] <NEW_LINE> url_list = [x["path"] for x in data] <NEW_LINE> data = BiliWebApi.mangaImageToken(self, url_list)["data"] <NEW_LINE> url_list = [f'{x["url"]}?token={x["token"]}' for x in data] <NEW_LIN...
获取漫画章节下载列表
625941dd91f36d47f21ac809
def missing_time(df): <NEW_LINE> <INDENT> return df.time.isnull().any()
return True if df time column has any null values in it
625941ddd6c5a10208144361
def test_2(self): <NEW_LINE> <INDENT> for suffix in IMP.rmf.suffixes: <NEW_LINE> <INDENT> f = RMF.create_rmf_file( self.get_tmp_file_name("restrnp2" + suffix)) <NEW_LINE> m = IMP.kernel.Model() <NEW_LINE> ps = [IMP.kernel.Particle(m) for i in range(0, 3)] <NEW_LINE> ds = [IMP.core.XYZR.setup_particle(p) for p in ps] <N...
Test that writing restraints doesn't reset model dependencies
625941ddd164cc6175783063
def reduce(self, taxonomies): <NEW_LINE> <INDENT> new = copy.copy(self) <NEW_LINE> new._riskmodels = {} <NEW_LINE> for riskid, rm in self._riskmodels.items(): <NEW_LINE> <INDENT> if riskid in taxonomies: <NEW_LINE> <INDENT> new._riskmodels[riskid] = rm <NEW_LINE> rm.compositemodel = new <NEW_LINE> <DEDENT> <DEDENT> ret...
:param taxonomies: a set of taxonomies :returns: a new CompositeRiskModel reduced to the given taxonomies
625941dd15baa723493c428b
def get_XML(self, xseed_version, *args, **kwargs): <NEW_LINE> <INDENT> if xseed_version == '1.0': <NEW_LINE> <INDENT> msg = 'The xsd-validation file for XML-SEED version 1.0 does ' + 'not support Blockette 60. It will be written but ' + 'please be aware that the file cannot be validate...
Write XML.
625941ddbf627c535bc134e3
def testECS6CookieFFI(self): <NEW_LINE> <INDENT> name = 'cookie-ecs6.ednsoptions.tests.powerdns.com.' <NEW_LINE> eco = cookiesoption.CookiesOption(b'deadbeef', b'deadbeef') <NEW_LINE> ecso = clientsubnetoption.ClientSubnetOption('2001:DB8::1', 128) <NEW_LINE> query = dns.message.make_query(name, 'A', 'IN', use_edns=Tru...
EDNS Options: Cookie + ECS6 (FFI)
625941dd498bea3a759b9dc2