language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
static double computeQuantile( double lo, double hi, double row, double nrows, double prob, QuantileModel.CombineMethod method ) { if( lo==hi ) return lo; // Equal; pick either if( method == null ) method= QuantileModel.CombineMethod.INTERPOLATE; switch( method ) { case INTERPOLATE: return linearInt...
python
def resolve_by_oai_id(self, oai_id): """Resolve the funder from the OpenAIRE OAI record id. Hack for when funder is not provided in OpenAIRE. """ if oai_id.startswith('oai:dnet:'): oai_id = oai_id[len('oai:dnet:'):] prefix = oai_id.split("::")[0] suffix = pre...
java
@SuppressWarnings("unchecked") @Override public EList<String> getLuminousIntensityAsString() { return (EList<String>) eGet(Ifc4Package.Literals.IFC_LIGHT_DISTRIBUTION_DATA__LUMINOUS_INTENSITY_AS_STRING, true); }
python
def load(obj, settings_module, identifier="py", silent=False, key=None): """Tries to import a python module""" mod, loaded_from = get_module(obj, settings_module, silent) if mod and loaded_from: obj.logger.debug("py_loader: {}".format(mod)) else: obj.logger.debug( "py_loader...
java
public static int getDayOfWeek(@NotNull final Date date) { int result = getWithMondayFirst(date, Calendar.DAY_OF_WEEK); return result == 1 ? 7 : result - 1; }
python
def cat(self): """ Return the ``<c:cat>`` element XML for this series, as an oxml element. """ categories = self._series.categories if categories.are_numeric: return parse_xml( self._numRef_cat_tmpl.format(**{ 'wksht_ref': ...
java
public boolean removePolicy(String sec, String ptype, List<String> rule) { for (int i = 0; i < model.get(sec).get(ptype).policy.size(); i ++) { List<String> r = model.get(sec).get(ptype).policy.get(i); if (Util.arrayEquals(rule, r)) { model.get(sec).get(ptype).policy.remo...
java
public int getChildCount() { if(!m_bHasLoaded) { NodeData data = (NodeData)this.getUserObject(); if ((data == null) || (!data.isLeaf())) this.loadChildren(); } return super.getChildCount(); }
java
public static Class<?> getInterestedEventType(Object subscriber, Method subMethod) { Class<?> interestedEventType = (DynamicSubscriber.class.isAssignableFrom(subscriber.getClass())) ? ((DynamicSubscriber) subscriber).getEventType() : subMethod.getParameterType...
java
public void endElement(String uri, String localName, String qName) throws SAXException { m_resultContentHandler.endElement(uri, localName, qName); }
java
public static void compressTGZ(Resource[] sources, Resource target, int mode) throws IOException { File tmpTarget = File.createTempFile("_temp", "tmp"); try { // write Tar OutputStream tmpOs = new FileOutputStream(tmpTarget); try { compressTar(sources, tmpOs, mode); } finally { IOUtil.clo...
python
def _brightness(x, change:uniform): "Apply `change` in brightness of image `x`." return x.add_(scipy.special.logit(change))
python
def sample_histograms(fig, input_sample, problem, param_dict): '''Plots a set of subplots of histograms of the input sample ''' num_vars = problem['num_vars'] names = problem['names'] framing = 101 + (num_vars * 10) # Find number of levels num_levels = len(set(input_sample[:, 1])) ou...
python
def RunAnalysis(dataset, pheno_covar): """Run the actual analysis on all valid loci for each phenotype :param dataset: GWAS parser object :param pheno_covar: holds all of the variables This acts as a standard iterator, returning a single MVResult for each locus/phenotype combination. Missing ...
java
@Deprecated public static synchronized void initializeFromResource( final ClassLoader classLoader, final String name) { try { regionMetadata = loadMetadataFromResource(classLoader, name); } catch (IOException exception) { throw new SdkClientException(...
java
public Page<Table> listTablesFromId(String projectId, String datasetName) { // [START bigquery_list_tables] DatasetId datasetId = DatasetId.of(projectId, datasetName); Page<Table> tables = bigquery.listTables(datasetId, TableListOption.pageSize(100)); for (Table table : tables.iterateAll()) { // d...
python
def netmiko_file_transfer( task: Task, source_file: str, dest_file: str, **kwargs: Any ) -> Result: """ Execute Netmiko file_transfer method Arguments: source_file: Source file. dest_file: Destination file. kwargs: Additional arguments to pass to file_transfer Returns: ...
java
private E getEntity(Object entity) { return (E) (entity.getClass().isAssignableFrom(EnhanceEntity.class) ? ((EnhanceEntity) entity).getEntity() : entity); }
python
def calculate_matrices(states, Omega=1): r"""Calculate the matrices omega_ij, gamma_ij, r_pij. This function calculates the matrices omega_ij, gamma_ij and r_pij given a list of atomic states. The states can be arbitrarily in their fine, hyperfine or magnetic detail. """ # We check that all sta...
java
public static void readRAMFiles(DataInput in, RAMDirectory dir) throws IOException { int numFiles = in.readInt(); for (int i = 0; i < numFiles; i++) { String name = Text.readString(in); long length = in.readLong(); if (length > 0) { // can we avoid the extra copy? ...
java
public T addFile(String file) { checkNotNull(file, "file"); builder.files.add(file); return self(); }
java
B append(BasePath<B> path) { ImmutableList.Builder<String> components = ImmutableList.builder(); components.addAll(this.getSegments()); components.addAll(path.getSegments()); return createPathWithSegments(components.build()); }
python
def insertSaneDefaults(self): """ Add sane defaults rules to the raw and filter tables """ self.raw.insert(0, '-A OUTPUT -o lo -j NOTRACK') self.raw.insert(1, '-A PREROUTING -i lo -j NOTRACK') self.filters.insert(0, '-A INPUT -i lo -j ACCEPT') self.filters.insert(1, '-A OUTPUT -o lo -j ACCEPT') self.filters...
java
@Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { checkClosed(); throw SQLError.noSupport(); }
python
def operator_si(u): """operator_si operator.""" global _aux if np.ndim(u) == 2: P = _P2 elif np.ndim(u) == 3: P = _P3 else: raise ValueError("u has an invalid number of dimensions " "(should be 2 or 3)") if u.shape != _aux.shape[1:]: ...
python
def put_settings(self, app=None, index=None, settings=None, es=None): """Modify index settings. Index must exist already. """ if not index: index = self.index if not app: app = self.app if not es: es = self.es if not setting...
python
def _string_to_ast(self, input_string): """ Parse a smart search string and return it in an AST like form """ # simple words # we need to use a regex to match on words because the regular # Word(alphanums) will only match on American ASCII alphanums and since # we try to...
java
@Override public DescribeLagsResult describeLags(DescribeLagsRequest request) { request = beforeClientExecution(request); return executeDescribeLags(request); }
python
def output_spectrum(self, spectrum, filepath, header={}): """ Prints a file of the given spectrum to an ascii file with specified filepath. Parameters ---------- spectrum: int, sequence The id from the SPECTRA table or a [w,f,e] sequence filepath: str ...
java
protected void writeQuerySizeEntry(StringBuilder sb, ExecutionInfo execInfo, List<QueryInfo> queryInfoList) { sb.append("\"querySize\":"); sb.append(queryInfoList.size()); sb.append(", "); }
java
private Iterator<Map.Entry<DeltaClusteringKey, Change>> decodeChangesFromCql(final Iterator<Row> iter) { return Iterators.transform(iter, row -> Maps.immutableEntry(new DeltaClusteringKey(getChangeId(row), _daoUtils.getNumDeltaBlocks(getValue(row))), _changeEncoder.decodeChange(getChangeId(row),...
python
def area_pipe_min(self): """The minimum cross-sectional area of the LFOM pipe that assures a safety factor.""" return (self.safety_factor * self.q / self.vel_critical).to(u.cm**2)
java
public Observable<ServiceResponse<UUID>> addWithServiceResponseAsync(ApplicationCreateObject applicationCreateObject) { if (this.client.endpoint() == null) { throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null."); } if (applicationCreat...
java
static boolean isBivariantType(JSType type) { ObjectType objType = type.toObjectType(); return objType != null // && objType.isNativeObjectType() && BIVARIANT_TYPES.contains(objType.getReferenceName()); }
java
public JobExecutionResult executePlan(Plan plan) throws Exception { if (plan == null) { throw new IllegalArgumentException("The plan may not be null."); } ContextChecker checker = new ContextChecker(); checker.check(plan); synchronized (this.lock) { // check if we start a session dedicated for...
python
def xindexes(slots): """ Generate list of possible indexes into a list of slots. Best way to think of this is as a number where each digit might have a different radix. E.g.: (10, 10, 10) would return 10 x 10 x 10 = 1000 responses from (0, 0, 0) to (9, 9, 9), (2, 2, 2, 2) would return 2...
python
def post_map(self, url, map, auth_map=None): """Gera um XML a partir dos dados do dicionário e o envia através de uma requisição POST. :param url: URL para enviar a requisição HTTP. :param map: Dicionário com os dados do corpo da requisição HTTP. :param auth_map: Dicionário com as infor...
python
def set_headline(self, level, message, timestamp=None, now_reference=None): """Set the persistent headline message for this service. Args: level (int): The level of the message (info, warning, error) message (string): The message contents timestamp (float): An option...
java
public final void mOPTION() throws RecognitionException { try { int _type = OPTION; int _channel = DEFAULT_TOKEN_CHANNEL; // com/dyuproject/protostuff/parser/ProtoLexer.g:107:5: ( 'option' ) // com/dyuproject/protostuff/parser/ProtoLexer.g:107:9: 'option' ...
python
def output(self): """ Output the results to either STDOUT or :return: """ if not self.path_output: self.output_to_fd(sys.stdout) else: with open(self.path_output, "w") as out: self.output_to_fd(out)
java
public static boolean loadDriver(String driverClassName) { try { Class.forName(driverClassName).newInstance(); return true; } catch (ClassNotFoundException e) { return false; } catch (IllegalAccessException e) { // Constructor is private, OK for ...
python
def start(self): """ The main method that starts the service. This is blocking. """ self._initial_setup() self.on_service_start() self.app = self.make_tornado_app() enable_pretty_logging() self.app.listen(self.port, address=self.host) self._star...
java
public static Encoding getDatabaseEncoding(String databaseEncoding) { if ("UTF8".equals(databaseEncoding)) { return UTF8_ENCODING; } // If the backend encoding is known and there is a suitable // encoding in the JVM we use that. Otherwise we fall back // to the default encoding of the JVM. ...
java
@Override public String getMessage() { StringBuilder msg = new StringBuilder("\n"); msg.append(super.getMessage()); if (detail != null) { msg.append("\n"); msg.append(detail.getMessage()); if (detail.getCause() != null) { msg.append(detail.getCause().getMessage()); } ...
java
protected Method resolveMethod (String name, Object[] arguments) { Class<?>[] ptypes = new Class<?>[arguments.length]; for (int ii = 0; ii < arguments.length; ii++) { ptypes[ii] = arguments[ii] == null ? null : arguments[ii].getClass(); } try { ...
python
def write_source(self, source): """ Writes out data for a single source. """ if not self._header_written: observations = [reading.get_observation() for reading in source.get_readings()] self.write_headers(observations, self.sys_header) self._write_source(...
python
def pin_verify(self, path, *paths, **kwargs): """Verify that recursive pins are complete. Scan the repo for pinned object graphs and check their integrity. Issues will be reported back with a helpful human-readable error message to aid in error recovery. This is useful to help recover ...
java
public int getGroup(Node n, List<Collection<Node>> grps) { int i = 0; for (Collection<Node> pGrp : grps) { if (pGrp.contains(n)) { return i; } i++; } return -1; }
java
private String buildInternalForm() { StringBuffer result = new StringBuffer(128); CmsResource resource = null; boolean internal = false; // try to read the internal flag from the resource try { resource = getCms().readResource(getParamResource(), CmsResourceFilter....
java
public static String getSkinName(final String skinDirName) { try { final Properties ret = new Properties(); final File file = getWebFile("/skins/" + skinDirName + "/skin.properties"); ret.load(new FileInputStream(file)); return ret.getProperty("name"); } ...
java
public com.google.protobuf.ByteString getVmIdBytes() { java.lang.Object ref = vmId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); vmId_ = b; return b; } else { ...
python
def format_sensor(self, sensor): """ Format a sensor value. If pango is enabled color is per sensor. """ current_val = sensor.current if self.pango_enabled: percentage = self.percentage(sensor.current, sensor.critical) if self.dynamic_color: color = self.c...
python
def connectdown(np, p, acc, outlet, wtsd=None, workingdir=None, mpiexedir=None, exedir=None, log_file=None, runtime_file=None, hostfile=None): """Reads an ad8 contributing area file, identifies the location of the largest ad8 value as the outlet of the largest watershed""" # ...
python
def format_auth_params(params): """Generate the format expected by HTTP Headers from parameters. Args: params (dict): {key: value} to convert to key=value Returns: A formatted header string. """ parts = [] for (key, value) in params.items(): ...
java
@Override public InputStream openResourceStream(String className, String resourceName) throws ClassSource_Exception { String methodName = "openResourceStream"; if (!isProviderResource(resourceName)) { if (tc.isDebugEnabled()) { Tr.debug(tc, MessageFor...
python
def set_thumbnail(self, thumbnail): """ Sets the thumbnail for this OAuth Client. If thumbnail is bytes, uploads it as a png. Otherwise, assumes thumbnail is a path to the thumbnail and reads it in as bytes before uploading. """ headers = { "Authorization": ...
java
private void generateTemplateMetadata() { SanitizedContentKind contentKind = templateNode.getContentKind(); String kind = contentKind == null ? "" : contentKind.name(); // using linked hash sets below for determinism Set<String> uniqueIjs = new LinkedHashSet<>(); for (VarRefNode var : getAllNodesOf...
python
def formfield(self, form_class=None, choices_form_class=None, **kwargs): """Make the default formfield a CommaSeparatedListField.""" defaults = { 'form_class': form_class or self.get_form_class() } defaults.update(kwargs) return super(ListField, self).formfield(**def...
python
def export_to_txt( table, filename_or_fobj=None, encoding=None, frame_style="ASCII", safe_none_frame=True, *args, **kwargs ): """Export a `rows.Table` to text. This function can return the result as a string or save into a file (via filename or file-like object). `encoding`...
python
def parse_device_list(device_list_str, key): """Parses a byte string representing a list of devices. The string is generated by calling either adb or fastboot. The tokens in each string is tab-separated. Args: device_list_str: Output of adb or fastboot. key: The token that signifies a ...
java
public boolean isJava7SwitchExpression(final XSwitchExpression it) { boolean _xblockexpression = false; { final LightweightTypeReference switchType = this.getSwitchVariableType(it); if ((switchType == null)) { return false; } boolean _isSubtypeOf = switchType.isSubtypeOf(Integer....
python
def file_list(load): ''' Return a list of all files in a specified environment ''' ret = set() try: for container in __opts__['azurefs']: if container.get('saltenv', 'base') != load['saltenv']: continue container_list = _get_container_path(container) +...
python
def gen_psi(self, x): """Generates the activity of the basis functions for a given canonical system rollout. x float, array: the canonical system state or path """ if isinstance(x, np.ndarray): x = x[:,None] return np.exp(-self.h * (x - self.c)*...
python
def add_callback(self, user_gpio, edge=RISING_EDGE, func=None): """ Calls a user supplied function (a callback) whenever the specified gpio edge is detected. user_gpio:= 0-31. edge:= EITHER_EDGE, RISING_EDGE (default), or FALLING_EDGE. func:= user supplied callback...
python
def dissoc(m, *args, **kw): ''' dissoc(m, k1, k2...) yields a map equivalent to m without the arguments k1, k2, etc. If m is a mutable pythin dictionary, this is equivalent to using del m[k] for k in [k1, k2...] then returning m itself. If m is a persistent map, this is equivalent to calling m = m.d...
python
def _getDirection(coord1, coord2): """ Return the direction the line formed by the (x, y) points in `coord1` and `coord2`. """ x1, y1 = coord1 x2, y2 = coord2 if x1 == x2 and y1 == y2: return None # two coordinates are the same. elif x1 == x2 and y1 > y2: return UP e...
java
@Override public EClass getIfcDamper() { if (ifcDamperEClass == null) { ifcDamperEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(169); } return ifcDamperEClass; }
python
def render_pep440_branch_based(pieces): """Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.BRANCH_gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.BRANCH_gHEX.dirty Exceptions: 1: no tags. git_describe was just H...
python
def expr2dimacscnf(ex): """Convert an expression into an equivalent DIMACS CNF.""" litmap, nvars, clauses = ex.encode_cnf() return litmap, DimacsCNF(nvars, clauses)
java
public static Map<String, Object> getYamlObjectValue(Map<String, Object> yamlObject, String key, boolean allowsEmpty) throws YamlConvertException { Object obj = getObjectValue(yamlObject, key, allowsEmpty); @SuppressWarnings("unchecked") Map<String, Object> result = (Map<String, Obje...
python
def _jgezerou32(ins): """ Jumps if top of the stack (23bit) is >= 0 to arg(1) Always TRUE for unsigned """ output = [] value = ins.quad[1] if not is_int(value): output = _32bit_oper(value) output.append('jp %s' % str(ins.quad[2])) return output
python
def get_param_bounds_from_config(cp, section, tag, param): """Gets bounds for the given parameter from a section in a config file. Minimum and maximum values for bounds are specified by adding `min-{param}` and `max-{param}` options, where `{param}` is the name of the parameter. The types of boundary (...
python
def to_dataframe(self): """Export grid data to dataframes for statistical analysis. The export to dataframe is similar to db tables exported by `export_mv_grid_new`. Returns ------- :pandas:`pandas.DataFrame<dataframe>` Pandas Data Frame See Als...
java
static public boolean containsOnlyDigits(String string0) { // are they all digits? for (int i = 0; i < string0.length(); i++) { if (!Character.isDigit(string0.charAt(i))) { return false; } } return true; }
java
private void printAvpsAux(AvpSet avpSet, int level) throws AvpDataException { String prefix = " ".substring(0, level * 2); for (Avp avp : avpSet) { AvpRepresentation avpRep = AvpDictionary.INSTANCE.getAvp(avp.getCode(), avp.getVendorId()); if (avpRep != null && avpRep.ge...
java
@Override public IBond getBond(int idx) { if (idx < 0 || idx >= bondCount) throw new IndexOutOfBoundsException("Bond index out of bounds: 0 <= " + idx + " < " + bondCount); return bonds[idx]; }
java
public void marshall(ListProtectionsRequest listProtectionsRequest, ProtocolMarshaller protocolMarshaller) { if (listProtectionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listProtectio...
python
def standard(target, mol_weight='pore.molecular_weight', density='pore.density'): r""" Calculates the molar density from the molecular weight and mass density Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This con...
python
def tplot_names(): """ This function will print out and return a list of all current Tplot Variables stored in the memory. Parameters: None Returns: list : list of str A list of all Tplot Variables stored in the memory Examples: >>> i...
java
public final void mSTRING_LITERAL() throws RecognitionException { try { int _type = STRING_LITERAL; int _channel = DEFAULT_TOKEN_CHANNEL; // com/dyuproject/protostuff/parser/ProtoLexer.g:272:5: ( '\"' ( ESC_SEQ | ~ ( '\\\\' | '\"' ) )* '\"' ) // com/dyuproject/pro...
python
def encrypt_ctr(self, data, counter): """ Return an iterator that encrypts `data` using the Counter (CTR) mode of operation. CTR mode can operate on `data` of any length. Each iteration, except the last, always returns a block-sized :obj:`bytes` object (i.e. 8 bytes). The last iteratio...
python
def count_reads(self, file_name, paired_end): """ Count reads in a file. Paired-end reads count as 2 in this function. For paired-end reads, this function assumes that the reads are split into 2 files, so it divides line count by 2 instead of 4. This will thus give an in...
python
def get_field_label(self, trans, field): """ Get the field label from the _meta api of the model :param trans: :param field: :return: """ try: # get from the instance object_field_label = trans._meta.get_field_by_name(field)[0].verbose_nam...
java
@Override protected void afterExecute(final Runnable r, final Throwable t) { super.afterExecute(r, t); synchronized (this.pending) { this.pending.remove(r); } Throwable rootCause = null; if (t == null && r instanceof Future<?>) { try { ...
java
@ObjectiveCName("onConversationOpenWithPeer:") public void onConversationOpen(@NotNull Peer peer) { modules.getEvents().post(new PeerChatOpened(peer)); }
java
private boolean connectionOf(String pre, String now, long currentComponent) { List<Long> prel = new LinkedList<Long>(), nowl = new LinkedList<Long>(); if (!pre.equals(now) && referentOfToken.get(pre) != null && referentOfToken.get(now) != null) { for (long l : referentOfToken.get(pre).keySet()) ...
python
def _fit_radec(self): """ call fit_radec of BK passing in the observations. """ # call fitradec with mpcfile, abgfile, resfile self.orbfit.fitradec.restype = ctypes.c_int self.orbfit.fitradec.argtypes = [ ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p ] mpc_...
java
protected void registerUnregisterJMX(boolean doRegister) { if (this.mbs == null ){ // this way makes it easier for mocking. this.mbs = ManagementFactory.getPlatformMBeanServer(); } try { String suffix = ""; if (this.config.getPoolName()!=null){ suffix="-"+this.config.getPoolName(); } ...
java
public EqualsBuilder append(Object lhs, Object rhs) { if (!isEquals) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } Class<?> lhsClass = lhs.g...
python
def replace_emphasis(self, s, index = 0): """replace the index'th emphasized text with s""" e = self.emphasized[index] self.body[e[0]:e[1]] = [s] del self.emphasized[index]
python
def _normalize_path(self, path): """ Takes a path and returns a simple absolute path as a list of directories from the root """ if type(path) is str: path = path.encode() path = path.split(b'\0')[0] if path[0:1] != self.pathsep: path = self.cwd + ...
python
def remove_tag(self, name, user, message=None, date=None): """ Removes tag with the given ``name``. :param name: name of the tag to be removed :param user: full username, i.e.: "Joe Doe <joe.doe@example.com>" :param message: message of the tag's removal commit :param dat...
python
def ConsultarUltimoRemitoEmitido(self, tipo_comprobante=995, punto_emision=1): "Obtener el último número de remito que se emitió por tipo de comprobante y punto de emisión" response = self.client.consultarUltimoRemitoEmitido( authRequest={'token': self.Token, 'sign': self...
java
public PagedList<SiteInner> beginSuspendNext(final String nextPageLink) { ServiceResponse<Page<SiteInner>> response = beginSuspendNextSinglePageAsync(nextPageLink).toBlocking().single(); return new PagedList<SiteInner>(response.body()) { @Override public Page<SiteInner> nextPage(...
java
private int getLayoutID(final int userId, final int profileId) { return jdbcOperations.execute( (ConnectionCallback<Integer>) con -> { String query = "SELECT LAYOUT_ID " ...
java
private boolean evalClass(QueryImpl query, QueryAtomGroupImpl group, QueryResultImpl result, QueryBindingImpl binding, QueryAtom atom) throws QueryEngineException { QueryArgument clsArg = atom.getArguments().get(0); ...
java
public boolean containsKey(Object key) { if(key == null) throw new NullPointerException("Binding to a resource bundle does not accept a null key"); BundleNodeMap map = lookupScriptableBundle(key.toString()); return map != null; }
java
@Override public ProjectFile read(InputStream inputStream) throws MPXJException { try { m_reader = new AstaReader(); ProjectFile project = m_reader.getProject(); project.getEventManager().addProjectListeners(m_projectListeners); m_tables = new HashMap<String, List<Row...
java
@Override public String getCssText() { final StringBuilder sb = new StringBuilder(); sb.append("@import"); final String href = getHref(); if (null != href) { sb.append(" url(").append(href).append(")"); } final MediaListImpl ml = getMedia(); if (...
python
def search(self): '''Override search to match on topic tags''' s = super(TopicSearchMixin, self).search() s = s.filter('bool', should=[ Q('term', tags=tag) for tag in self.topic.tags ]) return s