code
stringlengths
4
4.48k
docstring
stringlengths
1
6.45k
_id
stringlengths
24
24
def get_fake_todays(label, past_yrs): <NEW_LINE> <INDENT> fake_todays = calc_fake_today(label, past_yrs) <NEW_LINE> test_today = fake_todays[0] <NEW_LINE> valid_today = fake_todays[1] <NEW_LINE> train_today = fake_todays[2:] <NEW_LINE> return test_today, valid_today, train_today
get the necessary fake todays Input ----- label: str label of time frame to predict a break past_yrs: int number of years you are looking into the past Output ------ (test_today, vaid_today) int years to the test and valid set ls_train_today: ls ls of years to to train
625941c2d53ae8145f87a221
def query_criteria_count(self, pagesize=None, page=None, **criteria): <NEW_LINE> <INDENT> coordinates = criteria.pop('coordinates', None) <NEW_LINE> objectname = criteria.pop('objectname', None) <NEW_LINE> radius = criteria.pop('radius', 0.2*u.deg) <NEW_LINE> obstype = criteria.pop('obstype', 'science') <NEW_LINE> mash...
Given an set of filters, returns the number of MAST observations meeting those criteria. Parameters ---------- pagesize : int, optional Can be used to override the default pagesize. E.g. when using a slow internet connection. page : int, optional Can be used to override the default behavior of all results ...
625941c263f4b57ef00010cc
def embellish(basDir, GSHHS_ROOT, imgStr, ii, dateSnap, timeSnap): <NEW_LINE> <INDENT> import os, sys <NEW_LINE> import aggdraw, PIL <NEW_LINE> from PIL import Image, ImageFont <NEW_LINE> from pydecorate import DecoratorAGG as dag <NEW_LINE> from pycoast import ContourWriter <NEW_LINE> from satpy.resample import get_ar...
What does this definition do? Embellishes the image with custom graphics :param basDir: Base directory path :param GSHHS_ROOT: GSHHS installation folder :param imgStr: Complete path of the output image data as string :param ii: Channel name as string :param dateSnap: Date (YYYYMMDD) name as string :param timeSnap: Tim...
625941c2c4546d3d9de729e0
def install(pkg, refresh=False): <NEW_LINE> <INDENT> if(refresh): <NEW_LINE> <INDENT> refresh_db() <NEW_LINE> <DEDENT> ret_pkgs = {} <NEW_LINE> old_pkgs = list_pkgs() <NEW_LINE> cmd = 'emerge --quiet {0}'.format(pkg) <NEW_LINE> __salt__['cmd.retcode'](cmd) <NEW_LINE> new_pkgs = list_pkgs() <NEW_LINE> for pkg in new_pkg...
Install the passed package Return a dict containing the new package names and versions:: {'<package>': {'old': '<old-version>', 'new': '<new-version>']} CLI Example:: salt '*' pkg.install <package name>
625941c28e71fb1e9831d758
def test_new_date_post_json(self): <NEW_LINE> <INDENT> pastd = self._shift_date(self.data[0][0], delta=-2) <NEW_LINE> d = zip(self.headers, (pastd, self.data[0][1], self.data[0][2])) <NEW_LINE> jd = json.dumps(dict(d)) <NEW_LINE> rv = self.app.post('/historical/', data=jd, content_type='application/json') <NEW_LINE> j ...
Test the usual method of adding a new date: posting a JSON object
625941c2bde94217f3682da1
def find_everywhere_clipboard(): <NEW_LINE> <INDENT> actions.user.find_everywhere(clip.text())
Find clipboard in entire project/all files
625941c27047854f462a13ba
def __init__(self, username, password, file_handle): <NEW_LINE> <INDENT> self.u = username <NEW_LINE> self.p = password <NEW_LINE> self.f = file_handle
Initialising proper variables.
625941c2e5267d203edcdc4d
def OpenDialog(self,wildcard): <NEW_LINE> <INDENT> try: defaultDir=os.path.split(self.filename[self.notebookEditor.GetSelection()])[0] <NEW_LINE> except: defaultDir = os.getcwd() <NEW_LINE> opendlg = wx.FileDialog(self, message=_("Choose a file"), defaultDir=defaultDir, defaultFile="", wildcard=wildcard, style=wx.OPEN ...
Open Dialog and load file in a new editor
625941c2d10714528d5ffc8f
def store_metrics2(c, b, s, co, metd, arr): <NEW_LINE> <INDENT> if arr.ndim == 4: <NEW_LINE> <INDENT> idx = c,b,s,co <NEW_LINE> <DEDENT> elif arr.ndim == 5: <NEW_LINE> <INDENT> idx = c,b,s,co,slice(None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError("only know how to handle 4 or 5-d arrays") <NEW_LINE>...
Store a set of metrics into a structured array c = condition b = block s = subject co = cost? float metd = dict of metrics arr : array?
625941c223e79379d52ee513
def to_string(self): <NEW_LINE> <INDENT> return self.__config_string
Return the content of the CRT, encoded as TLV data in a string
625941c2f9cc0f698b1405ab
def process_message(bot, chains, update): <NEW_LINE> <INDENT> for hook in chains["messages"]: <NEW_LINE> <INDENT> bot.logger.debug("Processing update #%s with the hook %s..." % (update.update_id, hook.name)) <NEW_LINE> result = hook.call(bot, update) <NEW_LINE> if result is True: <NEW_LINE> <INDENT> bot.logger.debug("U...
Process a message sent to the bot
625941c2435de62698dfdbfa
def delete(self, path, version=-1): <NEW_LINE> <INDENT> if type(path) is list: <NEW_LINE> <INDENT> list(map(lambda el: self.delete(el, version), path)) <NEW_LINE> return <NEW_LINE> <DEDENT> url = '%s/znodes/v1%s?%s' % (self._base, path, urllib.parse.urlencode({ 'version':version })) <NEW_LINE> try: <NEW_LINE...
Delete a znode
625941c27b25080760e39408
def __init__(self): <NEW_LINE> <INDENT> self.menuBar.addmenuitem('Plugin', 'command', 'DSSP & Stride', label='DSSP & Stride', command=lambda s=self: DSSPPlugin(s))
DSSP and Stride plugin for PyMol
625941c2ec188e330fd5a751
def doStartPendingFiles(self, *args, **kwargs): <NEW_LINE> <INDENT> for filename, description, result_defer, keep_alive in self.factory.pendingoutboxfiles: <NEW_LINE> <INDENT> self.append_outbox_file(filename, description, result_defer, keep_alive) <NEW_LINE> <DEDENT> self.factory.pendingoutboxfiles = []
Action method.
625941c273bcbd0ca4b2c024
def id_replace(self): <NEW_LINE> <INDENT> aws_lookup = self.lookup() <NEW_LINE> var_lookup_list = pcf_util.find_nested_vars(self.desired_state_definition, var_list=[]) <NEW_LINE> for (nested_key, id_var) in var_lookup_list: <NEW_LINE> <INDENT> if id_var[0] == "lookup": <NEW_LINE> <INDENT> resource = id_var[1] <NEW_LINE...
Looks through the particle definition for $lookup and replaces them with specified resource with given name
625941c2a219f33f3462891a
def components(self): <NEW_LINE> <INDENT> r <NEW_LINE> components = [] <NEW_LINE> for Z in self.reduction_tree().inertial_components(): <NEW_LINE> <INDENT> components += [W.component() for W in Z.upper_components()] <NEW_LINE> <DEDENT> return components
Return the list of all components of the admissible reduction of the curve.
625941c24527f215b584c407
def __invert__(self) -> Predicate: <NEW_LINE> <INDENT> return _Not(self)
Create a new predicate from the logical negation of another. Predicates should be negated by using the ``~`` operator. :return: A new predicate that returns true if and only if the original returns false.
625941c231939e2706e4ce1b
def _json_to_objects(data): <NEW_LINE> <INDENT> if data.get("_sgtk_custom_type") == "sgtk.Template": <NEW_LINE> <INDENT> templates = sgtk.platform.current_engine().sgtk.templates <NEW_LINE> if data["name"] not in templates: <NEW_LINE> <INDENT> raise sgtk.TankError( "Template '{0}' was not found in templates.yml.".forma...
Check if an dictionary is actually representing a Toolkit object and unserializes it. :param dict data: Data to parse. :returns: The original data passed in or the Toolkit object if one was found. :rtype: object
625941c2956e5f7376d70e1c
def valid_palindrome(string): <NEW_LINE> <INDENT> count = {} <NEW_LINE> simplified_string = string.replace(' ', '').lower() <NEW_LINE> for ch in simplified_string: <NEW_LINE> <INDENT> count[ch] = count.get(ch, 0) + 1 <NEW_LINE> <DEDENT> odd_found = False <NEW_LINE> for ch in count.keys(): <NEW_LINE> <INDENT> if count[c...
Returns true/false if the input string can be rearranged into a valid palindrome. >>> valid_palindrome('Tact Coa') True >>> valid_palindrome('abcdef') False >>> valid_palindrome('abcab') True >>> valid_palindrome('aaaaa') True >>> valid_palindrome('') True
625941c24527f215b584c408
def tearDown(self): <NEW_LINE> <INDENT> sys.stdout.close() <NEW_LINE> sys.argv = self.oldSysArgv <NEW_LINE> sys.stdout = self.oldStdout <NEW_LINE> self.oldSysArgv = None <NEW_LINE> self.oldStdout = None
Put the original sys.argv's back.
625941c221a7993f00bc7c9b
def readable_timedelta(days): <NEW_LINE> <INDENT> week = days // 7 <NEW_LINE> day = days % 7 <NEW_LINE> return "{} week(s) and {} day(s).".format(week, day)
Return a string of the number of weeks and days included in days. Parameters: days -- number of days to convert (int) Returns: string of the number of weeks and days included in days
625941c2796e427e537b0572
def get_movie_info(movie_id): <NEW_LINE> <INDENT> movie_url = 'https://api.douban.com/v2/movie/'+movie_id <NEW_LINE> r = requests.get(movie_url) <NEW_LINE> if r.status_code == 200: <NEW_LINE> <INDENT> movie_info = r.json() <NEW_LINE> print(movie_info) <NEW_LINE> return movie_info['summary']
Get summary and rating num of a certain movie
625941c2a934411ee3751641
def __init__(self, misc_settings: dict = None): <NEW_LINE> <INDENT> self.misc_settings = misc_settings <NEW_LINE> self.used_plugins = [] <NEW_LINE> miss_root_plugins = [] <NEW_LINE> is_root = has_root_privileges() <NEW_LINE> for used in self.get_used_plugins(): <NEW_LINE> <INDENT> klass = self.get_class(used) <NEW_LINE...
Creates an instance. Also calls the setup methods on all registered plugins. It calls the setup() method. :param misc_settings: further settings
625941c21f5feb6acb0c4b01
def _get_combination_info( self, combination=False, product_id=False, add_qty=1, pricelist=False, parent_combination=False, only_template=False): <NEW_LINE> <INDENT> combination_info = super()._get_combination_info( combination=combination, product_id=product_id, add_qty=add_qty, pricelist=pricelist, parent_combination...
Update product template prices for products items view in website shop render with cheaper variant prices.
625941c2bd1bec0571d905dd
def encrypt(self, aWords): <NEW_LINE> <INDENT> oCipher = self.getCipher() <NEW_LINE> nWords = self.nBlockSize <NEW_LINE> r = [] <NEW_LINE> for i in xrange(0, len(aWords), nWords): <NEW_LINE> <INDENT> r.extend( oCipher.encipher(aWords, i) ) <NEW_LINE> <DEDENT> return r
@param aWords: @type aWords: @rtype: list
625941c2cdde0d52a9e52fdf
def test_save(self): <NEW_LINE> <INDENT> sender, recipient = self._get_test_users() <NEW_LINE> post = { 'subject': 'test', 'body': 'Test', 'recipient': 'recipient', } <NEW_LINE> form = PrivateMessageCreationForm(post, sender=sender) <NEW_LINE> self.assertTrue(form.is_valid()) <NEW_LINE> obj = form.save() <NEW_LINE> sel...
Test the save method of the form.
625941c2442bda511e8be3c9
def get_mean(lis): <NEW_LINE> <INDENT> return sum(lis)/len(lis)
returns the mean of the items in a list
625941c2d18da76e23532482
@register.filter <NEW_LINE> @stringfilter <NEW_LINE> def access_code_abbreviation(code): <NEW_LINE> <INDENT> if code in rights_access_terms_dict: <NEW_LINE> <INDENT> return rights_access_terms_dict[code].abbreviation
Template filter to display an access status abbreviation from :class:`~keep.common.models.Rights` based on the numeric access status code. Example use:: {{ code|access_code_abbreviation }}
625941c21b99ca400220aa60
def get_chart(self,train_data, feature_list, x_feature, chart_type, width_bar=None): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if x_feature and len(feature_list) > 0: <NEW_LINE> <INDENT> for i in range(len(feature_list)): <NEW_LINE> <INDENT> feature = feature_list[i] <NEW_LINE> x_labels = list(train_data.index) <NEW...
折线图、散点图、条形图绘制: parameters: train_data:DataFrame类型 x_feature:特征,要统计的x轴的数据类别名称 feature_list:特征列表 chart_type: 0:折线图 1:散点图 2:条形图 width_bar:num类型,条形图条的宽度,必须传值,否则多组数据统计时图形会覆盖
625941c207d97122c4178836
def align_reference(self, BAMentry): <NEW_LINE> <INDENT> index = BAMentry.reference_start <NEW_LINE> refAln = '' <NEW_LINE> for cTuple in BAMentry.cigartuples: <NEW_LINE> <INDENT> if cTuple[0] == 0: <NEW_LINE> <INDENT> refAln += self.reference.seq.upper()[index:index+cTuple[1]] <NEW_LINE> index += cTuple[1] <NEW_LINE> ...
given a pysam.AlignmentFile BAM entry, builds the reference alignment string with indels accounted for
625941c2796e427e537b0573
def run(time=None): <NEW_LINE> <INDENT> TOKEN = "insert your token here; get one at {team}.slack.com/apps/manage/custom-integrations" <NEW_LINE> bot = sr.SlackBot(TOKEN) <NEW_LINE> loop = asyncio.get_event_loop() <NEW_LINE> try: <NEW_LINE> <INDENT> loop.run_until_complete(asyncio.wait_for(bot.run(), time)) <NEW_LINE> <...
Runs the bot for time seconds, or forever if None.
625941c2507cdc57c6306c85
def add_dtable(self, default_values, comment=''): <NEW_LINE> <INDENT> dtable = DTABLE(default_values, comment=comment) <NEW_LINE> self._add_dtable_object(dtable) <NEW_LINE> return dtable
Creates a DTABLE card Parameters ---------- default_values : dict key : str the parameter name value : float the value comment : str; default='' a comment for the card
625941c250485f2cf553cd47
def __init__(self, url=None): <NEW_LINE> <INDENT> self._url = None <NEW_LINE> self.discriminator = None <NEW_LINE> if url is not None: <NEW_LINE> <INDENT> self.url = url
ValidateUrlRequestSyntaxOnly - a model defined in Swagger
625941c2d8ef3951e32434eb
def connect_to_url(): <NEW_LINE> <INDENT> return urllib.request.urlopen("http://auto.ria.com")
Read HTML content from http://auto.ria.com
625941c2f7d966606f6a9fb1
def is_multi_spu(self): <NEW_LINE> <INDENT> model = self.current_node.current_controller.get_model() <NEW_LINE> if not model: <NEW_LINE> <INDENT> version_info = self.get_version_info() <NEW_LINE> if "node0" in version_info: <NEW_LINE> <INDENT> model = version_info["node0"]["product_model"] <NEW_LINE> <DEDENT> else: <NE...
Checks the device whether the device running multiple flowd instances (multiple spu) :return: Returns True if the device is multi spu :rtype: bool
625941c23539df3088e2e2fa
def get_default_basename(self, viewset): <NEW_LINE> <INDENT> queryset = getattr(viewset, 'queryset', None) <NEW_LINE> if queryset is None: <NEW_LINE> <INDENT> app_label = viewset.__module__.split('.')[0] <NEW_LINE> object_name = viewset.__name__.lower().replace('viewset', '') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDEN...
Generate defautl 'basename'
625941c2099cdd3c635f0c0a
def picard_rnaMetrics(organism,outdir,annotDir,inpbam,strand,xrRNAcount,prefix,options): <NEW_LINE> <INDENT> if not os.path.exists(os.path.join(outdir,'out_Picard_RnaMetrics')): <NEW_LINE> <INDENT> os.mkdir(os.path.join(outdir,'out_Picard_RnaMetrics')) <NEW_LINE> <DEDENT> if organism == 'hg19' or organism == 'mm10': <N...
generate the RnaSeq metrics
625941c230dc7b7665901917
def recieve_file_name(self,name): <NEW_LINE> <INDENT> self.file_name = name <NEW_LINE> self.m_button15.SetLabel("Load") <NEW_LINE> self.m_staticText10.SetLabel(name)
Recieve a file name, save it as class variable and display in text cntrl
625941c2e1aae11d1e749c64
def ServerReady(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!')
@@ .. cpp:var:: rpc ServerReady(ServerReadyRequest) returns @@ (ServerReadyResponse) @@ @@ Check readiness of the inference server. @@
625941c296565a6dacc8f67a
def f_mu(self, d): <NEW_LINE> <INDENT> if type(d) is Domain: <NEW_LINE> <INDENT> self.d = d <NEW_LINE> self.extend_v = numpy.array([d.extend.x, d.extend.y, d.extend.time], dtype=numpy.float64) <NEW_LINE> self.pos_v = numpy.array([d.position.x, d.position.y, d.position.time], dtype=numpy.float64) <NEW_LINE> lower = [] <...
#vector of domain extend mean function :param d: domain :type d: Domain
625941c2c432627299f04bf3
def test_generate_full_day_calendar_event(): <NEW_LINE> <INDENT> shift = { 'shift_code': 'A1', 'start_datetime': datetime(2018, 1, 1, 9, 0, 0), 'end_datetime': datetime(2018, 1, 1, 17, 0, 0), 'comment': '', } <NEW_LINE> user = { 'full_day': True, 'reminder': None, } <NEW_LINE> dt_stamp = datetime.utcnow().strftime('%Y%...
Tests proper event generation for full day calendar event.
625941c2956e5f7376d70e1d
def _label_clusters(stat_map, threshold, tail, struct, all_adjacent, conn, criteria, cmap, cmap_flat, bin_buff, int_buff, int_buff_flat): <NEW_LINE> <INDENT> if tail >= 0: <NEW_LINE> <INDENT> bin_map_above = np.greater(stat_map, threshold, bin_buff) <NEW_LINE> cids = _label_clusters_binary(bin_map_above, cmap, cmap_fla...
Find clusters on a statistical parameter map Parameters ---------- stat_map : array Statistical parameter map (non-adjacent dimension on the first axis). cmap : array of int Buffer for the cluster id map (will be modified). Returns ------- cluster_ids : np.ndarray of uint32 Identifiers of the clusters...
625941c2e64d504609d747ef
def writeCell(self, cell): <NEW_LINE> <INDENT> if self._state == ConnState.OPEN: <NEW_LINE> <INDENT> self.transport.write(cell.getBytes()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._cell_queue.append(cell)
Write a cell to this connections transport. If this connection is not yet open, append to the cell_queue to be written when the connection opens up. :param cell cell: cell to write
625941c2be383301e01b5438
def lorentz(self, x, t, v): <NEW_LINE> <INDENT> c = 1.0 <NEW_LINE> gamma = 1 / sqrt(1 - (v*v/c/c)) <NEW_LINE> xp = gamma * (x - v*np.asarray(t)) <NEW_LINE> tp = gamma * (t - v*np.asarray(x)/(c*c)) <NEW_LINE> return xp,tp
Lorentz transform
625941c28a43f66fc4b54016
def sample_ruptures(src, num_ses, info): <NEW_LINE> <INDENT> rnd = random.Random(src.seed) <NEW_LINE> col_ids = info.col_ids_by_trt_id[src.trt_model_id] <NEW_LINE> num_occ_by_rup = collections.defaultdict(AccumDict) <NEW_LINE> for rup_no, rup in enumerate(src.iter_ruptures(), 1): <NEW_LINE> <INDENT> rup.rup_no = rup_no...
Sample the ruptures contained in the given source. :param src: a hazardlib source object :param num_ses: the number of Stochastic Event Sets to generate :param info: a :class:`openquake.commonlib.source.CompositionInfo` instance :returns: a dictionary of dictionaries rupture -> {(col_id, ses_id): num_occurre...
625941c21f5feb6acb0c4b02
def root_find(self,p): <NEW_LINE> <INDENT> while self.id[p] != p: <NEW_LINE> <INDENT> p=self.id[p] <NEW_LINE> <DEDENT> return p
Finds and returns the root of element p
625941c26e29344779a625c2
def process_auth(code): <NEW_LINE> <INDENT> credentials=FLOW.step2_exchange(code) <NEW_LINE> storage = Storage(CALENDAR_DATA) <NEW_LINE> storage.put(credentials) <NEW_LINE> return credentials
The second step in the authorization chain. After the first step finished, a code was passed back to the website from google. This function exchanges that code for credentials, including a refresh token that can be used to get credentials without further authorization. It stores the credentials and returns them to the ...
625941c24d74a7450ccd4172
def handle_commands(self, words, vision): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> words[1] <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> command = words[1].lower() <NEW_LINE> if command == "play" and len(words) > 2: <NEW_LINE> <INDENT> self.command_handler.play_spotify(...
Handles which type of commands to use. :param words: The words typed or spoke from listen(). :param vision: The core vision class.
625941c2dd821e528d63b159
def _on_action_expand_all_triggered(self): <NEW_LINE> <INDENT> self.expand_all()
Expands all fold triggers :return:
625941c2236d856c2ad44787
@click.group() <NEW_LINE> def main(): <NEW_LINE> <INDENT> pass
Utility commands for the Protean-Flask package
625941c263d6d428bbe4449e
def people_getPhotos(self, user_id): <NEW_LINE> <INDENT> params = {"user_id": user_id} <NEW_LINE> return self._listing("people.getPhotos", params)
Return photos from the given user's photostream.
625941c226068e7796caec8b
def detrend(data, axis=-1, type='linear', bp=0, overwrite_data=False): <NEW_LINE> <INDENT> if type not in ['linear', 'l', 'constant', 'c']: <NEW_LINE> <INDENT> raise ValueError("Trend type must be 'linear' or 'constant'.") <NEW_LINE> <DEDENT> data = np.asarray(data) <NEW_LINE> dtype = data.dtype.char <NEW_LINE> if dtyp...
Remove linear trend along axis from data. Parameters ---------- data : array_like The input data. axis : int, optional The axis along which to detrend the data. By default this is the last axis (-1). type : {'linear', 'constant'}, optional The type of detrending. If ``type == 'linear'`` (default), ...
625941c2dc8b845886cb54e3
def test20(self): <NEW_LINE> <INDENT> self.verify("$aFunc( $arg = $aMeth( $arg = $aFunc( 1 ) ) )", "1")
deeply nested argstring, no enclosure + with WS
625941c24428ac0f6e5ba7a0
def format_publisher(publisher): <NEW_LINE> <INDENT> publisher = publisher[publisher.find("by") + 3:] <NEW_LINE> publisher = publisher[0:publisher.find("\n")] + " " + publisher[publisher.find("("):publisher.find(")") + 1] <NEW_LINE> return publisher
Cleans and returns the publisher name scrapped from the webpage.
625941c266656f66f7cbc159
def getBlockCoordArrays(xMin, yMax, nCols, nRows, binSize): <NEW_LINE> <INDENT> (rowNdx, colNdx) = numpy.mgrid[0:nRows, 0:nCols] <NEW_LINE> xBlock = (xMin + binSize/2.0 + colNdx * binSize) <NEW_LINE> yBlock = (yMax - binSize/2.0 - rowNdx * binSize) <NEW_LINE> return (xBlock, yBlock)
Return a tuple of the world coordinates for every pixel in the current block. Each array has the same shape as the current block. Return value is a tuple:: (xBlock, yBlock) where the values in xBlock are the X coordinates of the centre of each pixel, and similarly for yBlock. ...
625941c260cbc95b062c64f2
def start_auth_session(self, method, endpoint, **kwargs): <NEW_LINE> <INDENT> req = self._client.request(method, endpoint, **kwargs) <NEW_LINE> self.auth_token = req.json.get("auth_token") <NEW_LINE> self.refresh_token = req.json.get("refresh_token") <NEW_LINE> if self.auth_token: <NEW_LINE> <INDENT> self._client.heade...
Inserts the response token to the header for continue using that instance as authorized user
625941c2b545ff76a8913dc5
def js(self, script): <NEW_LINE> <INDENT> self.driver.execute_script(script)
Execute JavaScript scripts. Usage: driver.js("window.scrollTo(200,1000);")
625941c2287bf620b61d3a14
def __init__(self): <NEW_LINE> <INDENT> gaupol.TopMenuAction.__init__(self, "show_projects_menu") <NEW_LINE> self.props.label = _("_Projects") <NEW_LINE> self.action_group = "main-safe"
Initialize a :class:`ShowProjectsMenuAction` object.
625941c2bf627c535bc1317e
def __init__(self, docker_connect): <NEW_LINE> <INDENT> self.docker_cli = docker.DockerClient(base_url=docker_connect, timeout=1800)
__init__ Create the docker_cli object given an endpoint :param docker_connect str: The endpoint for docker
625941c2b545ff76a8913dc6
def subscribe(self, subscribeReq): <NEW_LINE> <INDENT> pass
订阅行情,自动订阅全部行情,无需实现
625941c263b5f9789fde7094
@pytest.mark.parametrize("cmd", ("python3", "pip3", "virtualenv")) <NEW_LINE> def test_commands(host, cmd): <NEW_LINE> <INDENT> assert host.command(f"{cmd:s} --version").rc == 0 <NEW_LINE> return
Test for installed Python commands.
625941c27b25080760e39409
def channel(self, id, **kwargs): <NEW_LINE> <INDENT> api_params = { 'part': 'id', 'id': id, } <NEW_LINE> api_params.update(kwargs) <NEW_LINE> query = Query(self, 'channels', api_params) <NEW_LINE> return ListResponse(query).first()
Fetch a Channel instance. Additional API parameters should be given as keyword arguments. :param id: youtube channel id e.g. 'UCMDQxm7cUx3yXkfeHa5zJIQ' :return: Channel instance if channel is found, else None
625941c2e5267d203edcdc4e
def t_BOOL_OR(t): <NEW_LINE> <INDENT> return t
\|\|
625941c28da39b475bd64f21
def process(self, **kwargs): <NEW_LINE> <INDENT> parties = Party.objects.values_list('pk', 'name') <NEW_LINE> self.set_push_steps(len(parties) + 1) <NEW_LINE> if kwargs['delete']: <NEW_LINE> <INDENT> PartySimilarityModel.objects.all().delete() <NEW_LINE> <DEDENT> scorer = getattr(fuzzywuzzy.fuzz, kwargs['similarity_typ...
Task process method. :param kwargs: dict, form data
625941c2a17c0f6771cbe001
def __init__(self, artist, title, entry_type, link, popularity, genres): <NEW_LINE> <INDENT> self.artist = artist <NEW_LINE> self.title = title <NEW_LINE> self.type = entry_type <NEW_LINE> self.link = link <NEW_LINE> self.popularity = popularity <NEW_LINE> self.genres = genres <NEW_LINE> self.parent_genre = self.get_p...
Inits Entry with attributes fetched from Spotify
625941c245492302aab5e271
def __getitem__(self, index): <NEW_LINE> <INDENT> if isinstance(index, types.SliceType): <NEW_LINE> <INDENT> return self._main[index].items() <NEW_LINE> <DEDENT> key = self._main._sequence[index] <NEW_LINE> return (key, self._main[key])
Fetch the item at position i.
625941c297e22403b379cf48
def _error(self, message, excerpt_html=None): <NEW_LINE> <INDENT> self._error_on_line(self._line, message, excerpt_html)
Report given error message for the current line read from input stream.
625941c25166f23b2e1a5108
@requires_pandas <NEW_LINE> def test_to_data_frame(): <NEW_LINE> <INDENT> raw, events, picks = _get_data() <NEW_LINE> epochs = Epochs(raw, events, {'a': 1, 'b': 2}, tmin, tmax, picks=picks) <NEW_LINE> assert_raises(ValueError, epochs.to_data_frame, index=['foo', 'bar']) <NEW_LINE> assert_raises(ValueError, epochs.to_da...
Test epochs Pandas exporter
625941c210dbd63aa1bd2b53
def test_public_activity_creator(self): <NEW_LINE> <INDENT> self._add_board(self.user) <NEW_LINE> response = self.client.get(reverse('profile', args=(self.user.id,))) <NEW_LINE> self.assertTemplateUsed(response, 'boards/public_profile.html') <NEW_LINE> self.assertContains(response, "View All", count=1, status_code=200)...
Test public profile of user that has created a board.
625941c2d164cc6175782cfd
def __init__(self, error_reason=None, error_data=None): <NEW_LINE> <INDENT> self.error_reason = error_reason if error_reason is not None else 0 <NEW_LINE> self.error_data = error_data if error_data is not None else b''
Initialize the record with error reason and error data information. None values default to error reason value 0 and empty error data bytes, but note that error reason 0 will raise an exception when encoding.
625941c2cb5e8a47e48b7a5c
def remove_callbacks(self, attr, index=None): <NEW_LINE> <INDENT> if index: <NEW_LINE> <INDENT> self.PV(attr).del_monitor_callback(index=index)
remove a callback function to an attribute PV
625941c238b623060ff0ad9d
def corrupt(x,shape,stddev): <NEW_LINE> <INDENT> return tf.add(x, tf.random_normal(shape=shape, mean=0.0, stddev=stddev, dtype=tf.float32))
Take an input tensor and add uniform masking. Parameters ---------- x : Tensor/Placeholder Input to corrupt. Returns ------- x_corrupted : Tensor 50 pct of values corrupted.
625941c294891a1f4081ba58
@jobs_limit(PARAMS.get("jobs_limit_db", 1), "db") <NEW_LINE> @transform(mergeXYRatio, regex(r"xy_ratio/xy_ratio.tsv"), r"xy_ratio/xy_ratio.load") <NEW_LINE> def loadXYRatio(infile, outfile): <NEW_LINE> <INDENT> P.load(infile, outfile, "--header-names=Track,X,Y,XY_ratio")
load into database
625941c28e05c05ec3eea322
def get_type_info(type_): <NEW_LINE> <INDENT> t_typing, class_ = get_typing(type_) <NEW_LINE> if t_typing is None and class_ is None: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> args = tuple(a for a in _get_args(type_, t_typing=t_typing)) <NEW_LINE> parameters = tuple(p for p in _get_parameters(type_, t_typing=...
Get all the type information for a type. Examples: type_ = get_type_info(Mapping[TKey, int]) type_ == (Mapping, collections.abc.Mapping, (int,), (TKey,)) type_.typing == Mapping type_.class_ == collections.abc.Mapping type_.args == (int,) type_.parameters == (TKey,)
625941c2925a0f43d2549e25
def next(self): <NEW_LINE> <INDENT> self.index += 1 <NEW_LINE> if self.index >= len(self): <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> model = self.json.keys()[self.index] <NEW_LINE> return ApiEndpoint(model, self.json[model])
Return the next item from the :class:`ApiEndpoints` set. If there are no further items, raise the StopIteration exception.
625941c23cc13d1c6d3c732a
def search(self, query: str) -> typing.List[Station]: <NEW_LINE> <INDENT> logging.debug("Query: %s", query) <NEW_LINE> return [ self.code_station[code] for code in collections.OrderedDict.fromkeys( self.name_station[name].code for name in difflib.get_close_matches(query.lower(), self.names) ) ]
Searches for unique stations that match the query.
625941c2d58c6744b4257c10
def test_default_lang(en_us_dict): <NEW_LINE> <INDENT> def_lang = get_default_language() <NEW_LINE> if def_lang is None: <NEW_LINE> <INDENT> with pytest.raises(Error): <NEW_LINE> <INDENT> Dict() <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> d = Dict() <NEW_LINE> assert d.tag == def_lan...
Test behaviour of default language selection.
625941c2d7e4931a7ee9decc
def dbdict_factory(cursor, row): <NEW_LINE> <INDENT> colnames = [d[0] for d in cursor.description] <NEW_LINE> return dbdict(dict(zip(colnames, row)))
Convert a row returned from a query into ``dbdict`` objects :param cursor: cursor object :param row: row tuple :returns: row as ``dbdict`` object
625941c297e22403b379cf49
def __evaluate_wave_speeds(self, left, right, p_estimate): <NEW_LINE> <INDENT> gamma_coeff = (self.gamma + 1) / (2 * self.gamma) <NEW_LINE> q_L = 1 if p_estimate <= left.p else (1 + gamma_coeff * (p_estimate / left.p - 1)) ** 0.5 <NEW_LINE> q_R = 1 if p_estimate <= right.p else (1 + gamma_coeff * (p_estimate / right.p ...
Evaluate wave speeds based on pressure estimate
625941c263f4b57ef00010cd
def _fetchFirstMutation(self, muts): <NEW_LINE> <INDENT> mut = None <NEW_LINE> for mutation in muts: <NEW_LINE> <INDENT> mut = copy.deepcopy(mutation) <NEW_LINE> lst = [muts, (mut for mut in [mut])] <NEW_LINE> muts = itertools.chain(*lst) <NEW_LINE> break <NEW_LINE> <DEDENT> return mut, muts
Get the first mutation from the generator of mutations. :param muts: generator of mutations :return: first mutation
625941c210dbd63aa1bd2b54
def test_delete_timelog_negative(self): <NEW_LINE> <INDENT> c = Client() <NEW_LINE> c.login(username="ddlsb", password="123456") <NEW_LINE> response = c.get("/timeLog/delete/{0}/".format(TimeLog.objects.filter(employee_id__user__username="ddlsb", registryDate__lt=timezone.make_aware(datetime.today()-timedelta(days=1), ...
try deleting a timelog whose date has passed
625941c2377c676e91272159
def mul_vector(self, vector): <NEW_LINE> <INDENT> outputVector = JonesVector(Ex=vector.E1, Ey=vector.E2, k=vector.k, z=vector.z) <NEW_LINE> for m in self.matrices: <NEW_LINE> <INDENT> outputVector.transformBy(m) <NEW_LINE> <DEDENT> return outputVector
At this point, we are multiplying the MatrixProduct by a JonesVector, therefore we *know* the wavevector k for the multiplication. By managing the product ourselves, we start the multiplication "from the right" and multiply the rightmost matrix by the JonesVector , and if that matrix requires the vector k, it will req...
625941c27c178a314d6ef40c
@pytest.mark.django_db <NEW_LINE> def test_backend_for_failed_auth(monkeypatch, django_user_model): <NEW_LINE> <INDENT> factory = RequestFactory() <NEW_LINE> request = factory.get('/login/') <NEW_LINE> request.session = {} <NEW_LINE> def mock_verify(ticket, service): <NEW_LINE> <INDENT> return None, {} <NEW_LINE> <DEDE...
Test CAS authentication failure.
625941c25f7d997b87174a45
def find_longest_substring(query): <NEW_LINE> <INDENT> current = "" <NEW_LINE> longest = 0 <NEW_LINE> for i, v in enumerate(query): <NEW_LINE> <INDENT> if i == 0: <NEW_LINE> <INDENT> longest = len(current) <NEW_LINE> current += v <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if v in current and len(current) > longest: ...
find length of longest substring w/out repeating char further cases ⬇️ assert scaffold('a') == 1 assert scaffold('abcdbefghi') == ?
625941c299fddb7c1c9de341
def __init__(self, sock, address, server_queue, log_file, debug=True): <NEW_LINE> <INDENT> if not isinstance(sock, socket.socket): <NEW_LINE> <INDENT> raise ValueError("sock argument is not a socket.socket") <NEW_LINE> <DEDENT> if not isinstance(address, tuple) or not len(address) == 2 or not isinstance(address[0], str...
:param sock: socket.socket object :param address: (ip, id) tuple :param server_queue: Queue
625941c2ac7a0e7691ed4080
def get_tool_config(self, request): <NEW_LINE> <INDENT> launch_url = self.get_launch_url(request) <NEW_LINE> return ToolConfig( title=self.TOOL_TITLE, launch_url=launch_url, secure_launch_url=launch_url, )
Returns an instance of ToolConfig().
625941c2adb09d7d5db6c740
def geosgeometry_str_to_struct(value): <NEW_LINE> <INDENT> result = geos_ptrn.match(value) <NEW_LINE> if not result: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> return { 'srid': result.group(1), 'x': result.group(2), 'y': result.group(3), }
Parses a geosgeometry string into struct. Example: SRID=5432;POINT(12.0 13.0) Returns: >> [5432, 12.0, 13.0]
625941c2b7558d58953c4ec7
def wiki_to_md(text): <NEW_LINE> <INDENT> fn = [] <NEW_LINE> new_text = [] <NEW_LINE> fn_n = 1 <NEW_LINE> for line in text.split('\n'): <NEW_LINE> <INDENT> match = re.match("^([#\*]+)(.*)", line) <NEW_LINE> if match: <NEW_LINE> <INDENT> list, text = match.groups() <NEW_LINE> num_of_spaces = 4 * (len(list) - 1) <NEW_LIN...
Convert wiki formatting to markdown formatting. :param text: string of text to process :return: processed string
625941c22c8b7c6e89b35772
def testOpenCloseLocation(self): <NEW_LINE> <INDENT> path_spec = path_spec_factory.Factory.NewPathSpec( definitions.TYPE_INDICATOR_TSK, location='/passwords.txt', parent=self._os_path_spec) <NEW_LINE> file_object = tsk_file_io.TSKFile(self._resolver_context, path_spec) <NEW_LINE> self._TestOpenCloseLocation(file_object...
Test the open and close functionality using a location.
625941c25fc7496912cc392e
def setLevelsPre(self, levels): <NEW_LINE> <INDENT> self.currentCalib['levelsPre'] = levels
Sets the last set of luminance values measured during calibration
625941c221bff66bcd684904
def set_field(self, name, value): <NEW_LINE> <INDENT> name = name.lower() <NEW_LINE> if hasattr(self,name): <NEW_LINE> <INDENT> if isinstance(value,str): <NEW_LINE> <INDENT> setattr(self,name,value.strip('"')) <NEW_LINE> <DEDENT> elif isinstance(value,bool): <NEW_LINE> <INDENT> setattr(self,name,value) <NEW_LINE> <DEDE...
Set a track field value as a class attributes. This method provides additional formating to any data fields. For example, removing quoting and checking the field name. :param name: Field name to set :type name: str :param value: Value of field :type value: str :return: :data:`True` if field is written to the clas...
625941c23d592f4c4ed1d022
def get(self, id): <NEW_LINE> <INDENT> with self._lock: <NEW_LINE> <INDENT> self._socket.send_json({ 'action': 'get', 'id': id}) <NEW_LINE> result = self._socket.recv_json() <NEW_LINE> <DEDENT> if result.get('status') == 'OK': <NEW_LINE> <INDENT> return result.get('data') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s...
Get the data from the state. Args id - string. Returns the data for the id.
625941c24428ac0f6e5ba7a1
def test_arm_away_publishes_mqtt(self): <NEW_LINE> <INDENT> self.hass.config.components = set(['mqtt']) <NEW_LINE> assert setup_component(self.hass, alarm_control_panel.DOMAIN, { alarm_control_panel.DOMAIN: { 'platform': 'mqtt', 'name': 'test', 'state_topic': 'alarm/state', 'command_topic': 'alarm/command', } }) <NEW_L...
Test publishing of MQTT messages while armed.
625941c291af0d3eaac9b9c7
def set_matrix_data(linC, linPy) -> None: <NEW_LINE> <INDENT> if get_type(linPy) == cvxcore.SPARSE_CONST: <NEW_LINE> <INDENT> coo = format_matrix(linPy.data, format='sparse') <NEW_LINE> linC.set_sparse_data(coo.data, coo.row.astype(float), coo.col.astype(float), coo.shape[0], coo.shape[1]) <NEW_LINE> <DEDENT> else: <NE...
Calls the appropriate cvxcore function to set the matrix data field of our C++ linOp.
625941c276d4e153a657eae0
def edge_ids_one(self, etype, u, v): <NEW_LINE> <INDENT> eid = F.from_dgl_nd(_CAPI_DGLHeteroEdgeIdsOne( self, int(etype), F.to_dgl_nd(u), F.to_dgl_nd(v))) <NEW_LINE> return eid
Return an arrays of edge IDs. Parameters ---------- etype : int Edge type u : Tensor The src nodes. v : Tensor The dst nodes. Returns ------- Tensor The edge ids.
625941c2cc40096d61595901
def plot_path(qpath,shadow=0): <NEW_LINE> <INDENT> nlines=4 <NEW_LINE> N=qpath.shape[2] <NEW_LINE> no_steps=qpath.shape[0] <NEW_LINE> step=no_steps//nlines <NEW_LINE> for i in range(step,no_steps-step,step): <NEW_LINE> <INDENT> plt.plot(smooth(qpath[i,0,:]),smooth(qpath[i,1,:]), '-',color='0.75',linewidth=0.5) <NEW_LIN...
qpath[i,j,k] i=spatial dim; j= particle dim; k=time step
625941c291f36d47f21ac4a0
def test_example(self, gtf_path): <NEW_LINE> <INDENT> gtf = tabix.read_gtf_frame(gtf_path) <NEW_LINE> assert gtf.shape == (76, 9) <NEW_LINE> assert list(gtf.columns) == tabix.GTF_COLUMNS <NEW_LINE> assert gtf.iloc[0]['start'] == 100124851
Test example gtf containing Smn1.
625941c2dc8b845886cb54e4
def __init__(self, init_stamp_token, epsilon, num_quantiles, max_elements=None, name=None, container=None, generate_quantiles=False): <NEW_LINE> <INDENT> self._epsilon = epsilon <NEW_LINE> self._generate_quantiles = generate_quantiles <NEW_LINE> name = _PATTERN.sub("", name) <NEW_LINE> with ops.name_scope(name, "Quanti...
Creates a QuantileAccumulator object. Args: init_stamp_token: The initial value for the stamp token. epsilon: Error bound on the quantile computation. num_quantiles: Number of quantiles to produce from the final summary. max_elements: Maximum number of elements added to the accumulator. name: the name to sav...
625941c23346ee7daa2b2d1b
def lrange(self, name, start=None, end=None): <NEW_LINE> <INDENT> return self.db[name][start:end]
Return range of values in a list
625941c24e696a04525c93fc
def extractSentimentFromText(self,txt): <NEW_LINE> <INDENT> alchemyapi = AlchemyAPI() <NEW_LINE> response = alchemyapi.sentiment('text', txt) <NEW_LINE> if response['status'] == 'OK': <NEW_LINE> <INDENT> sentimentType = response['docSentiment']['type'] <NEW_LINE> if sentimentType == "neutral": <NEW_LINE> <INDENT> senti...
method for extracting the sentiment associated with the text of a document
625941c24f88993c3716c019