language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def render_secrets( config_path, secret_path, ): """combine a jinja template with a secret .ini file Args: config_path (str): path to .cfg file with jinja templating secret_path (str): path to .ini-like secrets file Returns: ProsperConfig: rendered configuration obj...
java
public java.util.List<PublicIpv4PoolRange> getPoolAddressRanges() { if (poolAddressRanges == null) { poolAddressRanges = new com.amazonaws.internal.SdkInternalList<PublicIpv4PoolRange>(); } return poolAddressRanges; }
java
public void removeDeleted(String entryId) { CmsListItem item = getDeleted().getItem(entryId); if (item != null) { // remove getDeleted().removeItem(item); } if (getDeleted().getWidgetCount() == 0) { m_clipboardButton.enableClearDeleted(false); ...
python
def load_movies(data_home, size): """Load movie genres as a context. Returns: dict of movie vectors: item_id -> numpy array (n_genre,) """ all_genres = ['Action', 'Adventure', 'Animation', "Children's", 'Comedy', ...
python
def headers(headerDict={}, **headerskwargs): ''' This function is the decorator which is used to wrap a Flask route with. Either pass a dictionary of headers to be set as the headerDict keyword argument, or pass header values as keyword arguments. Or, do both :-) The key and value of ite...
java
@Contract(pure = false) public String asString(@NotNull Charset charset) { String string = getString(charset); recycle(); return string; }
python
def style(self, style): """ Set val attribute of <w:pStyle> child element to *style*, adding a new element if necessary. If *style* is |None|, remove the <w:pStyle> element if present. """ if style is None: self._remove_pStyle() return pSty...
python
def elements(self): """Return the BIC's Party Prefix, Country Code, Party Suffix and Branch Code as a tuple.""" return (self.party_prefix, self.country_code, self.party_suffix, self.branch_code)
python
def GetMissingChunks(self, fd, length, offset): """Return which chunks a file doesn't have. Specifically, we return a list of the chunks specified by a length-offset range which are not in the datastore. Args: fd: The database object to read chunks from. length: Length to read. offse...
java
protected boolean doesParentMatch(final CSNodeWrapper parent, final CSNodeWrapper entityParent) { if (parent != null && entityParent != null) { if (parent.getId() != null && parent.getId().equals(entityParent.getId())) { return true; } else if (parent.getId() == null && e...
java
private void addPostParams(final Request request) { if (name != null) { request.addPostParam("Name", name); } if (codeLength != null) { request.addPostParam("CodeLength", codeLength.toString()); } }
java
static public FileSystemManager getManager(){ StandardFileSystemManager fsManager = new StandardFileSystemManager(); try { fsManager.init(); } catch (FileSystemException e) { log.error("Cannot initialize StandardFileSystemManager.", e); } return fsManager; }
python
def _validateIterCommonParams(MaxObjectCount, OperationTimeout): """ Validate common parameters for an iter... operation. MaxObjectCount must be a positive non-zero integer or None. OperationTimeout must be positive integer or zero Raises: ValueError: if these parameters are invalid ""...
java
public void removeRelationship(ExtendedRelation extendedRelation) { try { if (extendedRelationsDao.isTableExists()) { geoPackage.deleteTable(extendedRelation.getMappingTableName()); extendedRelationsDao.delete(extendedRelation); } } catch (SQLException e) { throw new GeoPackageException("Failed to...
java
public ActionListDialogBuilder addAction(final String label, final Runnable action) { return addAction(new Runnable() { @Override public String toString() { return label; } @Override public void run() { action.run(); ...
java
public PactDslJsonArray maxArrayLike(Integer size, PactDslJsonRootValue value, int numberExamples) { if (numberExamples > size) { throw new IllegalArgumentException(String.format("Number of example %d is more than the maximum size of %d", numberExamples, size)); } matchers.addRule(rootPath + a...
python
def get_site_coordination_environments_fractions(self, site, isite=None, dequivsite=None, dthissite=None, mysym=None, ordered=True, min_fraction=0.0, return_maps=True, return_strategy_dict_info=False): """ ...
java
public ServiceFuture<ImagePrediction> predictImageWithNoStoreAsync(UUID projectId, byte[] imageData, PredictImageWithNoStoreOptionalParameter predictImageWithNoStoreOptionalParameter, final ServiceCallback<ImagePrediction> serviceCallback) { return ServiceFuture.fromResponse(predictImageWithNoStoreWithServiceRe...
python
def yank(self): """ Yank back the most recently killed text. """ text = self._ring.yank() if text: self._skip_cursor = True cursor = self._text_edit.textCursor() cursor.insertText(text) self._prev_yank = text
java
public Set<PhysicalEntity> getNonUbiques(Set<PhysicalEntity> entities, RelType ctx) { Collection<SmallMolecule> ubiques = getUbiques(entities, ctx); if (ubiques.isEmpty()) return entities; Set<PhysicalEntity> result = new HashSet<PhysicalEntity>(entities); result.removeAll(ubiques); return result; }
java
public KeyOperationResult decrypt(String vaultBaseUrl, String keyName, String keyVersion, JsonWebKeyEncryptionAlgorithm algorithm, byte[] value) { return decryptWithServiceResponseAsync(vaultBaseUrl, keyName, keyVersion, algorithm, value).toBlocking().single().body(); }
python
def logger(self) -> Logger: """A :class:`logging.Logger` logger for the app. This can be used to log messages in a format as defined in the app configuration, for example, .. code-block:: python app.logger.debug("Request method %s", request.method) app.logger.e...
java
@Override public DetectDocumentTextResult detectDocumentText(DetectDocumentTextRequest request) { request = beforeClientExecution(request); return executeDetectDocumentText(request); }
java
@Override public boolean removeTrigger(final TriggerKey triggerKey) throws JobPersistenceException { return doWithLock(new LockCallback<Boolean>() { @Override public Boolean doWithLock(JedisCommands jedis) throws JobPersistenceException { try { ret...
java
public double[] getColumn(int column) { column = getIndexFromMap(colMaskMap, column); double[] values = new double[rows()]; for (int r = 0; r < rows(); ++r) values[r] = matrix.get(getIndexFromMap(rowMaskMap, r), column); return values; }
java
public static RawData escapeRegex(Object o) { if (null == o) return RawData.NULL; if (o instanceof RawData) return (RawData) o; String s = o.toString(); return new RawData(s.replaceAll("([\\/\\*\\{\\}\\<\\>\\-\\\\\\!])", "\\\\$1")); }
python
def identify_names(filename): """Builds a codeobj summary by identifying and resolving used names.""" node, _ = parse_source_file(filename) if node is None: return {} # Get matches from the code (AST) finder = NameFinder() finder.visit(node) names = list(finder.get_mapping()) na...
java
private void updateGridListDensity() { for (Map.Entry<DensityGrid, CharacteristicVector> grid : grid_list.entrySet()) { DensityGrid dg = grid.getKey(); CharacteristicVector cvOfG = grid.getValue(); dg.setVisited(false); cvOfG.updateGridDensity(this.getCurrTime(), this.getDecayFactor(), this.getDL(), t...
python
async def await_reply(self, correlation_id, timeout=None): """Wait for a reply to a given correlation id. If a timeout is provided, it will raise a asyncio.TimeoutError. """ try: result = await asyncio.wait_for( self._futures[correlation_id], timeout=timeout)...
java
public void set(TafResp tafResp, Lur lur) { principal = tafResp.getPrincipal(); access = tafResp.getAccess(); this.lur = lur; }
python
def patch_csi_node(self, name, body, **kwargs): """ partially update the specified CSINode This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_csi_node(name, body, async_req=True) ...
python
def json_2_team(json_obj): """ transform JSON obj coming from Ariane to ariane_clip3 object :param json_obj: the JSON obj coming from Ariane :return: ariane_clip3 Team object """ LOGGER.debug("Team.json_2_team") return Team(teamid=json_obj['teamID'], ...
python
def get_uri(dir_name): """ Returns the URI path for a directory. This allows files hosted on different file servers to have distinct locations. Args: dir_name: A directory name. Returns: Full URI path, e.g., fileserver.host.com:/full/path/of/dir_name. """ fullpa...
python
def example_delete_topics(a, topics): """ delete topics """ # Call delete_topics to asynchronously delete topics, a future is returned. # By default this operation on the broker returns immediately while # topics are deleted in the background. But here we give it some time (30s) # to propagate in t...
python
def folder_name(self): '''The name of the build folders containing this recipe.''' name = self.site_packages_name if name is None: name = self.name return name
python
def load_repo_addons(_globals): '''Load all fabsetup addons which are stored under ~/.fabsetup-addon-repos as git repositories. Args: _globals(dict): the globals() namespace of the fabric script. Return: None ''' repos_dir = os.path.expanduser('~/.fabsetup-addon-repos') if os.path....
java
public static void packEntries(File[] filesToPack, File destZipFile, NameMapper mapper, int compressionLevel) { log.debug("Compressing '{}' into '{}'.", filesToPack, destZipFile); ZipOutputStream out = null; FileOutputStream fos = null; try { fos = new FileOutputStream(destZipFile); out = n...
java
public boolean deleteLedgerMetadata(EditLogLedgerMetadata ledger, int version) throws IOException { String ledgerPath = fullyQualifiedPathForLedger(ledger); try { zooKeeper.delete(ledgerPath, version); return true; } catch (KeeperException.NoNodeException e) { LOG.warn(ledgerPath + "...
python
def backup_watched(plex, opts): """ Backup watched status to the specified filepath. """ data = defaultdict(lambda: dict()) for section in _iter_sections(plex, opts): print('Fetching watched status for %s..' % section.title) skey = section.title.lower() for item in _iter_items(sectio...
java
public Coordinate snap(Coordinate coordinate, double distance) { // Some initialization: calculatedDistance = distance; hasSnapped = false; Coordinate snappingPoint = coordinate; // Calculate the distances for all coordinate arrays: for (Coordinate[] coordinateArray : coordinates) { if (coordinateArray....
java
@Override public synchronized ChainData[] getAllChains(Class<?> factoryClass) throws InvalidChannelFactoryException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "getAllChains(factory)"); } if (null == factoryClass) { throw new Inva...
python
def truncate_to(self, cert): """ Remove all certificates in the path after the cert specified :param cert: An asn1crypto.x509.Certificate object to find :raises: LookupError - when the certificate could not be found :return: The current Vali...
python
def inspect_obj(obj): '''Learn what there is to be learned from our target. Given an object at `obj`, which must be a function, method or class, return a configuration *discovered* from the name of the object and its parameter list. This function is responsible for doing runtime...
python
def getAttrWithFallback(info, attr): """ Get the value for *attr* from the *info* object. If the object does not have the attribute or the value for the atribute is None, this will either get a value from a predefined set of attributes or it will synthesize a value from the available data. "...
python
def alphanum_key(s): """Turn a string into a list of string and number chunks. "z23a" -> ["z", 23, "a"] """ return [int(c) if c.isdigit() else c for c in _RE_INT.split(s)]
java
@Indexable(type = IndexableType.REINDEX) @Override public CommerceWishList updateCommerceWishList( CommerceWishList commerceWishList) { return commerceWishListPersistence.update(commerceWishList); }
python
def display_event(div, attributes=[]): """ Function to build a suitable CustomJS to display the current event in the div model. """ style = 'float: left; clear: left; font-size: 10pt' return CustomJS(args=dict(div=div), code=""" var attrs = %s; var args = []; for (var i =...
python
def _open_fix(file): """Takes in a fits file name, open the file in binary mode and creates an HDU. Will attempt to fix some of the header keywords to match the standard FITS format. """ import pyfits, re, string temp = pyfits.HDUList() hdu = pyfits.PrimaryHDU() hdu._file=open(file,'rb') ...
python
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. """ # Endpoint parameters ...
java
public Chunk setRemoteGoto(String filename, int page) { return setAttribute(REMOTEGOTO, new Object[] { filename, Integer.valueOf(page) }); }
java
public void setData(byte[] data) { // There are always two bytes of payload in the message -- the // slave ID and the run status indicator. if (data == null) { m_length = 2; m_data = new byte[0]; return; } if (data.length > 249) { ...
python
def until_not_synced(self, timeout=None): """Convenience method to wait (with Future) until client is not synced""" not_synced_states = [state for state in self._state.valid_states if state != 'synced'] not_synced_futures = [self._state.until_state(state) ...
java
public List<SearchResult> search(String query) throws MovieMeterException { String url = buildSearchUrl(query); try { return mapper.readValue(requestWebPage(url), new TypeReference<List<SearchResult>>() { }); } catch (IOException ex) { throw new MovieMeterExc...
java
public com.squareup.okhttp.Call getObjectAsync(String objectType, String dnType, List<String> dnGroups, String groupType, Integer limit, Integer offset, String searchTerm, String searchKey, String matchMethod, String sortKey, Boolean sortAscending, String sortMethod, String dbids, Boolean inUse, final ApiCallback<GetOb...
python
def modifyModlist( old_entry: dict, new_entry: dict, ignore_attr_types: Optional[List[str]] = None, ignore_oldexistent: bool = False) -> Dict[str, Tuple[str, List[bytes]]]: """ Build differential modify list for calling LDAPObject.modify()/modify_s() :param old_entry: Dictionary hol...
java
private UploadRequestProcessor getUploadRequestProcessor(TransferContext transferContext) { LOGGER.entering(transferContext); String contentType = transferContext.getHttpServletRequest().getContentType() != null ? transferContext .getHttpServletRequest().getContentType().toLowerCase() : ...
python
def bads_report(bads, path_prefix=None): """ Return a nice report of bad architectures in `bads` Parameters ---------- bads : set set of length 2 or 3 tuples. A length 2 tuple is of form ``(depending_lib, missing_archs)`` meaning that an arch in `require_archs` was missing from ...
java
public void setDomainsAlwaysInScope(List<DomainAlwaysInScopeMatcher> domainsAlwaysInScope) { if (domainsAlwaysInScope == null || domainsAlwaysInScope.isEmpty()) { this.domainsAlwaysInScope = Collections.emptyList(); } else { this.domainsAlwaysInScope = domainsAlwaysInScope; } }
python
def send(self, sendspec): """Send string as a shell command, and wait until the expected output is seen (either a string or any from a list of strings) before returning. The expected string will default to the currently-set default expected string (see get_default_shutit_pexpect_session_expect) Returns the p...
python
def GroupBy(self: Iterable, f=None): """ [ { 'self': [1, 2, 3], 'f': lambda x: x%2, 'assert': lambda ret: ret[0] == [2] and ret[1] == [1, 3] } ] """ if f and is_to_destruct(f): f = destruct_func(f) return _group_by(self, f)
python
def asin(x, context=None): """ Return the inverse sine of ``x``. The mathematically exact result lies in the range [-π/2, π/2]. However, note that as a result of rounding to the current context, it's possible for the actual value to lie just outside this range. """ return _apply_function_...
python
def validate(self, value): """Validates that `value` can be assigned to this Property. Parameters: value: The value to validate. Raises: TypeError: If the type of the assigned value is invalid. Returns: The value that should be assigned to the entity. ...
java
@Nonnull public static ACLContext as(@Nonnull Authentication auth) { final ACLContext context = new ACLContext(SecurityContextHolder.getContext()); SecurityContextHolder.setContext(new NonSerializableSecurityContext(auth)); return context; }
python
def theano_compiler(model): """Take a triflow model and return optimized theano routines. Parameters ---------- model: triflow.Model: Model to compile Returns ------- (theano function, theano_function): Optimized routine that compute the evolution equations and their ...
java
private FetchPath getPathProperties(JsonGenerator jsonGenerator) { FetchPath fetchPath = EbeanUtils.getRequestFetchPath(); if (fetchPath != null) { JsonStreamContext context = jsonGenerator.getOutputContext(); JsonStreamContext parent = context.getParent(); if (parent...
java
public <K> JavaPairRDD<K, INDArray> feedForwardWithMaskAndKey(JavaPairRDD<K, Tuple2<INDArray,INDArray>> featuresDataAndMask, int batchSize) { return featuresDataAndMask .mapPartitionsToPair(new FeedForwardWithKeyFunction<K>(sc.broadcast(network.params()), sc.broadcast(con...
python
def cluster_add_slots(self, slot, *slots): """Assign new hash slots to receiving node.""" slots = (slot,) + slots if not all(isinstance(s, int) for s in slots): raise TypeError("All parameters must be of type int") fut = self.execute(b'CLUSTER', b'ADDSLOTS', *slots) r...
java
public static TBSCertificateStructure getTBSCertificateStructure( X509Certificate cert) throws CertificateEncodingException, IOException { ASN1Primitive obj = toASN1Primitive(cert.getTBSCertificate()); return TBSCertificateStructure.getInstance(obj); }
python
def processPointOfSalePayment(request): ''' This view handles the callbacks from point-of-sale transactions. Please note that this will only work if you have set up your callback URL in Square to point to this view. ''' print('Request data is: %s' % request.GET) # iOS transactions put all r...
python
def connection_required(func): """Decorator to specify that a target connection is required in order for the given method to be used. Args: func (function): function being decorated Returns: The wrapper function. """ @functools.wraps(func) de...
java
public static Query createQueryForNodesWithFieldLessThan(String constraintValue, String fieldName, Function<String, String> caseOperation) { return FieldComparison.LT.createQueryForNodesWith...
java
@Nullable public final View nextView(RecyclerView.Recycler recycler, LayoutStateWrapper layoutState, LayoutManagerHelper helper, LayoutChunkResult result) { View view = layoutState.next(recycler); if (view == null) { // if we are laying out views in scrap, this may return null which mean...
java
private int buildLookUpTable() { int i = 0; int incDen = Math.round(8F * radiusMin); // increment denominator lut = new int[2][incDen][depth]; for( int radius = radiusMin; radius <= radiusMax; radius = radius + radiusInc ) { i = 0; for( int incNun = 0; incNun <...
python
def insert(self, data, return_object=False): """ Inserts the data as a new document. """ obj = self(data) # pylint: disable=E1102 obj.save() if return_object: return obj else: return obj["_id"]
python
def analyze_frames(cls, workdir): '''generate draft from recorded frames''' record = cls(None, workdir) obj = {} with open(os.path.join(workdir, 'frames', 'frames.json')) as f: obj = json.load(f) record.device_info = obj['device'] record.frames = obj['f...
java
private Double scale(Double value, Double mean, Double std) { if(std.equals(0.0)) { if(value > mean) { return 1.0; } else if(value < mean) { return -1.0; } else { return Math.signum(value); } ...
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case DroolsPackage.ON_ENTRY_SCRIPT_TYPE__SCRIPT: return getScript(); case DroolsPackage.ON_ENTRY_SCRIPT_TYPE__SCRIPT_FORMAT: return getScriptFormat(); } return super.eGet(featureID, resolve, coreTy...
java
public Collection<Dependency> getMemberInjectionDependencies( Key<?> typeKey, TypeLiteral<?> type) { Set<Dependency> required = new LinkedHashSet<Dependency>(); for (MethodLiteral<?, Method> method : memberCollector.getMethods(type)) { required.addAll(getDependencies(typeKey, method)); } fo...
java
public static boolean contentEquals(InputStream input1, InputStream input2) throws IOException { if (!(input1 instanceof BufferedInputStream)) { input1 = new BufferedInputStream(input1); } if (!(input2 instanceof BufferedInputStream)) { input2 = new BufferedInputStream(input2); } ...
java
@SuppressWarnings("unchecked") public CassandraJavaPairRDD<K, V> select(String... columnNames) { Seq<ColumnRef> columnRefs = toScalaSeq(toSelectableColumnRefs(columnNames)); CassandraRDD<Tuple2<K, V>> newRDD = rdd().select(columnRefs); return wrap(newRDD); }
java
public int compareTo(InternalFeature o) { if (null == o) { return -1; // avoid NPE, put null objects at the end } if (null != styleDefinition && null != o.getStyleInfo()) { if (styleDefinition.getIndex() > o.getStyleInfo().getIndex()) { return 1; } if (styleDefinition.getIndex() < o.getStyleInfo()...
python
def page_count(self): """ Get count of total pages """ postcount = self.post_set.count() max_pages = (postcount / get_paginate_by()) if postcount % get_paginate_by() != 0: max_pages += 1 return max_pages
java
private ReferenceType computeFirstCommonSuperclassOfSameDimensionArrays(ArrayType aArrType, ArrayType bArrType) throws ClassNotFoundException { assert aArrType.getDimensions() == bArrType.getDimensions(); Type aBaseType = aArrType.getBasicType(); Type bBaseType = bArrType.getBasicTy...
python
def _validate_config(self): """ ensure REQUIRED_CONFIG_KEYS are filled """ # exit if no backend specified if not self.backend: return # exit if no required config keys if len(self.REQUIRED_CONFIG_KEYS) < 1: return self.config = self.config or {} ...
java
public void setSendRefererHeader(boolean send) { if (send == sendRefererHeader) { return; } this.sendRefererHeader = send; getConfig().setProperty(SPIDER_SENDER_REFERER_HEADER, this.sendRefererHeader); }
python
def _conf(cls, opts): """Setup logging via ini-file from logging_conf_file option.""" if not opts.logging_conf_file: return False if not os.path.exists(opts.logging_conf_file): # FileNotFoundError added only in Python 3.3 # https://docs.python.org/3/whatsnew/...
python
def _iterate_records(self): """ iterate over each record """ raise_invalid_gzip = False empty_record = False while True: try: self.record = self._next_record(self.next_line) if raise_invalid_gzip: self._raise_invali...
python
def has_option(self, target): """ Return ``True`` if the actual arguments include the specified ``target`` option or, if ``target`` is a list of options, at least one of them. :param target: the option or a list of options :type target: Unicode string or list of...
java
public static String toStringForTimeZone(DateTime dateTime, String newZoneId) { return dateTimesHelper.toStringForTimeZone(dateTime, newZoneId); }
java
public static int cusolverSpScsrlsvluHost( cusolverSpHandle handle, int n, int nnzA, cusparseMatDescr descrA, Pointer csrValA, Pointer csrRowPtrA, Pointer csrColIndA, Pointer b, float tol, int reorder, Pointer x...
java
public void setExtension(/* @Nullable */ JvmField field, EObject sourceElement, boolean value) { if (field == null) return; internalSetExtension(field, sourceElement, value); }
java
public static Context discover(Object context, Class<?>... subset) { Set<Class<?>> contextSubset = (subset == null || subset.length == 0)? contexts.keySet() :new HashSet<Class<?>>(Arrays.asList(subset)); Set<Class<?>> contextClasses = contexts.keySet(); for (Class<?> contextClass : contextClasses) { ...
python
def job_success(self, job, queue, job_result): """ Called just after an execute call was successful. job_result is the value returned by the callback, if any. """ job.queued.delete() job.hmset(end=str(datetime.utcnow()), status=STATUSES.SUCCESS) queue.success.rpus...
java
public static Version valueOf(String versionString) throws IllegalArgumentException { Matcher matcher = versionPattern.matcher(versionString); if (!matcher.matches()) { throw new IllegalArgumentException( "The version string must match the pattern '" + versionRegExp + "'."); } int majorVersio...
python
def floyd_warshall_get_cycle(self, distance, nextn, element = None): ''' API: floyd_warshall_get_cycle(self, distance, nextn, element = None) Description: Finds a negative cycle in the graph. Pre: (1) distance and nextn are outputs of floyd_warshall me...
java
public StateId forRange(final StateRange range) { if (getRange().equals(range)) { return this; } return new StateId(stateToken, range); }
java
public void del(byte[] key){ Jedis jedis = jedisPool.getResource(); try{ jedis.del(key); }finally{ jedisPool.returnResource(jedis); } }
java
public static base_responses update(nitro_service client, autoscaleaction resources[]) throws Exception { base_responses result = null; if (resources != null && resources.length > 0) { autoscaleaction updateresources[] = new autoscaleaction[resources.length]; for (int i=0;i<resources.length;i++){ updatere...
java
@Override public void setActionObject(final Object data) { InputModel model = getOrCreateComponentModel(); model.actionObject = data; }
java
@SuppressWarnings("unchecked") public <K> K[] getKeys(Map<K, ?> map) { K[] result = null; Set<K> keySet = map.keySet(); if (keySet.size() > 0) { result = (K[]) keySet.toArray(new Object[keySet.size()]); } return result; }