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> mashupFilters = self._build_filter_set(**criteria) <NEW_LINE> position = None <NEW_LINE> if objectname and coordinates: <NEW_LINE> <INDENT> raise InvalidQueryError("Only one of objectname and coordinates may be specified.") <NEW_LINE> <DEDENT> if objectname: <NEW_LINE> <INDENT> coordinates = self._resolve_object(objectname) <NEW_LINE> <DEDENT> if coordinates: <NEW_LINE> <INDENT> coordinates = commons.parse_coordinates(coordinates) <NEW_LINE> if isinstance(radius, (int, float)): <NEW_LINE> <INDENT> radius = radius * u.deg <NEW_LINE> <DEDENT> radius = coord.Angle(radius) <NEW_LINE> position = ', '.join([str(x) for x in (coordinates.ra.deg, coordinates.dec.deg, radius.deg)]) <NEW_LINE> <DEDENT> if position: <NEW_LINE> <INDENT> service = "Mast.Caom.Filtered.Position" <NEW_LINE> params = {"columns": "COUNT_BIG(*)", "filters": mashupFilters, "obstype": obstype, "position": position} <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> service = "Mast.Caom.Filtered" <NEW_LINE> params = {"columns": "COUNT_BIG(*)", "filters": mashupFilters, "obstype": obstype} <NEW_LINE> <DEDENT> return self.service_request(service, params)[0][0].astype(int) | 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 being returned to obtain
one sepcific page of results.
**criteria
Criteria to apply. At least one non-positional criterion must be supplied.
Valid criteria are coordinates, objectname, radius (as in `query_region` and `query_object`),
and all observation fields listed `here <https://mast.stsci.edu/api/v0/_c_a_o_mfields.html>`__.
The Column Name is the keyword, with the argument being one or more acceptable values for that parameter,
except for fields with a float datatype where the argument should be in the form [minVal, maxVal].
For non-float type criteria wildcards maybe used (both * and % are considered wildcards), however
only one wildcarded value can be processed per criterion.
RA and Dec must be given in decimal degrees, and datetimes in MJD.
For example: filters=["FUV","NUV"],proposal_pi="Ost*",t_max=[52264.4586,54452.8914]
Returns
-------
response : int | 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_area_def <NEW_LINE> img = Image.open(imgStr, mode = "r") <NEW_LINE> if ("L" or "A" in img.getbands()): <NEW_LINE> <INDENT> rgbimg = Image.new("RGBA", img.size) <NEW_LINE> rgbimg.paste(img) <NEW_LINE> img = rgbimg <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("\n It was already an RGB image, so no need to convert!") <NEW_LINE> <DEDENT> dc = dag(img) <NEW_LINE> dc.add_logo(basDir + 'logo/NCMRWF.png', height = 75.0, bg='yellow') <NEW_LINE> capStr = ii <NEW_LINE> textStr = "MSG-1: SEVIRI [" + capStr + "]\n" + dateSnap + '\n' + timeSnap + ' UTC' <NEW_LINE> fontClr = aggdraw.Font('black', "/usr/share/fonts/truetype/DejaVuSerif.ttf", size = 18) <NEW_LINE> dc.add_text(textStr, font = fontClr) <NEW_LINE> dc.align_right() <NEW_LINE> dc.add_logo(basDir + 'logo/imdlogo.jpg', height=75.0) <NEW_LINE> dc.align_left() <NEW_LINE> dc.align_bottom() <NEW_LINE> dc.add_logo(basDir + 'logo/eumetsatLogo.jpg', height=50.0) <NEW_LINE> dc.align_right() <NEW_LINE> dc.add_logo(basDir + 'logo/pytroll-logo.png', height = 50.0) <NEW_LINE> proj4_str = '+proj=merc +lon_0=75.0 + lat_0=17.5 + lat_ts=17.5 +ellps=WGS84' <NEW_LINE> area_extent = (-3339584.72, -1111475.10, 3339584.72, 5591295.92) <NEW_LINE> area_def = (proj4_str, area_extent) <NEW_LINE> cw = ContourWriter(GSHHS_ROOT) <NEW_LINE> cw.add_coastlines(img, area_def, resolution = 'h', level = 1) <NEW_LINE> cw.add_shapefile_shapes(img, area_def, GSHHS_ROOT + 'India/Admin2.shp', outline = 'white') <NEW_LINE> fontClr2 = ImageFont.truetype("/usr/share/fonts/truetype/DejaVuSerif.ttf", 14) <NEW_LINE> cw.add_grid(img, area_def, (10.0, 10.0), (2.0, 2.0), fontClr2, fill = "white", outline = 'lightblue', minor_outline = 'lightblue') <NEW_LINE> img.save(imgStr) <NEW_LINE> return img | 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: Time (HHMM) name as string
:return: Image with all the decorations..
References:
[1]. https://stackoverflow.com/questions/18522295/python-pil-change-greyscale-tif-to-rgb | 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_pkgs: <NEW_LINE> <INDENT> if pkg in old_pkgs: <NEW_LINE> <INDENT> if old_pkgs[pkg] == new_pkgs[pkg]: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> ret_pkgs[pkg] = {'old': old_pkgs[pkg], 'new': new_pkgs[pkg]} <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> ret_pkgs[pkg] = {'old': '', 'new': new_pkgs[pkg]} <NEW_LINE> <DEDENT> <DEDENT> return ret_pkgs | 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 = json.loads(rv.data) <NEW_LINE> self.assertEqual(rv.status_code, 201, "invalid status code (%i) posting new date '%s'" % (rv.status_code, pastd)) <NEW_LINE> self.assertEqual(j['DATE'], pastd, "unexpected response posting new date '%s'" % pastd) | 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 | wx.CHANGE_DIR) <NEW_LINE> if opendlg.ShowModal() == wx.ID_OK: <NEW_LINE> <INDENT> paths = opendlg.GetPaths() <NEW_LINE> for path in paths: <NEW_LINE> <INDENT> self.Open(path) | 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> <DEDENT> for met_name, met_val in metd.items(): <NEW_LINE> <INDENT> arr[idx][met_name] = met_val | 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("Update #%s was just processed by the %s hook." % (update.update_id, hook.name)) <NEW_LINE> return <NEW_LINE> <DEDENT> <DEDENT> bot.logger.debug("No hook actually processed the #%s update." % update.update_id) | 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> <INDENT> return self._do_delete(url) <NEW_LINE> <DEDENT> except urllib.error.HTTPError as e: <NEW_LINE> <INDENT> if e.code == 412: <NEW_LINE> <INDENT> raise ZooKeeper.WrongVersion(path) <NEW_LINE> <DEDENT> elif e.code == 404: <NEW_LINE> <INDENT> raise ZooKeeper.NotFound(path) <NEW_LINE> <DEDENT> raise | 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> names = id_var[2].split(':') <NEW_LINE> var = aws_lookup.get_id(resource, names) <NEW_LINE> pcf_util.replace_value_nested_dict(curr_dict=self.desired_state_definition, list_nested_keys=nested_key.split('.'), new_value=var) | 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.".format(data["name"]) ) <NEW_LINE> <DEDENT> return templates[data["name"]] <NEW_LINE> <DEDENT> return data | 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[ch] % 2 != 0: <NEW_LINE> <INDENT> if odd_found: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> odd_found = True <NEW_LINE> <DEDENT> <DEDENT> return True | 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> if klass.needs_root_privileges and not is_root: <NEW_LINE> <INDENT> miss_root_plugins.append(used) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.used_plugins.append(self.get_for_name(used)) <NEW_LINE> <DEDENT> <DEDENT> if miss_root_plugins: <NEW_LINE> <INDENT> logging.warning("The following plugins are disabled because they need root privileges " "(consider using `--sudo`): %s", join_strs(miss_root_plugins)) <NEW_LINE> <DEDENT> self.setup() | 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=parent_combination, only_template=only_template) <NEW_LINE> if (only_template and self.env.context.get('website_id') and self.product_variant_count > 1): <NEW_LINE> <INDENT> cheaper_variant = self.product_variant_ids.sorted( key=lambda p: p.website_price)[:1] <NEW_LINE> res = cheaper_variant._get_combination_info_variant() <NEW_LINE> combination_info.update({ 'price': res.get('price'), 'list_price': res.get('list_price'), 'has_discounted_price': res.get('has_discounted_price'), }) <NEW_LINE> <DEDENT> return combination_info | 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> self.assertEqual(list(PrivateMessage.objects.all()), [obj]) | 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_LINE> x = range(len(x_labels)) <NEW_LINE> plt.xticks(x, x_labels) <NEW_LINE> y = train_data[feature] <NEW_LINE> if chart_type == 0: <NEW_LINE> <INDENT> y = train_data[feature] <NEW_LINE> plt.plot(x, y, label=x_feature) <NEW_LINE> <DEDENT> elif chart_type == 1: <NEW_LINE> <INDENT> y = train_data[feature] <NEW_LINE> plt.scatter(x, y, label=x_feature) <NEW_LINE> <DEDENT> elif chart_type == 2: <NEW_LINE> <INDENT> x = [j + width_bar * i for j in x] <NEW_LINE> plt.bar(x, y, width=width_bar, label=x_feature) <NEW_LINE> <DEDENT> <DEDENT> plt.legend() <NEW_LINE> plt.show() <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print(e) | 折线图、散点图、条形图绘制:
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> <DEDENT> elif cTuple[0] == 1: <NEW_LINE> <INDENT> refAln += '-'*cTuple[1] <NEW_LINE> <DEDENT> elif cTuple[0] == 2: <NEW_LINE> <INDENT> index += cTuple[1] <NEW_LINE> <DEDENT> <DEDENT> return refAln | 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> <DEDENT> except asyncio.TimeoutError: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> loop.close() | 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: <NEW_LINE> <INDENT> model = version_info["product_model"] <NEW_LINE> <DEDENT> <DEDENT> if re.match(r"(srx5400|srx5600|srx5800)", model, re.IGNORECASE): <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False | 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> <INDENT> object_name = queryset.model._meta.object_name.lower() <NEW_LINE> app_label = queryset.model._meta.app_label.lower() <NEW_LINE> <DEDENT> return f"api-{app_label}-{object_name}" | 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': <NEW_LINE> <INDENT> system_call = 'docker run --rm -v %s:%s:ro -v %s:%s:ro -v %s:%s -v %s:%s:ro genomicsdocker/picard:2.5.0 picard_CollectRnaSeqMetrics.py --inpbam %s --refFlat %s --rRNA_interval %s --output %s --strand %s' %( '/etc/localtime','/etc/localtime', outdir,'/workdir', os.path.join(outdir,'out_Picard_RnaMetrics'),'/PicardDir', annotDir,'/annotDir', os.path.join('/workdir/',os.path.basename(inpbam)), os.path.join('/annotDir','refFlat'), os.path.join('/annotDir','rRNA.interval'), os.path.join('/PicardDir',prefix+'_RnaSeqMetrics.txt'), strand) <NEW_LINE> run_command_line(system_call) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> system_call = 'docker run --rm -v %s:%s:ro -v %s:%s:ro -v %s:%s -v %s:%s:ro -v %s:%s:ro genomicsdocker/picard:2.5.0 picard_CollectRnaSeqMetrics.py --inpbam %s --refFlat %s --rRNA_interval %s --output %s --strand %s' %( '/etc/localtime','/etc/localtime', outdir,'/workdir', os.path.join(outdir,'out_Picard_RnaMetrics'),'/PicardDir', os.path.dirname(options.refFlat),'/refFlatdir', os.path.dirname(options.rRNA_interval),'/rRNAdir', os.path.join('/workdir/',os.path.basename(inpbam)), os.path.join('/refFlatdir',os.path.basename(options.refFlat)), os.path.join('/rRNAdir',os.path.basename(options.rRNA_interval)), os.path.join('/PicardDir',prefix+'_RnaSeqMetrics.txt'), strand) <NEW_LINE> run_command_line(system_call) <NEW_LINE> <DEDENT> metricfilepath = os.path.join(outdir,'out_Picard_RnaMetrics',prefix+'_RnaSeqMetrics.txt') <NEW_LINE> system_call = 'docker run --rm -v %s:%s:ro -v %s:%s:ro -v %s:%s genomicsdocker/picard:2.5.0 results_RnaSeqMetrics.py --metricfile %s --metricpath %s --xrRNAbasecount %s --result_json %s --fig %s' %( '/etc/localtime','/etc/localtime', options.outdir,'/workdir', os.path.join(options.outdir,'out_Picard_RnaMetrics'),'/PicardDir', os.path.join('/PicardDir',prefix+'_RnaSeqMetrics.txt'), metricfilepath, os.path.join('/workdir',os.path.basename(xrRNAcount)), os.path.join('/PicardDir','temp.json'), os.path.join('/PicardDir','RnaSeqQCMetrics.png')) <NEW_LINE> run_command_line(system_call) <NEW_LINE> os.rename(os.path.join(outdir,'out_Picard_RnaMetrics','temp.json'),os.path.join(outdir,'out_Picard_RnaMetrics','RnaSeqMetrics_results.json')) | 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 = [] <NEW_LINE> for p, v in zip(self.pos_v, self.extend_v): <NEW_LINE> <INDENT> if v != 0: <NEW_LINE> <INDENT> lower.append(p) <NEW_LINE> <DEDENT> <DEDENT> upper = [] <NEW_LINE> for p, v in zip(self.pos_v, self.extend_v): <NEW_LINE> <INDENT> if v != 0: <NEW_LINE> <INDENT> if v + p != 0: <NEW_LINE> <INDENT> x = p + v <NEW_LINE> upper.append(x) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> upper = numpy.array(upper, dtype=numpy.float64) <NEW_LINE> lower = numpy.array(lower, dtype=numpy.float64) <NEW_LINE> I = cubature(self.f_int, ndim=lower.shape[0], fdim=upper.shape[0], maxEval=10000, xmin=lower, xmax=upper, adaptive='p', ) <NEW_LINE> return I[0][0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return self.mean | #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%m%dT%H%M%SZ') <NEW_LINE> index = 0 <NEW_LINE> lines = calendar.generate_calendar_event(shift, user, dt_stamp, index) <NEW_LINE> assert lines[1] == 'DTSTART;VALUE=DATE:20180101' <NEW_LINE> assert lines[2] == 'DTEND;VALUE=DATE:20180102' | 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_flat, struct, all_adjacent, conn, criteria) <NEW_LINE> <DEDENT> if tail <= 0: <NEW_LINE> <INDENT> bin_map_below = np.less(stat_map, -threshold, bin_buff) <NEW_LINE> if tail < 0: <NEW_LINE> <INDENT> cids = _label_clusters_binary(bin_map_below, cmap, cmap_flat, struct, all_adjacent, conn, criteria) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> cids_l = _label_clusters_binary(bin_map_below, int_buff, int_buff_flat, struct, all_adjacent, conn, criteria) <NEW_LINE> x = cmap.max() <NEW_LINE> int_buff[bin_map_below] += x <NEW_LINE> cids_l += x <NEW_LINE> cmap += int_buff <NEW_LINE> cids = np.concatenate((cids, cids_l)) <NEW_LINE> <DEDENT> <DEDENT> return cids | 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 that survive the minimum duration
criterion. | 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 <NEW_LINE> for col_id in col_ids: <NEW_LINE> <INDENT> for ses_idx in range(1, num_ses + 1): <NEW_LINE> <INDENT> numpy.random.seed(rnd.randint(0, MAX_INT)) <NEW_LINE> num_occurrences = rup.sample_number_of_occurrences() <NEW_LINE> if num_occurrences: <NEW_LINE> <INDENT> num_occ_by_rup[rup] += { (col_id, ses_idx): num_occurrences} <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return num_occ_by_rup | 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_occurrences} | 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 caller. | 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(words, vision) <NEW_LINE> <DEDENT> if command == "pause" and len(words) > 2: <NEW_LINE> <INDENT> self.command_handler.pause_song(words, vision) <NEW_LINE> <DEDENT> if command == "resume" and len(words) > 2: <NEW_LINE> <INDENT> self.command_handler.resume_song(words, vision) <NEW_LINE> <DEDENT> elif command == "next" and len(words) > 2: <NEW_LINE> <INDENT> self.command_handler.next_song(words, vision) <NEW_LINE> <DEDENT> elif command == "previous" and len(words) > 2: <NEW_LINE> <INDENT> self.command_handler.previous_song(words, vision) <NEW_LINE> <DEDENT> elif StringUtil.ccs(command, "spotify") and StringUtil.ccs(words[2], "volume"): <NEW_LINE> <INDENT> self.command_handler.change_spotify_volume(words, vision) <NEW_LINE> <DEDENT> elif command == "list" and len(words) > 2: <NEW_LINE> <INDENT> self.command_handler.list_commands(words, vision) <NEW_LINE> <DEDENT> elif command == "close" and len(words) == 2: <NEW_LINE> <INDENT> vision.stop() <NEW_LINE> <DEDENT> elif command == "open" and len(words) > 2: <NEW_LINE> <INDENT> self.command_handler.open_program(words) <NEW_LINE> <DEDENT> elif command == "close" and len(words) == 3: <NEW_LINE> <INDENT> self.command_handler.close_program(words) <NEW_LINE> <DEDENT> elif command == "text" and len(words) > 2: <NEW_LINE> <INDENT> self.command_handler.text_mode(words, vision) <NEW_LINE> <DEDENT> elif command == "login" and len(words) > 2: <NEW_LINE> <INDENT> self.command_handler.program_login(words, vision) <NEW_LINE> <DEDENT> elif command == "debug" and len(words) > 2: <NEW_LINE> <INDENT> self.command_handler.change_debug(words, vision) <NEW_LINE> <DEDENT> elif command == "profanity" and len(words) > 2: <NEW_LINE> <INDENT> self.command_handler.change_profanity(words, vision) <NEW_LINE> <DEDENT> elif command == "search" and len(words) > 2: <NEW_LINE> <INDENT> self.command_handler.search(words, vision) | 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 dtype not in 'dfDF': <NEW_LINE> <INDENT> dtype = 'd' <NEW_LINE> <DEDENT> if type in ['constant', 'c']: <NEW_LINE> <INDENT> ret = data - np.mean(data, axis, keepdims=True) <NEW_LINE> return ret <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dshape = data.shape <NEW_LINE> N = dshape[axis] <NEW_LINE> bp = np.sort(np.unique(np.r_[0, bp, N])) <NEW_LINE> if np.any(bp > N): <NEW_LINE> <INDENT> raise ValueError("Breakpoints must be less than length " "of data along given axis.") <NEW_LINE> <DEDENT> Nreg = len(bp) - 1 <NEW_LINE> rnk = len(dshape) <NEW_LINE> if axis < 0: <NEW_LINE> <INDENT> axis = axis + rnk <NEW_LINE> <DEDENT> newdims = np.r_[axis, 0:axis, axis + 1:rnk] <NEW_LINE> newdata = np.reshape(np.transpose(data, tuple(newdims)), (N, _prod(dshape) // N)) <NEW_LINE> if not overwrite_data: <NEW_LINE> <INDENT> newdata = newdata.copy() <NEW_LINE> <DEDENT> if newdata.dtype.char not in 'dfDF': <NEW_LINE> <INDENT> newdata = newdata.astype(dtype) <NEW_LINE> <DEDENT> for m in range(Nreg): <NEW_LINE> <INDENT> Npts = bp[m + 1] - bp[m] <NEW_LINE> A = np.ones((Npts, 2), dtype) <NEW_LINE> A[:, 0] = np.cast[dtype](np.arange(1, Npts + 1) * 1.0 / Npts) <NEW_LINE> sl = slice(bp[m], bp[m + 1]) <NEW_LINE> coef, resids, rank, s = linalg.lstsq(A, newdata[sl]) <NEW_LINE> newdata[sl] = newdata[sl] - np.dot(A, coef) <NEW_LINE> <DEDENT> tdshape = np.take(dshape, newdims, 0) <NEW_LINE> ret = np.reshape(newdata, tuple(tdshape)) <NEW_LINE> vals = list(range(1, rnk)) <NEW_LINE> olddims = vals[:axis] + [0] + vals[axis:] <NEW_LINE> ret = np.transpose(ret, tuple(olddims)) <NEW_LINE> return ret | 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),
the result of a linear least-squares fit to `data` is subtracted
from `data`.
If ``type == 'constant'``, only the mean of `data` is subtracted.
bp : array_like of ints, optional
A sequence of break points. If given, an individual linear fit is
performed for each part of `data` between two break points.
Break points are specified as indices into `data`. This parameter
only has an effect when ``type == 'linear'``.
overwrite_data : bool, optional
If True, perform in place detrending and avoid a copy. Default is False
Returns
-------
ret : ndarray
The detrended input data.
Examples
--------
>>> from scipy import signal
>>> from numpy.random import default_rng
>>> rng = default_rng()
>>> npoints = 1000
>>> noise = rng.standard_normal(npoints)
>>> x = 3 + 2*np.linspace(0, 1, npoints) + noise
>>> (signal.detrend(x) - noise).max()
0.06 # random | 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.
The coordinates returned are for the pixel centres. This is
slightly inconsistent with usual GDAL usage, but more likely to
be what one wants.
| 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.headers["Authorization"] = "Bearer " + self.auth_token <NEW_LINE> <DEDENT> return req | 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_type']) <NEW_LINE> run = SimilarityRun.objects.create( name=kwargs.get('run_name'), created_date=datetime.datetime.now(), created_by_id=kwargs.get('user_id'), feature_source='party', similarity_threshold=kwargs['similarity_threshold'], unit_source='party', ) <NEW_LINE> similar_results = [] <NEW_LINE> for party_a_pk, party_a_name in parties: <NEW_LINE> <INDENT> for party_b_pk, party_b_name in parties: <NEW_LINE> <INDENT> if party_a_pk == party_b_pk: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if not kwargs['case_sensitive']: <NEW_LINE> <INDENT> party_a_name = party_a_name.upper() <NEW_LINE> party_b_name = party_b_name.upper() <NEW_LINE> <DEDENT> score = scorer(party_a_name, party_b_name) <NEW_LINE> if score >= kwargs['similarity_threshold']: <NEW_LINE> <INDENT> similar_results.append( PartySimilarityModel( run=run, party_a_id=party_a_pk, party_b_id=party_b_pk, similarity=score)) <NEW_LINE> <DEDENT> <DEDENT> self.push() <NEW_LINE> <DEDENT> PartySimilarityModel.objects.bulk_create(similar_results, ignore_conflicts=True) <NEW_LINE> self.push() <NEW_LINE> Action.objects.create(name='Processed Similarity Tasks', message=f'{self.name} task is finished', user_id=kwargs.get('user_id'), content_type=ContentType.objects.get_for_model(SimilarityRun), model_name='SimilarityRun', app_label='analyze', object_pk=run.pk) | 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_parent_genre() | 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_data_frame, index='qux') <NEW_LINE> assert_raises(ValueError, epochs.to_data_frame, np.arange(400)) <NEW_LINE> df = epochs.to_data_frame(index=['condition', 'epoch', 'time'], picks=list(range(epochs.info['nchan']))) <NEW_LINE> df2 = epochs.to_data_frame() <NEW_LINE> assert_equal(df.index.names, df2.index.names) <NEW_LINE> assert_array_equal(df.columns.values, epochs.ch_names) <NEW_LINE> data = np.hstack(epochs.get_data()) <NEW_LINE> assert_true((df.columns == epochs.ch_names).all()) <NEW_LINE> assert_array_equal(df.values[:, 0], data[0] * 1e13) <NEW_LINE> assert_array_equal(df.values[:, 2], data[2] * 1e15) <NEW_LINE> for ind in ['time', ['condition', 'time'], ['condition', 'time', 'epoch']]: <NEW_LINE> <INDENT> df = epochs.to_data_frame(index=ind) <NEW_LINE> assert_true(df.index.names == ind if isinstance(ind, list) else [ind]) <NEW_LINE> assert_array_equal(sorted(df.reset_index().columns[:3]), sorted(['time', 'condition', 'epoch'])) | 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) <NEW_LINE> self.assertContains(response, "has not contributed to any boards") <NEW_LINE> self.assertContains(response, "has not evaluated any boards") | 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=t_typing)) <NEW_LINE> return _TypeInfo(t_typing, class_, args, parameters) | 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_lang <NEW_LINE> <DEDENT> except DictNotFoundError: <NEW_LINE> <INDENT> pass | 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 - 1)) ** 0.5 <NEW_LINE> S_L = left.u - left.sound_speed() * q_L <NEW_LINE> S_R = right.u + right.sound_speed() * q_R <NEW_LINE> S_Star = self.__evaluate_S_star(left, right, S_L, S_R) <NEW_LINE> return S_L, S_R, S_Star | 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), timezone.get_current_timezone())).first().id)) <NEW_LINE> self.assertEquals(response.status_code, 403) | 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 request it in mul_vector in order to calculate
the numerical value of the matrix. | 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> <DEDENT> monkeypatch.setattr('django_cas_ng.backends._verify', mock_verify) <NEW_LINE> assert not django_user_model.objects.filter( username='test@example.com', ).exists() <NEW_LINE> backend = backends.CASBackend() <NEW_LINE> user = backend.authenticate( ticket='fake-ticket', service='fake-service', request=request, ) <NEW_LINE> assert user is None <NEW_LINE> assert not django_user_model.objects.filter( username='test@example.com', ).exists() | 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: <NEW_LINE> <INDENT> longest = len(current) <NEW_LINE> current = v <NEW_LINE> <DEDENT> elif v in current: <NEW_LINE> <INDENT> current = "" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> current += v <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return 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): <NEW_LINE> <INDENT> raise ValueError("invalid address tuple passed as argument: {}".format(address)) <NEW_LINE> <DEDENT> if not isinstance(server_queue, Queue): <NEW_LINE> <INDENT> raise ValueError("server_queue argument is not a queue.Queue") <NEW_LINE> <DEDENT> if not isinstance(log_file, str): <NEW_LINE> <INDENT> raise ValueError("invalid log_file name passed as argument: {}".format(log_file)) <NEW_LINE> <DEDENT> self.socket = sock <NEW_LINE> self.address = address <NEW_LINE> self.server_queue = server_queue <NEW_LINE> self.message_queue = Queue() <NEW_LINE> self.debug = debug <NEW_LINE> self.log_file = log_file | :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_LINE> spaces = " " * num_of_spaces <NEW_LINE> list_type = "" <NEW_LINE> if list[-1] == "#": <NEW_LINE> <INDENT> list_type = "1." <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> list_type = "*" <NEW_LINE> <DEDENT> additional_space = "" <NEW_LINE> if text[0] != " ": <NEW_LINE> <INDENT> additional_space = " " <NEW_LINE> <DEDENT> line = spaces + list_type + additional_space + text <NEW_LINE> <DEDENT> match = re.match('(!+)(\\s?)[^\\[]', line) <NEW_LINE> if match: <NEW_LINE> <INDENT> header, spaces = match.groups() <NEW_LINE> new_str = '#' * len(header) <NEW_LINE> line = re.sub('(!+)(\\s?)([^\\[])', new_str + ' ' + '\\3', line) <NEW_LINE> <DEDENT> line = re.sub("__(.*?)__", "\\1", line) <NEW_LINE> line = re.sub("''(.*?)''", "**\\1**", line) <NEW_LINE> line = re.sub("//(.*?)//", "_\\1_", line) <NEW_LINE> line = re.sub("\\[\\[(\\w+?)\\]\\]", "\\1", line) <NEW_LINE> line = re.sub("\\[\\[(.*)\\|(.*)\\]\\]", "[\\1](\\2)", line) <NEW_LINE> line = re.sub("\\{\\{\\{(.*?)\\}\\}\\}", "`\\1`", line) <NEW_LINE> match = re.search("```(.*)```", line) <NEW_LINE> if match: <NEW_LINE> <INDENT> text = match.groups()[0] <NEW_LINE> fn.append(text) <NEW_LINE> line = re.sub("```(.*)```", '[^{}]'.format(fn_n), line) <NEW_LINE> fn_n += 1 <NEW_LINE> <DEDENT> new_text.append(line) <NEW_LINE> <DEDENT> for i, each in enumerate(fn): <NEW_LINE> <INDENT> new_text.append('[^{}]: {}'.format(i+1, each)) <NEW_LINE> <DEDENT> return '\n'.join(new_text) | 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) <NEW_LINE> path_spec.parent = None <NEW_LINE> file_object = tsk_file_io.TSKFile(self._resolver_context, path_spec) <NEW_LINE> with self.assertRaises(errors.PathSpecError): <NEW_LINE> <INDENT> 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> <DEDENT> return True <NEW_LINE> <DEDENT> return False | 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 class data, or
:data:`False` | 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> self.logger.error('Error while getting %s', id) <NEW_LINE> return None | 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_LINE> alarm_control_panel.alarm_arm_away(self.hass) <NEW_LINE> self.hass.block_till_done() <NEW_LINE> self.assertEqual(('alarm/command', 'ARM_AWAY', 0, False), self.mock_publish.mock_calls[-1][1]) | 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: <NEW_LINE> <INDENT> linC.set_dense_data(format_matrix(linPy.data, shape=linPy.shape)) <NEW_LINE> linC.set_data_ndim(len(linPy.data.shape)) | 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_LINE> <DEDENT> for i in range(N): <NEW_LINE> <INDENT> plt.plot(qpath[:,0,i], qpath[:,1,i], 'y-',linewidth=0.5) <NEW_LINE> <DEDENT> plot_reference(qpath[0,:,:],shadow) <NEW_LINE> plot_target(qpath[-1,:,:],shadow) | 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, "QuantileAccumulator") as name: <NEW_LINE> <INDENT> self._quantile_accumulator_handle = ( gen_quantile_ops.quantile_stream_resource_handle_op( container=container, shared_name=name, name=name)) <NEW_LINE> self._create_op = gen_quantile_ops.create_quantile_accumulator( self._quantile_accumulator_handle, init_stamp_token, epsilon=epsilon, max_elements=max_elements, num_quantiles=num_quantiles, generate_quantiles=generate_quantiles) <NEW_LINE> is_initialized_op = gen_quantile_ops.quantile_accumulator_is_initialized( self._quantile_accumulator_handle) <NEW_LINE> <DEDENT> resources.register_resource(self._quantile_accumulator_handle, self._create_op, is_initialized_op) <NEW_LINE> self._make_savable(name) | 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 save the accumulator under.
container: An optional `string`. Defaults to `""`
generate_quantiles: Generate quantiles instead of approximate boundaries.
If true, exactly `num_quantiles` will be produced in the final summary. | 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> sentimentScore = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sentimentScore = response['docSentiment']['score'] <NEW_LINE> <DEDENT> self.sentimentFromText = AlchemyStructure.Sentiment() <NEW_LINE> self.sentimentFromText.setType(sentimentType) <NEW_LINE> self.sentimentFromText.setScore(sentimentScore) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print('Error in sentiment analysis call: ', response['statusInfo']) | method for extracting the sentiment associated with the text of a document | 625941c24f88993c3716c019 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.