code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
with open(source, 'r') as fp: data = json.load(fp) register_grant(data)
def registergrant(source=None, setspec=None)
Harvest grants from OpenAIRE.
4.32767
4.994899
0.866418
if os.path.isfile(destination): click.confirm("Database '{0}' already exists." "Do you want to write to it?".format(destination), abort=True) # no cover dumper = OAIREDumper(destination, setspec=setspec) dumper.dump(as_json=a...
def dumpgrants(destination, as_json=None, setspec=None)
Harvest grants from OpenAIRE and store them locally.
5.12184
4.804772
1.06599
o = self.store.findFirst( offering.InstalledOffering, (offering.InstalledOffering.offeringName == self["name"])) if o is None: raise usage.UsageError("No offering of that name" " is installed.") fp = sel...
def postOptions(self)
Find an installed offering and set the site front page to its application's front page.
10.181158
6.769609
1.503951
p = patterns[parameter.type + '-input-container'] if parameter.type == TEXTAREA_INPUT: p = dictFillSlots(p, dict(label=parameter.label, name=parameter.name, value=parameter.default or '')) elif parameter.type == MULTI_TEXT_INP...
def _legacySpecialCases(form, patterns, parameter)
Create a view object for the given parameter. This function implements the remaining view construction logic which has not yet been converted to the C{viewFactory}-style expressed in L{_LiveFormMixin.form}. @type form: L{_LiveFormMixin} @param form: The form fragment which contains the given param...
3.294372
3.366544
0.978562
if parameter.type == TEXT_INPUT: return TextParameterView(parameter) if parameter.type == PASSWORD_INPUT: return PasswordParameterView(parameter) if parameter.type == FORM_INPUT: return FormInputParameterView(parameter) return None
def _textParameterToView(parameter)
Return a L{TextParameterView} adapter for C{TEXT_INPUT}, C{PASSWORD_INPUT}, and C{FORM_INPUT} L{Parameter} instances.
2.639775
1.795732
1.470027
try: values = inputs[self.name] except KeyError: raise ConfigurationError( "Missing value for input: " + self.name) return self.coerceMany(values)
def fromInputs(self, inputs)
Extract the inputs associated with the child forms of this parameter from the given dictionary and coerce them using C{self.coercer}. @type inputs: C{dict} mapping C{unicode} to C{list} of C{unicode} @param inputs: The contents of a form post, in the conventional structure. ...
5.049146
5.561209
0.907922
return self.__class__( self.name, self.type, self.coercer, self.label, self.description, default, self.viewFactory)
def clone(self, default)
Make a copy of this parameter, supplying a different default. @type default: C{unicode} or C{NoneType} @param default: A value which will be initially presented in the view as the value for this parameter, or C{None} if no such value is to be presented. @rtype: L{Parameter}
6.032897
5.436469
1.109709
liveForm = liveForm.asSubForm(self.name) # XXX Why did this work??? # if we are compact, tell the liveform so it can tell its parameters # also if self._parameterIsCompact: liveForm.compact() return liveForm
def _prepareSubForm(self, liveForm)
Utility for turning liveforms into subforms, and compacting them as necessary. @param liveForm: a liveform. @type liveForm: L{LiveForm} @return: a sub form. @rtype: L{LiveForm}
14.242649
16.706869
0.852503
if isinstance(original, ChoiceParameter): default = [Option(o.description, o.value, o.value in default) for o in original.choices] return original.clone(default)
def _cloneDefaultedParameter(self, original, default)
Make a copy of the parameter C{original}, supplying C{default} as the default value. @type original: L{Parameter} or L{ChoiceParameter} @param original: A liveform parameter. @param default: An alternate default value for the parameter. @rtype: L{Parameter} or L{ChoiceParamete...
5.545657
6.175319
0.898036
identifier = self._allocateID() self._idsToObjects[identifier] = defaultObject return identifier
def _idForObject(self, defaultObject)
Generate an opaque identifier which can be used to talk about C{defaultObject}. @rtype: C{int}
7.741966
7.857587
0.985285
id = self._allocateID() self._idsToObjects[id] = self._NO_OBJECT_MARKER self._lastValues[id] = None return id
def _newIdentifier(self)
Make a new identifier for an as-yet uncreated model object. @rtype: C{int}
8.718472
9.351814
0.932276
liveForm = self.liveFormFactory(lambda **k: None, parameters, self.name) liveForm = self._prepareSubForm(liveForm) liveForm = self.repeatedLiveFormWrapper(liveForm, identifier, removable) liveForm.docFactory = webtheme.getLoader(liveForm.fragmentName) return liveForm
def _makeALiveForm(self, parameters, identifier, removable=True)
Make a live form with the parameters C{parameters}, which will be used to edit the values/model object with identifier C{identifier}. @type parameters: C{list} @param parameters: list of L{Parameter} instances. @type identifier: C{int} @type removable: C{bool} @rtype:...
7.622736
7.619284
1.000453
parameters = [self._cloneDefaultedParameter(p, defaults[p.name]) for p in self.parameters] return self._makeALiveForm(parameters, identifier)
def _makeDefaultLiveForm(self, (defaults, identifier))
Make a liveform suitable for editing the set of default values C{defaults}. @type defaults: C{dict} @param defaults: Mapping of parameter names to values. @rtype: L{repeatedLiveFormWrapper}
6.878191
9.701349
0.708993
liveForms = [] if self._defaultStuff: for values in self._defaultStuff: liveForms.append(self._makeDefaultLiveForm(values)) else: # or only one, for the first new thing liveForms.append( self._makeALiveForm( ...
def getInitialLiveForms(self)
Make and return as many L{LiveForm} instances as are necessary to hold our default values. @return: some subforms. @rtype: C{list} of L{LiveForm}
9.424569
8.747318
1.077424
# make a liveform because there is some logic in _coerced form = LiveForm(lambda **k: None, self.parameters, self.name) return form.fromInputs(dataSet)
def _coerceSingleRepetition(self, dataSet)
Make a new liveform with our parameters, and get it to coerce our data for us.
19.772711
12.416184
1.592495
for dataSet in dataSets: modelObject = self._objectFromID(dataSet[self._IDENTIFIER_KEY]) if modelObject is self._NO_OBJECT_MARKER: dataCopy = dataSet.copy() identifier = dataCopy.pop(self._IDENTIFIER_KEY) yield identifier, dataCopy
def _extractCreations(self, dataSets)
Find the elements of C{dataSets} which represent the creation of new objects. @param dataSets: C{list} of C{dict} mapping C{unicode} form submission keys to form submission values. @return: iterator of C{tuple}s with the first element giving the opaque identifier of an ...
5.667999
5.545042
1.022174
def associate(result, obj): return (obj, result) coerceDeferreds = [] for obj, dataSet in inputs: oneCoerce = self._coerceSingleRepetition(dataSet) oneCoerce.addCallback(associate, obj) coerceDeferreds.append(oneCoerce) return gat...
def _coerceAll(self, inputs)
XXX
6.141427
6.184057
0.993106
# Xxx - This does a slightly complex (hey, it's like 20 lines, how # complex could it really be?) thing to figure out which elements are # newly created, which elements were edited, and which elements no # longer exist. It might be simpler if the client kept track of this ...
def coercer(self, dataSets)
Coerce all of the repetitions and sort them into creations, edits and deletions. @rtype: L{ListChanges} @return: An object describing all of the creations, modifications, and deletions represented by C{dataSets}.
6.609725
6.423474
1.028995
outputs = [] for i in xrange(self.count): name = self.name + '_' + str(i) try: value = inputs[name][0] except KeyError: raise ConfigurationError( "Missing value for field %d of %s" % (i, self.name)) ...
def fromInputs(self, inputs)
Extract the inputs associated with this parameter from the given dictionary and coerce them using C{self.coercer}. @type inputs: C{dict} mapping C{str} to C{list} of C{str} @param inputs: The contents of a form post, in the conventional structure. @rtype: L{Deferred} ...
3.844506
3.540006
1.086017
return self.__class__( self.name, choices, self.label, self.description, self.multiple, self.viewFactory)
def clone(self, choices)
Make a copy of this parameter, supply different choices. @param choices: A sequence of L{Option} instances. @type choices: C{list} @rtype: L{ChoiceParameter}
6.580849
7.373397
0.892512
self.docFactory = webtheme.getLoader(self.compactFragmentName) for param in self.parameters: param.compact()
def compact(self)
Switch to the compact variant of the live form template. By default, this will simply create a loader for the C{self.compactFragmentName} template and compact all of this form's parameters.
31.94418
10.171266
3.14063
self.subFormName = name self.jsClass = _SUBFORM_JS_CLASS return self
def asSubForm(self, name)
Make a form suitable for nesting within another form (a subform) out of this top-level liveform. @param name: the name of the subform within its parent. @type name: C{unicode} @return: a subform. @rtype: L{LiveForm}
9.65162
15.749175
0.612833
return tags.input(type='submit', name='__submit__', value=self._getDescription())
def submitbutton(self, request, tag)
Render an INPUT element of type SUBMIT which will post this form to the server.
13.999351
9.82705
1.424573
patterns = PatternDictionary(self.docFactory) inputs = [] for parameter in self.parameters: view = parameter.viewFactory(parameter, None) if view is not None: view.setDefaultTemplate( tag.onePattern(view.patternName + '-input-...
def form(self, request, tag)
Render the inputs for a form. @param tag: A tag with: - I{form} and I{description} slots - I{liveform} and I{subform} patterns, to fill the I{form} slot - An I{inputs} slot, to fill with parameter views - L{IParameterView.patternName}I{-input-container} patte...
6.812989
4.843086
1.406746
result = self.fromInputs(formPostEmulator) result.addCallback(lambda params: self.callable(**params)) return result
def invoke(self, formPostEmulator)
Invoke my callable with input from the browser. @param formPostEmulator: a dict of lists of strings in a format like a cgi-module form post.
10.953094
11.064825
0.989902
results = [] for parameter in self.parameters: name = parameter.name.encode('ascii') d = maybeDeferred(parameter.fromInputs, received) d.addCallback(lambda value, name=name: (name, value)) results.append(d) return gatherResults(results).ad...
def fromInputs(self, received)
Convert some random strings received from a browser into structured data, using a list of parameters. @param received: a dict of lists of strings, i.e. the canonical Python form of web form post. @rtype: L{Deferred} @return: A Deferred which will be called back with a dict ...
3.659297
3.403635
1.075114
if self.parameter.label: tag[self.parameter.label] return tag
def label(self, request, tag)
Render the label of the wrapped L{Parameter} or L{ChoiceParameter} instance.
9.631812
6.65702
1.446866
if self.parameter.description is not None: tag[self.parameter.description] return tag
def description(self, request, tag)
Render the description of the wrapped L{Parameter} instance.
8.33213
6.110311
1.363618
self.liveForm.setFragmentParent(self) return self.liveForm
def realForm(self, req, tag)
Render L{liveForm}.
11.431057
6.436312
1.776026
if self.parameter.default is not None: tag[self.parameter.default] return tag
def default(self, request, tag)
Render the initial value of the wrapped L{Parameter} instance.
8.199702
6.480108
1.265365
if self.option.selected: tag(selected='selected') return tag
def selected(self, request, tag)
Render a selected attribute on the given tag if the wrapped L{Option} instance is selected.
12.205158
8.144855
1.498512
if self.parameter.multiple: tag(multiple='multiple') return tag
def multiple(self, request, tag)
Render a I{multiple} attribute on the given tag if the wrapped L{ChoiceParameter} instance allows multiple selection.
15.940795
8.589834
1.855774
option = tag.patternGenerator('option') return tag[[ OptionView(index, o, option()) for (index, o) in enumerate(self.parameter.choices)]]
def options(self, request, tag)
Render each of the options of the wrapped L{ChoiceParameter} instance.
24.392481
15.26374
1.598067
liveForms = self.parameter.getInitialLiveForms() for liveForm in liveForms: liveForm.setFragmentParent(self) return liveForms
def forms(self, req, tag)
Make and return some forms, using L{self.parameter.getInitialLiveForms}. @return: some subforms. @rtype: C{list} of L{LiveForm}
10.513508
3.685095
2.852982
liveForm = self.parameter.asLiveForm() liveForm.setFragmentParent(self) return liveForm
def repeatForm(self)
Make and return a form, using L{self.parameter.asLiveForm}. @return: a subform. @rtype: L{LiveForm}
15.015817
4.783158
3.13931
repeater = inevow.IQ(self.docFactory).onePattern('repeater') return repeater.fillSlots( 'object-description', self.parameter.modelObjectDescription)
def repeater(self, req, tag)
Render some UI for repeating our form.
18.58954
13.818392
1.345275
subform = self.parameter.form.asSubForm(self.parameter.name) subform.setFragmentParent(self) return tag[subform]
def input(self, request, tag)
Add the wrapped form, as a subform, as a child of the given tag.
10.511663
7.131009
1.474078
ra_deg = 290.66666667 dec_deg = +44.5 #rollAngle_deg = 33.0 rollAngle_deg = +123. boresight = r.vecFromRaDec(ra_deg, dec_deg) #Read in prime mission coords and convert to vectors inFile = "../etc/fov.txt" inFile = np.loadtxt(inFile) radecs = np.zeros( (len(inFile), 3)) rot...
def generateVectors()
Convert the known ra/decs of the channel corners into unit vectors. This code creates the conents of the function loadOriginVectors() (below)
4.454671
4.229782
1.053168
# Endpoint parameters params = { 'idStop': kwargs.get('stop_number'), 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = self.make_request('geo', 'get_arrive_stop', **params) # Funny endpoint, no status code ...
def get_arrive_stop(self, **kwargs)
Obtain bus arrival info in target stop. Args: stop_number (int): Stop number to query. lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[Arrival]), or message string in case of error.
8.039038
7.652474
1.050515
# Endpoint parameters params = { 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = self.make_request('geo', 'get_groups', **params) if not util.check_result(result): return False, result.get('resultDescription', ...
def get_groups(self, **kwargs)
Obtain line types and details. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[GeoGroupItem]), or message string in case of error.
8.46016
7.421433
1.139963
# Endpoint parameters select_date = '%02d/%02d/%d' % ( kwargs.get('day', '01'), kwargs.get('month', '01'), kwargs.get('year', '1970') ) params = { 'fecha': select_date, 'line': util.ints_to_string(kwargs.get('lines', [...
def get_info_line(self, **kwargs)
Obtain basic information on a bus line on a given date. Args: day (int): Day of the month in format DD. The number is automatically padded if it only has one digit. month (int): Month number in format MM. The number is automatically padded if it only has ...
5.748291
5.318984
1.080712
# Endpoint parameters params = { 'coordinateX': kwargs.get('longitude'), 'coordinateY': kwargs.get('latitude'), 'tipos': util.ints_to_string(kwargs.get('types')), 'Radius': kwargs.get('radius'), 'cultureInfo': util.language_code(kwargs...
def get_poi(self, **kwargs)
Obtain a list of POI in the given radius. Args: latitude (double): Latitude in decimal degrees. longitude (double): Longitude in decimal degrees. types (list[int] | int): POI IDs (or empty list to get all). radius (int): Radius (in meters) of the search. ...
6.692686
6.358956
1.052482
# Endpoint parameters params = { 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = self.make_request('geo', 'get_poi_types', **params) # Parse values = result.get('types', []) return True, [emtype.PoiType(**a...
def get_poi_types(self, **kwargs)
Obtain POI types. Args: lang (str): Language code (*es* or *en*). Returns: Status boolean and parsed response (list[PoiType]), or message string in case of error.
8.745028
9.316455
0.938665
# Endpoint parameters select_date = '%02d/%02d/%d' % ( kwargs.get('day', '01'), kwargs.get('month', '01'), kwargs.get('year', '1970') ) params = { 'SelectDate': select_date, 'Lines': util.ints_to_string(kwargs.get('lin...
def get_route_lines_route(self, **kwargs)
Obtain itinerary for one or more lines in the given date. Args: day (int): Day of the month in format DD. The number is automatically padded if it only has one digit. month (int): Month number in format MM. The number is automatically padded if it only ha...
4.968533
4.19746
1.1837
# Endpoint parameters params = { 'line': util.ints_to_string(kwargs.get('lines', [])), 'direction': util.direction_code(kwargs.get('direction', '')), 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = self.make...
def get_stops_line(self, **kwargs)
Obtain information on the stops of the given lines. Arguments: lines (list[int] | int): Lines to query, may be empty to get all the lines. direction (str): Optional, either *forward* or *backward*. lang (str): Language code (*es* or *en*). Returns: ...
7.188772
6.860745
1.047812
# Endpoint parameters params = { 'description': kwargs.get('street_name'), 'streetNumber': kwargs.get('street_number'), 'Radius': kwargs.get('radius'), 'Stops': kwargs.get('stops'), 'cultureInfo': util.language_code(kwargs.get('lang'))...
def get_street(self, **kwargs)
Obtain a list of nodes related to a location within a given radius. Not sure of its use, but... Args: street_name (str): Name of the street to search. street_number (int): Street number to search. radius (int): Radius (in meters) of the search. stops (in...
7.369144
5.886872
1.251793
# Endpoint parameters params = { 'coordinateX': kwargs.get('longitude'), 'coordinateY': kwargs.get('latitude'), 'Radius': kwargs.get('radius'), 'cultureInfo': util.language_code(kwargs.get('lang')) } # Request result = sel...
def get_street_from_xy(self, **kwargs)
Obtain a list of streets around the specified point. Args: latitude (double): Latitude in decimal degrees. longitude (double): Longitude in decimal degrees. radius (int): Radius (in meters) of the search. lang (str): Language code (*es* or *en*). Returns...
6.854416
6.753968
1.014872
loader = LocalFundRefLoader(source=source) if source \ else RemoteFundRefLoader() for funder_json in loader.iter_funders(): register_funder.delay(funder_json)
def harvest_fundref(source=None)
Harvest funders from FundRef and store as authority records.
6.79596
6.457891
1.05235
loader = LocalOAIRELoader(source=source) if source \ else RemoteOAIRELoader(setspec=setspec) for grant_json in loader.iter_grants(): register_grant.delay(grant_json)
def harvest_openaire_projects(source=None, setspec=None)
Harvest grants from OpenAIRE and store as authority records.
7.249403
6.352196
1.141244
setspecs = current_app.config['OPENAIRE_GRANTS_SPECS'] chain(harvest_openaire_projects.s(setspec=setspec) for setspec in setspecs).apply_async()
def harvest_all_openaire_projects()
Reharvest all grants from OpenAIRE. Harvest all OpenAIRE grants in a chain to prevent OpenAIRE overloading from multiple parallel harvesting.
7.562056
5.780907
1.308109
resolver = Resolver( pid_type=pid_type, object_type='rec', getter=Record.get_record) try: pid, record = resolver.resolve(data[id_key]) data_c = deepcopy(data) del data_c['remote_modified'] record_c = deepcopy(record) del record_c['remote_modified'] #...
def create_or_update_record(data, pid_type, id_key, minter)
Register a funder or grant.
4.112199
4.060488
1.012735
instance = instance._redpipe_future_result # noqa except AttributeError: pass try: other = other._redpipe_future_result except AttributeError: pass return instance is other
def IS(instance, other): # noqa try
Support the `future is other` use-case. Can't override the language so we built a function. Will work on non-future objects too. :param instance: future or any python object :param other: object to compare. :return:
5.945655
8.687112
0.684423
instance = instance._redpipe_future_result except AttributeError: pass return isinstance(instance, A_tuple)
def ISINSTANCE(instance, A_tuple): # noqa try
Allows you to do isinstance checks on futures. Really, I discourage this because duck-typing is usually better. But this can provide you with a way to use isinstance with futures. Works with other objects too. :param instance: :param A_tuple: :return:
16.517229
15.588101
1.059605
@wraps(func) def inner(self, o): try: return o._redpipe_future_result # noqa except AttributeError: pass return func(self, o) return inner
def _json_default_encoder(func)
Monkey-Patch the core json encoder library. This isn't as bad as it sounds. We override the default method so that if an object falls through and can't be encoded normally, we see if it is a Future object and return the result to be encoded. I set a special attribute on the Future object so I can t...
6.298666
5.485741
1.148189
if installation.suspended: raise RuntimeError("Installation already suspended") powerups = list(installation.allPowerups) for p in powerups: if INavigableElement.providedBy(p): p.store.powerDown(p, INavigableElement) sne = SuspendedNavigableElement(store=p.store,...
def suspendJustTabProviders(installation)
Replace INavigableElements with facades that indicate their suspension.
5.699721
5.076263
1.122818
if not installation.suspended: raise RuntimeError("Installation not suspended") powerups = list(installation.allPowerups) allSNEs = list(powerups[0].store.powerupsFor(ISuspender)) for p in powerups: for sne in allSNEs: if sne.originalNE is p: p.store.powe...
def unsuspendTabProviders(installation)
Remove suspension facades and replace them with their originals.
5.273697
4.9465
1.066147
bf = self.copy() result = bf.query.executeQuery(format="soa") return result["_rowName"]
def rows(self)
Returns a numpy array of the rows name
49.119255
32.669788
1.503507
bf = self.copy() content = requests.get(bf.dataset_url).json() rowCount = content['status']['rowCount'] valueCount = content['status']['valueCount'] return (rowCount, valueCount)
def shape(self)
Returns (rowCount, valueCount)
8.643944
5.585498
1.547569
if isinstance(value, Column): self.query.addWHERE("(({}){}({}))".format( self.execution_name, operator, value.execution_name)) elif isinstance(value, str): self.query.addWHERE("(({}){}\'{}\')".format( self.e...
def _comparison(self, value, operator)
Parameters ---------- value: Column object or base type The value against which to compare the column. It can either be another column or a base type value (e.g. int) Returns ------- self.query Notes ----- Returning self.query wil...
3.288177
3.164838
1.038972
if isinstance(right, (int, float)): right = right elif isinstance(right, Column): right = right.execution_name else: raise AttributeError( "{} can only be used ".format(binary) + "with integer, float or column") ...
def _binary_arithemtic(self, left, binary, right)
Parameters ---------- operand: Column object, integer or float Value on which to apply operator to this column binary: char binary arithmetic operator (-, +, *, /, ^, %) Returns ------- self Notes ----- Returning self will...
3.076272
2.873088
1.07072
copy = self.copy() copy.query.removeSELECT("{}".format(copy.execution_name)) copy.execution_name = "{}({})".format(unary, self.execution_name) copy.query.addSELECT(copy.execution_name) return copy
def _unary_arithmetic(self, unary)
Parameters ---------- unary: char Unary arithmetic operator (-, +) to be applied to this column Returns ------- self Notes ----- Returning self will allow the next object to use this column ops and concatenate something else
5.888443
7.192858
0.818651
col = self.copy() col.query.setLIMIT(n) return col.toPandas()
def head(self, n=5)
Returns first n rows
17.916903
15.109885
1.185774
encoding = kwargs.get('encoding') or 'utf-8' value = '\t'.join([s for s in tup]) + '\n' output_stream.write(value.encode(encoding))
def write_tsv(output_stream, *tup, **kwargs)
Write argument list in `tup` out as a tab-separeated row to the stream.
3.272712
3.207425
1.020355
if cols: cols = [c if not c in ('x', 'X', 0, None) else random_string(length=5) for c in cols] Record = collections.namedtuple('Record', cols) for line in input_stream: yield Record._make(line.decode(encoding).rstrip('\n').split('\t')) else: for l...
def iter_tsv(input_stream, cols=None, encoding='utf-8')
If a tuple is given in cols, use the elements as names to construct a namedtuple. Columns can be marked as ignored by using ``X`` or ``0`` as column name. Example (ignore the first four columns of a five column TSV): :: def run(self): with self.input().open() as handle: ...
2.879241
3.173702
0.907218
with open(filename, 'rb') as fp: fp.seek(0) magic = fp.read(2) if magic != b'MZ': return False # First grab the pointer to the coff_header, which is at offset 60 fp.seek(60) coff_header_offset = struct.unpack('<L', fp.read(4))[0] # Check the...
def is_authenticode_signed(filename)
Returns True if the file is signed with authenticode
2.452919
2.457701
0.998054
global _campaign_dict_cache if _campaign_dict_cache is None: # All pointing parameters and dates are stored in a JSON file fn = os.path.join(PACKAGEDIR, "data", "k2-campaign-parameters.json") _campaign_dict_cache = json.load(open(fn)) return _campaign_dict_cache
def _getCampaignDict()
Returns a dictionary specifying the details of all campaigns.
4.915404
5.041397
0.975008
try: info = _getCampaignDict()["c{0}".format(fieldnum)] # Print warning messages if necessary if "preliminary" in info and info["preliminary"] == "True": logger.warning("Warning: the position of field {0} is preliminary. " "Do not use this position...
def getFieldInfo(fieldnum)
Returns a dictionary containing the metadata of a K2 Campaign field. Raises a ValueError if the field number is unknown. Parameters ---------- fieldnum : int Campaign field number (e.g. 0, 1, 2, ...) Returns ------- field : dict The dictionary contains the keys 'ra...
6.375115
5.812895
1.096719
info = getFieldInfo(fieldnum) ra, dec, scRoll = info["ra"], info["dec"], info["roll"] # convert from SC roll to FOV coordinates # do not use the fovRoll coords anywhere else # they are internal to this script only fovRoll = fov.getFovAngleFromSpacecraftRoll(scRoll) # KeplerFov takes a l...
def getKeplerFov(fieldnum)
Returns a `fov.KeplerFov` object for a given campaign. Parameters ---------- fieldnum : int K2 Campaign number. Returns ------- fovobj : `fov.KeplerFov` object Details the footprint of the requested K2 campaign.
9.146935
9.059265
1.009677
if index and index.startswith('grants-'): # Generate suggest field suggestions = [ json.get('code'), json.get('acronym'), json.get('title') ] json['suggest'] = { 'input': [s for s in suggestions if s], 'output': json['t...
def indexer_receiver(sender, json=None, record=None, index=None, **dummy_kwargs)
Connect to before_record_index signal to transform record for ES.
3.175646
3.086582
1.028855
# Endpoint parameters start_date = util.date_string( kwargs.get('start_day', '01'), kwargs.get('start_month', '01'), kwargs.get('start_year', '1970') ) end_date = util.date_string( kwargs.get('end_day', '01'), kwargs.g...
def get_calendar(self, **kwargs)
Obtain EMT calendar for a range of dates. Args: start_day (int): Starting day of the month in format DD. The number is automatically padded if it only has one digit. start_month (int): Starting month number in format MM. The number is automatically padded...
3.417164
3.141012
1.087918
# Endpoint parameters params = {'Nodes': util.ints_to_string(kwargs.get('nodes', []))} # Request result = self.make_request('bus', 'get_nodes_lines', **params) if not util.check_result(result): return False, result.get('resultDescription', 'UNKNOWN ERROR') ...
def get_nodes_lines(self, **kwargs)
Obtain stop IDs, coordinates and line information. Args: nodes (list[int] | int): nodes to query, may be empty to get all nodes. Returns: Status boolean and parsed response (list[NodeLinesItem]), or message string in case of error.
7.673056
6.936696
1.106154
request = IRequest(ctx) root = self.webSite.rootURL(request) self._moduleRoot = root.child('__jsmodule__')
def beforeRender(self, ctx)
Before rendering, retrieve the hostname from the request being responded to and generate an URL which will serve as the root for all JavaScript modules to be loaded.
13.021248
9.402804
1.384826
if self._moduleRoot is None: raise NotImplementedError( "JS module URLs cannot be requested before rendering.") moduleHash = self.hashCache.getModule(moduleName).hashValue return self._moduleRoot.child(moduleHash).child(moduleName)
def getJSModuleURL(self, moduleName)
Retrieve an L{URL} object which references the given module name. This makes a 'best effort' guess as to an fully qualified HTTPS URL based on the hostname provided during rendering and the configuration of the site. This is to avoid unnecessary duplicate retrieval of the same scripts ...
9.147841
8.099175
1.129478
def thunk(): cr = getattr(self, 'createResource', None) if cr is not None: return cr() else: return self.createResourceWith(webViewer) return self._produceIt(segments, thunk)
def produceResource(self, request, segments, webViewer)
Return a C{(resource, subsegments)} tuple or None, depending on whether I wish to return an L{IResource} provider for the given set of segments or not.
6.550114
7.167504
0.913863
if not self.prefixURL: needle = () else: needle = tuple(self.prefixURL.split('/')) S = len(needle) if segments[:S] == needle: if segments == JUST_SLASH: # I *HATE* THE WEB subsegments = segments else...
def _produceIt(self, segments, thunk)
Underlying implmeentation of L{PrefixURLMixin.produceResource} and L{PrefixURLMixin.sessionlessProduceResource}. @param segments: the URL segments to dispatch. @param thunk: a 0-argument callable which returns an L{IResource} provider, or None. @return: a 2-tuple of C{(resourc...
10.748532
9.982406
1.076748
for iface, priority in self.__getPowerupInterfaces__([]): self.store.powerUp(self, iface, priority)
def installSite(self)
Not using the dependency system for this class because it's only installed via the command line, and multiple instances can be installed.
32.418945
30.471262
1.063919
return StylesheetRewritingResourceWrapper( File(path), self.installedOfferingNames, self.rootURL)
def makeStylesheetResource(self, path, registry)
Return a resource for the css at the given path with its urls rewritten based on self.rootURL.
41.881489
26.94523
1.554319
request = IRequest(context) request = StylesheetRewritingRequestWrapper( request, self.installedOfferingNames, self.rootURL) context.remember(request, IRequest) return self.resource.renderHTTP(context)
def renderHTTP(self, context)
Render C{self.resource} through a L{StylesheetRewritingRequestWrapper}.
9.853667
6.085501
1.619204
segments = url.split('/') if segments[0] == '': root = self.rootURL(self.request) if segments[1] == 'Mantissa': root = root.child('static').child('mantissa-base') segments = segments[2:] elif segments[1] in self.installedOfferi...
def _replace(self, url)
Change URLs with absolute paths so they are rooted at the correct location.
4.108437
3.776218
1.087977
stylesheet = ''.join(self._buffer) parser = CSSParser() css = parser.parseString(stylesheet) replaceUrls(css, self._replace) self.request.write(css.cssText) return self.request.finish()
def finish(self)
Parse the buffered response body, rewrite its URLs, write the result to the wrapped request, and finish the wrapped request.
8.058473
5.687255
1.416935
warnings.warn( "Use ISiteURLGenerator.rootURL instead of WebSite.cleartextRoot.", category=DeprecationWarning, stacklevel=2) if self.store.parent is not None: generator = ISiteURLGenerator(self.store.parent) else: generator = I...
def cleartextRoot(self, hostname=None)
Return a string representing the HTTP URL which is at the root of this site. @param hostname: An optional unicode string which, if specified, will be used as the hostname in the resulting URL, regardless of the C{hostname} attribute of this item.
4.582367
4.388759
1.044115
warnings.warn( "Use ISiteURLGenerator.rootURL instead of WebSite.rootURL.", category=DeprecationWarning, stacklevel=2) if self.store.parent is not None: generator = ISiteURLGenerator(self.store.parent) else: generator = ISiteUR...
def rootURL(self, request)
Simple utility function to provide a root URL for this website which is appropriate to use in links generated in response to the given request. @type request: L{twisted.web.http.Request} @param request: The request which is being responded to. @rtype: L{URL} @return: The locati...
3.955107
4.640679
0.852269
from xmantissa.ixmantissa import IWebTranslator, IPreferenceAggregator return URL.fromString( IWebTranslator(self.store).linkTo( IPreferenceAggregator(self.store).storeID))
def rootChild_resetPassword(self, req, webViewer)
Redirect authenticated users to their settings page (hopefully they have one) when they try to reset their password. This is the wrong way for this functionality to be implemented. See #2524.
10.663049
9.215066
1.157132
return siteStore.findUnique( cls, cls.apiName == apiName, default=None)
def getKeyForAPI(cls, siteStore, apiName)
Get the API key for the named API, if one exists. @param siteStore: The site store. @type siteStore: L{axiom.store.Store} @param apiName: The name of the API. @type apiName: C{unicode} (L{APIKey} constant) @rtype: L{APIKey} or C{NoneType}
6.612021
7.562171
0.874355
existingKey = cls.getKeyForAPI(siteStore, apiName) if existingKey is None: return cls(store=siteStore, apiName=apiName, apiKey=apiKey) existingKey.apiKey = apiKey return existingKey
def setKeyForAPI(cls, siteStore, apiName, apiKey)
Set the API key for the named API, overwriting any existing key. @param siteStore: The site store to install the key in. @type siteStore: L{axiom.store.Store} @param apiName: The name of the API. @type apiName: C{unicode} (L{APIKey} constant) @param apiKey: The key for accessi...
2.638621
2.625926
1.004834
host = request.getHeader('host') or self.hostname if ':' in host: host = host.split(':', 1)[0] for domain in [self.hostname] + getDomainNames(self.store): if (host == domain or host.startswith('www.') and host[len('www.'):] == domain): ...
def rootURL(self, request)
Return the URL for the root of this website which is appropriate to use in links generated in response to the given request. @type request: L{twisted.web.http.Request} @param request: The request which is being responded to. @rtype: L{URL} @return: The location at which the roo...
4.672271
5.023077
0.930161
checkers = [self.loginSystem, AllowAnonymousAccess()] guardedRoot = PersistentSessionWrapper( self.store, Portal(self.loginSystem, checkers), domains=[self.hostname]) unguardedRoot = UnguardedWrapper(self.store, guardedRoot) securingRoot = Sec...
def getFactory(self)
Create an L{AxiomSite} which supports authenticated and anonymous access.
8.256311
6.798511
1.214429
offeringTech = IOfferingTechnician(self.siteStore) installedOfferings = offeringTech.getInstalledOfferings() offeringsWithContent = dict([ (offering.name, offering.staticContentPath) for offering in installedOfferings.itervalues() ...
def child_static(self, context)
Serve a container page for static content for Mantissa and other offerings.
9.94227
7.704636
1.290427
shortcut = getattr(self, 'child_' + segments[0], None) if shortcut: res = shortcut(context) if res is not None: return res, segments[1:] req = IRequest(context) for plg in self.siteStore.powerupsFor(ISessionlessSiteRootPlugin): ...
def locateChild(self, context, segments)
Return a statically defined child or a child defined by a sessionless site root plugin or an avatar from guard.
5.056253
3.869489
1.306698
request = IRequest(context) if request.isSecure(): return self.wrappedResource, segments return _SecureWrapper(self.urlGenerator, self.wrappedResource), segments
def locateChild(self, context, segments)
Unwrap the wrapped resource if HTTPS is already being used, otherwise wrap it in a helper which will preserve the wrapping all the way down to the final resource.
9.646612
5.960045
1.618547
request = IRequest(context) if request.isSecure(): renderer = self.wrappedResource else: renderer = _SecureWrapper(self.urlGenerator, self.wrappedResource) return renderer.renderHTTP(context)
def renderHTTP(self, context)
Render the wrapped resource if HTTPS is already being used, otherwise invoke a helper which may generate a redirect.
6.221885
4.186349
1.486232
childDeferred = maybeDeferred( self.wrappedResource.locateChild, context, segments) def childLocated((resource, segments)): if (resource, segments) == NotFound: return NotFound return _SecureWrapper(self.urlGenerator, resource), segments ...
def locateChild(self, context, segments)
Delegate child lookup to the wrapped resource but wrap whatever results in another instance of this wrapper.
7.003218
5.618758
1.2464
if getattr(self.wrappedResource, 'needsSecure', False): request = IRequest(context) url = self.urlGenerator.encryptedRoot() if url is not None: for seg in request.prepath: url = url.child(seg) return url ret...
def renderHTTP(self, context)
Check to see if the wrapped resource wants to be rendered over HTTPS and generate a redirect if this is so, if HTTPS is available, and if the request is not already over HTTPS.
7.221918
5.515649
1.309351
name = segments[0] try: staticContent = self.staticPaths[name] except KeyError: return NotFound else: resource = File(staticContent.path) resource.processors = self.processors return resource, segments[1:] retur...
def locateChild(self, context, segments)
Find the offering with the name matching the first segment and return a L{File} for its I{staticContentPath}.
6.323667
4.879173
1.296053
if not isinstance(request_object, (MethodCall, Notification)): raise TypeError("Invalid type for request_object") method_name = request_object.method_name params = request_object.params req_id = request_object.id request_body = self.build_request_body(metho...
def handle_single_request(self, request_object)
Handles a single request object and returns the raw response :param request_object:
3.00473
3.043088
0.987395
if isinstance(method_name_or_object, MethodCall): req_obj = method_name_or_object else: req_obj = MethodCall(method_name_or_object, params) raw_response = self.handle_single_request(req_obj) response_obj = Result(result=raw_response["result"], error=raw_r...
def call_method(self, method_name_or_object, params=None)
Calls the ``method_name`` method from the given service and returns a :py:class:`gemstone.client.structs.Result` instance. :param method_name_or_object: The name of te called method or a ``MethodCall`` instance :param params: A list of dict representing the parameters for the request :r...
2.748155
2.80519
0.979668
thread_pool = self._get_thread_pool() if isinstance(method_name_or_object, MethodCall): req_obj = method_name_or_object else: req_obj = MethodCall(method_name_or_object, params) async_result_mp = thread_pool.apply_async(self.handle_single_request, args=...
def call_method_async(self, method_name_or_object, params=None)
Calls the ``method_name`` method from the given service asynchronously and returns a :py:class:`gemstone.client.structs.AsyncMethodCall` instance. :param method_name_or_object: The name of te called method or a ``MethodCall`` instance :param params: A list of dict representing the parameters fo...
2.931119
2.787607
1.051482
if isinstance(method_name_or_object, Notification): req_obj = method_name_or_object else: req_obj = Notification(method_name_or_object, params) self.handle_single_request(req_obj)
def notify(self, method_name_or_object, params=None)
Sends a notification to the service by calling the ``method_name`` method with the ``params`` parameters. Does not wait for a response, even if the response triggers an error. :param method_name_or_object: the name of the method to be called or a ``Notification`` ...
2.749801
2.776634
0.990336
# don't handle responses? if isinstance(request_object, JsonRpcResponse): return request_object error = None result = None id_ = request_object.id # validate method name if request_object.method not in self.methods: resp = Generi...
def handle_single_request(self, request_object)
Handles a single request object and returns the correct result as follows: - A valid response object if it is a regular request (with ID) - ``None`` if it was a notification (if None is returned, a response object with "received" body was already sent to the client. :param request_ob...
3.211296
3.214868
0.998889
if not isinstance(response_obj, JsonRpcResponse): raise ValueError( "Expected JsonRpcResponse, but got {} instead".format(type(response_obj).__name__)) if not self.response_is_sent: self.set_status(200) self.set_header("Content-Type", "applic...
def write_single_response(self, response_obj)
Writes a json rpc response ``{"result": result, "error": error, "id": id}``. If the ``id`` is ``None``, the response will not contain an ``id`` field. The response is sent to the client as an ``application/json`` response. Only one call per response is allowed :param response_obj: A Jso...
2.63826
2.638935
0.999744