language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def setup(self): """Setup filter (only called when filter is actually used).""" super(RequireJSFilter, self).setup() excluded_files = [] for bundle in self.excluded_bundles: excluded_files.extend( map(lambda f: os.path.splitext(f)[0], bund...
java
public void moveKBase(String oldQName, String newQName) { Map<String, KieBaseModel> newMap = new HashMap<String, KieBaseModel>(); newMap.putAll( this.kBases ); KieBaseModel kieBaseModel = newMap.remove( oldQName ); newMap.put( newQName, kieBaseModel); setKBases( newMap ); }
python
def get_row_missing(xc, xd, cdiffs, index, cindices, dindices): """ Calculate distance between index instance and all other instances. """ row = np.empty(0, dtype=np.double) # initialize empty row cinst1 = xc[index] # continuous-valued features for index instance dinst1 = xd[index] # discrete-val...
java
protected void closeSocketAndStreams() { LOG.trace("enter HttpConnection.closeSockedAndStreams()"); isOpen = false; // no longer care about previous responses... lastResponseInputStream = null; if (null != outputStream) { OutputStream temp = outputStream; ...
java
public EEnum getMODCAInterchangeSetIStype() { if (modcaInterchangeSetIStypeEEnum == null) { modcaInterchangeSetIStypeEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(97); } return modcaInterchangeSetIStypeEEnum; }
python
def rnaQuantificationsGenerator(self, request): """ Returns a generator over the (rnaQuantification, nextPageToken) pairs defined by the specified request. """ if len(request.rna_quantification_set_id) < 1: raise exceptions.BadRequestException( "Rna Qu...
python
def run_analysis(self, argv): """Run this analysis""" args = self._parser.parse_args(argv) exttype = splitext(args.infile)[-1] if exttype in ['.fits', '.npy']: castro_data = CastroData.create_from_sedfile(args.infile) elif exttype in ['.yaml']: castro_dat...
java
public List<TimephasedCost> getTimephasedBaselineCost(int index) { return m_timephasedBaselineCost[index] == null ? null : m_timephasedBaselineCost[index].getData(); }
java
public static byte[] toArray(Collection<? extends Number> bytes) { byte[] array = new byte[bytes.size()]; Iterator<? extends Number> iter = bytes.iterator(); for (int i = 0; i < bytes.size(); i++) { array[i] = iter.next().byteValue(); } return array; }
python
def libvlc_video_set_callbacks(mp, lock, unlock, display, opaque): '''Set callbacks and private data to render decoded video to a custom area in memory. Use L{libvlc_video_set_format}() or L{libvlc_video_set_format_callbacks}() to configure the decoded format. @param mp: the media player. @param...
java
public static Collection map(Mapper mapper, Iterator i, boolean includeNull) { ArrayList l = new ArrayList(); while (i.hasNext()) { Object o = mapper.map(i.next()); if (includeNull || o != null) { l.add(o); } } return l; }
java
public Result transfer(long count) { if (count < 0L) throw new IllegalArgumentException("negative count"); return buffer == null ? transferNoBuffer(count) : transferBuffered(count); }
java
public void setRows(java.util.Collection<Row> rows) { if (rows == null) { this.rows = null; return; } this.rows = new java.util.ArrayList<Row>(rows); }
python
def crude_age_standardization(e, b, n): """A utility function to compute rate through crude age standardization Parameters ---------- e : array (n*h, 1), event variable measured for each age group across n spatial units b : array (n*h, 1), populat...
java
@XmlElementDecl(namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", name = "includeAllowableActions", scope = Query.class) public JAXBElement<Boolean> createQueryIncludeAllowableActions(Boolean value) { return new JAXBElement<Boolean>( _GetObjectOfLatestVersionIncludeAllowableActions_QNAME, ...
java
private HashSet<Point> hitMissHashSet( BinaryFast b, HashSet<Point> input, int[] kernel ) { HashSet<Point> output = new HashSet<Point>(); Iterator<Point> it = input.iterator(); while( it.hasNext() ) { Point p = it.next(); if (kernelMatch(p, b.getPixels(), b.getWidth(), b....
java
public static void invalidArgIf(boolean tester, String msg, Object... args) { if (tester) { throw invalidArg(msg, args); } }
python
def cdf_single(z, N, normalization, dH=1, dK=3): """Cumulative distribution for the Lomb-Scargle periodogram Compute the expected cumulative distribution of the periodogram for the null hypothesis - i.e. data consisting of Gaussian noise. Parameters ---------- z : array-like the period...
java
public void initializeExtensions() throws SQLException { if (extensionsNeedInitialization) { for (EmbeddedDbExtension ext : MdwServiceRegistry.getInstance().getEmbeddedDbExtensions()) { logger.info("Initializing embedded db extension: " + ext); List<String> sources = ...
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "TriangulatedSurface", substitutionHeadNamespace = "http://www.opengis.net/gml", substitutionHeadName = "Surface") public JAXBElement<TriangulatedSurfaceType> createTriangulatedSurface(TriangulatedSurfaceType value) { return new JAXBElement<Tr...
python
def get_activity_zones(self, activity_id): """ Gets zones for activity. Requires premium account. http://strava.github.io/api/v3/activities/#zones :param activity_id: The activity for which to zones. :type activity_id: int :return: An list of :class:`stravalib...
python
def set_sdk_enabled(cls, value): """ Modifies the enabled flag if the "AWS_XRAY_SDK_ENABLED" environment variable is not set, otherwise, set the enabled flag to be equal to the environment variable. If the env variable is an invalid string boolean, it will default to true. :para...
java
@Override public <DATA> InFileObjectPersister<DATA> createInFileObjectPersister(Class<DATA> clazz, File cacheFolder) throws CacheCreationException { return new JacksonObjectPersister<DATA>(getApplication(), clazz, cacheFolder); }
python
def delete_service(name, restart=True): ''' Delete an existing service CLI Example: .. code-block:: bash salt '*' firewalld.delete_service my_service By default firewalld will be reloaded. However, to avoid reloading you need to specify the restart as False .. code-block:: bash ...
java
protected void checkAutoscroll (MouseEvent exitEvent) { Component comp = exitEvent.getComponent(); Point p = exitEvent.getPoint(); try { Point scr = comp.getLocationOnScreen(); p.translate(scr.x, scr.y); } catch (IllegalComponentStateException icse) { ...
java
public final void mELEMENTS() throws RecognitionException { try { int _type = ELEMENTS; int _channel = DEFAULT_TOKEN_CHANNEL; // hql.g:21:10: ( 'elements' ) // hql.g:21:12: 'elements' { match("elements"); if (state.failed) return; } state.type = _type; state.channel = _channel; } fina...
python
def from_bytes(cls, bitstream): ''' Parse the given packet and update properties accordingly ''' packet = cls() # Convert to ConstBitStream (if not already provided) if not isinstance(bitstream, ConstBitStream): if isinstance(bitstream, Bits): ...
java
public void truncateAllWithPrefix(@Nonnull String prefix) { for (String queueName : queues.keySet()) { if (queueName.startsWith(prefix)) { truncate(queueName); } } }
python
def get(cls, domain, name): """ Get the requested site entry @param domain: Domain name @type domain: Domain @param name: Site name @type name: str @rtype: Domain """ Site = cls return Session.query(Site).filter(Site.domain == dom...
python
def oftype(self, typ): '''Return a generator of formatters codes of type typ''' for key, val in self.items(): if val.type == typ: yield key
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case XtextPackage.TYPE_REF__METAMODEL: return metamodel != null; case XtextPackage.TYPE_REF__CLASSIFIER: return classifier != null; } return super.eIsSet(featureID); }
java
private boolean isCharVisible(int x, int y, StringWalker walker, ClipArea area) { if (area == null || area.noClip()) return true; if (area.fullClip()) return false; return area.isInside(x, y) || area.isInside(x + (int) Math.ceil(walker.width()), y + (int) Math.ceil(walker.height())); }
python
def num2varint(num): """ Converts a number to a variable length Int. Used for array length header :param: {number} num - The number :return: {string} hexstring of the variable Int. """ # if (typeof num !== 'number') throw new Error('VarInt must be numeric') # if (num < 0) throw new RangeErr...
java
@Override public Class<?> getType(ELContext context, Object base, Object property) { context.setPropertyResolved(false); for (ELResolver resolver : resolvers) { Class<?> type = resolver.getType(context, base, property); if (context.isPropertyResolved()) { return type; } } return null; }
java
public void selfUnregister() { LocalUnitsManager.unitMap(unitMap -> { unitMap.forEach((groupName, unitListIgnored) -> { try { ServiceInstance<GroupProxy> serviceInstance = ZkServiceInstanceAdaptor.thisCuratorServiceInstance(groupName); serviceD...
python
def parallel(args): """ %prog parallel genome.fasta N Partition the genome into parts and run separately. This is useful if MAKER is to be run on the grid. """ from jcvi.formats.base import split p = OptionParser(parallel.__doc__) p.set_home("maker") p.set_tmpdir(tmpdir="tmp") ...
java
public void setRGLength(Integer newRGLength) { Integer oldRGLength = rgLength; rgLength = newRGLength; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.MCF1__RG_LENGTH, oldRGLength, rgLength)); }
java
public String merge (String newlyGenerated, String previouslyGenerated) throws Exception { // Extract the generated section names from the output and make sure they're all matched Map<String, Section> sections = Maps.newLinkedHashMap(); Matcher m = _sectionDelimiter.matcher(newlyGene...
python
def _get_files_modified(): """Get the list of modified files that are Python or Jinja2.""" cmd = "git diff-index --cached --name-only --diff-filter=ACMRTUXB HEAD" _, files_modified, _ = run(cmd) extensions = [re.escape(ext) for ext in list(SUPPORTED_FILES) + [".rst"]] test = "(?:{0})$".format("|".j...
java
public static org.restcomm.connect.provisioning.number.api.PhoneNumber convertIncomingPhoneNumbertoPhoneNumber(IncomingPhoneNumber incomingPhoneNumber) { return new org.restcomm.connect.provisioning.number.api.PhoneNumber( incomingPhoneNumber.getFriendlyName(), incomingPhoneNumbe...
python
def merge_likelihood_headers(filenames, outfile): """ Merge header information from likelihood files. Parameters: ----------- filenames : input filenames oufile : the merged file to write Returns: -------- data : the data being written """ filenames = np.atleas...
java
@Read() public Patient read(@IdParam IdDt theId) { Patient retVal = myPatients.get(theId.getIdPartAsLong()); if (retVal == null) { throw new ResourceNotFoundException(theId); } return retVal; }
java
public <S, T> ToMarshaller<S,T> findMarshaller(ConverterKey<S,T> key) { return BINDING.findMarshaller(key); }
java
public Parse parse(Parse tokens) { Parse p = parse(tokens,1)[0]; setParents(p); return p; }
python
def parse_type_system_definition(lexer: Lexer) -> TypeSystemDefinitionNode: """TypeSystemDefinition""" # Many definitions begin with a description and require a lookahead. keyword_token = lexer.lookahead() if peek_description(lexer) else lexer.token func = _parse_type_system_definition_functions.get(cas...
java
@SuppressWarnings("WeakerAccess") public String getZone() { LocationName location = Verify.verifyNotNull(LocationName.parse(stateProto.getLocation())); //noinspection ConstantConditions return location.getLocation(); }
java
public static byte[] getIncreasingByteArray(int start, int len) { byte[] ret = new byte[len]; for (int k = 0; k < len; k++) { ret[k] = (byte) (k + start); } return ret; }
java
public CreateJobRequest withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
python
def in6_getnsmac(a): # return multicast Ethernet address associated with multicast v6 destination """ Return the multicast mac address associated with provided IPv6 address. Passed address must be in network format. """ a = struct.unpack('16B', a)[-4:] mac = '33:33:' mac += (':'.join(map(l...
python
def replace_group(self, index, func_grp, strategy, bond_order=1, graph_dict=None, strategy_params=None, reorder=True, extend_structure=True): """ Builds off of Molecule.substitute and MoleculeGraph.substitute_group to replace a functional group in self...
python
def concat(self, one, two): """Multiply two matrices and replace current one.""" if not len(one) == len(two) == 6: raise ValueError("bad sequ. length") self.a, self.b, self.c, self.d, self.e, self.f = TOOLS._concat_matrix(one, two) return self
java
public Set<LdapEntry> searchEntities(String name, String filter, Object[] filterArgs, int scope, List<String> inEntityTypes, List<String> propNames, boolean getMbrshipAttr, boolean getMbrAttr, int countLimit, int timeLimit) throws WIMException { String inEntityType = nul...
python
def check_notification(self, code): """ check a notification by its code """ response = self.get(url=self.config.NOTIFICATION_URL % code) return PagSeguroNotificationResponse(response.content, self.config)
python
def _get_project_types(self): """Get all available project types.""" project_types = get_available_project_types() projects = [] for project in project_types: projects.append(project.PROJECT_TYPE_NAME) return projects
java
@Override protected Object buildResource(final ParameterItem<?> parameterItem, final ParameterParams parameterParams) { Object object = null; if (parameterParams instanceof ObjectParameter) { final ObjectParameter<?> op = (ObjectParameter<?>) parameterParams; // Load...
java
private static String[] split(String value, String delimeter) { StringTokenizer st = new StringTokenizer(value, delimeter); String[] res = new String[st.countTokens()]; for (int i = 0; st.hasMoreTokens(); i++) { res[i] = st.nextToken(); } return res; }
python
def verify(self, signature): """Verifies a signature :raises InvalidJWSSignature: if the verification fails. """ try: payload = self._payload() sigin = b'.'.join([self.protected.encode('utf-8'), payload]) self.engine.verify(self.key, sigin, signature)...
python
def plot_stacked_hist(self, key="wall_time", nmax=5, ax=None, **kwargs): """ Plot stacked histogram of the different timers. Args: key: Keyword used to extract data from the timers. Only the first `nmax` sections with largest value are show. mmax: Maximum...
python
def AddFXrefWrite(self, method, classobj, field): """ Add a Field Write to this class :param method: :param classobj: :param field: :return: """ if field not in self._fields: self._fields[field] = FieldClassAnalysis(field) self._fields...
python
def to_dict(self, model_run): """Create a Json-like dictionary for a model run object. Extends the basic object with run state, arguments, and optional prediction results or error descriptions. Parameters ---------- model_run : PredictionHandle Returns -...
java
public static void histogram( GrayS16 input , int minValue , int histogram[] ) { if( BoofConcurrency.USE_CONCURRENT ) { ImplImageStatistics_MT.histogram(input,minValue,histogram); } else { ImplImageStatistics.histogram(input,minValue,histogram); } }
python
def from_file(cls, fp, is_outlook=False): """ Init a new object from a file path. Args: fp (string): file path of raw email is_outlook (boolean): if True is an Outlook email Returns: Instance of MailParser """ log.debug("Parsing email...
python
def spawn_actors(self, monitor): '''Spawn new actors if needed. ''' to_spawn = monitor.cfg.workers - len(self.managed_actors) if monitor.cfg.workers and to_spawn > 0: for _ in range(to_spawn): monitor.spawn()
python
def resolve_attr(obj, name): """A custom attrgetter that operates both on dictionaries and objects""" # TODO: setup some hinting, so we can go directly to the correct # Maybe it's a dict ? Let's try dict lookup, it's the fastest try: return obj[name] except TypeError: pass except...
java
@RestrictTo(LIBRARY) public void notifyUseCaseStart(UseCaseListener listener) { try { LOGGER.debug("Notifying " + getClass().getSimpleName() + " start to listener " + listener.getClass().getSimpleName()); listener.onStartUseCase(); } catch (Exception e) { AbstractException abstractException = wrapExceptio...
python
def create(self, environments): """ Method to create environments vip :param environments vip: Dict containing environments vip desired to be created on database :return: None """ data = {'environments_vip': environments} uri = '...
python
def code(self): """Returns the code object for this BUILD file.""" return compile(self.source(), self.full_path, 'exec', flags=0, dont_inherit=True)
java
@Override public MergeDeveloperIdentitiesResult mergeDeveloperIdentities(MergeDeveloperIdentitiesRequest request) { request = beforeClientExecution(request); return executeMergeDeveloperIdentities(request); }
java
public long skip(long len) { if (position + len > limit) len = limit - position; if (len <= 0) return 0; position += len; return len; }
java
@Bean @ConditionalOnMissingBean @ConditionalOnClass(name = "org.springframework.web.reactive.function.client.WebClient") public ReactiveCredHubOperations reactiveCredHubTemplate( CredHubProperties credHubProperties, ClientOptions clientOptions, @Autowired(required = false) ReactiveClientRegistrationRepository ...
java
@Override public void sawOpcode(int seen) { FinallyBlockInfo fbi = fbInfo.get(0); if (getPC() < fbi.startPC) { return; } if (getPC() == fbi.startPC) { if (OpcodeUtils.isAStore(seen)) { fbi.exReg = RegisterUtils.getAStoreReg(this, seen); ...
python
def getConId(self, contract_identifier): """ Get contracts conId """ details = self.contractDetails(contract_identifier) if len(details["contracts"]) > 1: return details["m_underConId"] return details["m_summary"]["m_conId"]
java
public int getWidth () { // Return the maximal width of our component mirages. int width = 0; for (Mirage m : _mirages) { width = Math.max(width, m.getWidth()); } return width; }
python
def print_dedicated_access(access): """Prints out the dedicated hosts a user can access""" table = formatting.Table(['id', 'Name', 'Cpus', 'Memory', 'Disk', 'Created'], 'Dedicated Access') for host in access: host_id = host.get('id') host_fqdn = host.get('name') host_cpu = host.get(...
python
def api_url(self): '''return the api url of self''' return pathjoin(Bin.path, self.name, url=self.service.url)
python
def get_balance(): """ Get the latest balance(s) for a single User. Currently no search parameters are supported. All balances returned. --- responses: '200': description: the User's balance(s) schema: items: $ref: '#/definitions/Balance' type: a...
java
private void colorChooser2ndTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_colorChooser2ndTextActionPerformed if (this.colorChooser2ndText.isLastOkPressed() && changeNotificationAllowed) { this.controller.changed(); } }
java
private static boolean disableNestedLoopIndexJoinForInComparison (AbstractPlanNode root, AbstractParsedStmt parsedStmt) { if (root.getPlanNodeType() == PlanNodeType.NESTLOOPINDEX) { assert(parsedStmt != null); return true; } return false; }
python
def log_connection_info(self): """ Overridden to customize the start-up message printed to the terminal """ _ctrl_c_lines = [ 'NOTE: Ctrl-C does not work to exit from the command line.', 'To exit, just close the window, type "exit" or "quit" at the ' '...
python
def get_default_connection(): """Returns the default datastore connection. Defaults endpoint to helper.get_project_endpoint_from_env() and credentials to helper.get_credentials_from_env(). Use set_options to override defaults. """ tid = id(threading.current_thread()) conn = _conn_holder.get(tid) if no...
python
def list_calendars(self, limit=None, *, query=None, order_by=None): """ Gets a list of calendars To use query an order_by check the OData specification here: http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/ part2-url-conventions/odata-v4.0-errata03-os-part2-url-conventi...
java
public void addProgressChangeListener(MapboxNavigation navigation) { this.navigation = navigation; navigation.setCameraEngine(new DynamicCamera(mapboxMap)); navigation.addProgressChangeListener(progressChangeListener); }
python
def set(self, item: Union[Service, PublicKey]) -> 'DIDDoc': """ Add or replace service or public key; return current DIDDoc. Raise BadDIDDocItem if input item is neither service nor public key. :param item: service or public key to set :return: current DIDDoc """ ...
python
def flattened(value, split=None): """ Args: value: Possibly nested arguments (sequence of lists, nested lists) split (int | str | unicode | (str | unicode, int) | None): How to split values: - None: simply flatten, no further processing - one char string: split() on speci...
java
protected void setXaResourceFactory(ServiceReference<ResourceFactory> ref) { if (tc.isEntryEnabled()) Tr.entry(tc, "setXaResourceFactory, ref " + ref); _xaResourceFactoryReady = true; if (ableToStartRecoveryNow()) { // Can start recovery now try { ...
java
public EpollSocketChannelConfig setSoBusyPoll(int loopMicros) { try { ((EpollSocketChannel) channel).socket.setSoBusyPoll(loopMicros); return this; } catch (IOException e) { throw new ChannelException(e); } }
java
public static PatchedBigQueryTableRowIterator fromTable(TableReference ref, Bigquery client) { checkNotNull(ref, "ref"); checkNotNull(client, "client"); return new PatchedBigQueryTableRowIterator(ref, /* queryConfig */null, ref.getProjectId(), client); }
python
def clean(): "take out the trash" src_dir = easy.options.setdefault("docs", {}).get('src_dir', None) if src_dir is None: src_dir = 'src' if easy.path('src').exists() else '.' with easy.pushd(src_dir): for pkg in set(easy.options.setup.packages) | set(("tests",)): for filenam...
java
@Override public void delete(Object entity, Object pKey) { EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass()); MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel( metadata.getPersiste...
java
public GetReservationPurchaseRecommendationResult withRecommendations(ReservationPurchaseRecommendation... recommendations) { if (this.recommendations == null) { setRecommendations(new java.util.ArrayList<ReservationPurchaseRecommendation>(recommendations.length)); } for (Reservation...
python
def reissue(csr_file, certificate_id, web_server_type, approver_email=None, http_dc_validation=False, **kwargs): ''' Reissues a purchased SSL certificate. Returns a dictionary of result values. csr_file Path to Certificate Signing Requ...
python
def add_version_iri(graph, epoch): """ Also remove the previous versionIRI if there was one.""" for ont in graph.subjects(rdf.type, owl.Ontology): for versionIRI in graph.objects(ont, owl.versionIRI): graph.remove((ont, owl.versionIRI, versionIRI)) t = ont, owl.versionIRI, make_versi...
java
public static boolean primitiveIsAssignableFrom (Class<?> lhs, Class<?> rhs) { if (lhs == null || rhs == null) { return false; } if (!(lhs.isPrimitive() && rhs.isPrimitive())) { return false; } if (lhs.equals(rhs)) { return true; } ...
java
@SuppressWarnings({ "unchecked", "rawtypes" }) public Serializable parseIdString(String id) { Class idType = getIdField().getType(); return parser.parse(id, idType); }
python
def kmeans_pp(data, k, centers=None): """ Generates kmeans++ initial centers. Args: data (array): A 2d array- genes x cells k (int): Number of clusters centers (array, optional): if provided, these are one or more known cluster centers. 2d array of genes x number of centers (<=k). ...
python
def remove_child_gradebook(self, gradebook_id, child_id): """Removes a child from a gradebook. arg: gradebook_id (osid.id.Id): the ``Id`` of a gradebook arg: child_id (osid.id.Id): the ``Id`` of the new child raise: NotFound - ``gradebook_id`` not a parent of ``child_id`` ...
java
private IDataSet performReplacements(IDataSet dataSet, List<Replacer> replacersList) { if (replacersList == null || replacersList.isEmpty()) return dataSet; ReplacementDataSet replacementSet = new ReplacementDataSet(dataSet); // convert to set to remove duplicates Set<Repla...
python
def cutadapt_length_trimmed_plot (self): """ Generate the trimming length plot """ description = 'This plot shows the number of reads with certain lengths of adapter trimmed. \n\ Obs/Exp shows the raw counts divided by the number expected due to sequencing errors. A defined peak \n\ may...
java
public Observable<VirtualNetworkGatewayInner> resetAsync(String resourceGroupName, String virtualNetworkGatewayName) { return resetWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName).map(new Func1<ServiceResponse<VirtualNetworkGatewayInner>, VirtualNetworkGatewayInner>() { @Overri...
python
def _setup_output_file(self, output_filename, args, write_header=True): """Open and prepare output file.""" # write command line into outputFile # (without environment variables, they are documented by benchexec) try: output_file = open(output_filename, 'w') # override existi...