language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def get_input(*args, secret=False, required=False, blank=False, **kwargs): """ secret: Don't show user input when they are typing. required: Keep prompting if the user enters an empty value. blank: turn all empty strings into None. """ while True: if secret: value = getpass....
python
def object_build(self, node, obj): """recursive method which create a partial ast from real objects (only function, class, and method are handled) """ if obj in self._done: return self._done[obj] self._done[obj] = node for name in dir(obj): try: ...
java
private void setUserInfo(CmsUser user, String key, String value) { if (!CmsStringUtil.isEmptyOrWhitespaceOnly(value)) { user.getAdditionalInfo().put(key, value); } }
java
public static String firstRegistryOf(String ... checkFirst) { for (String registry : checkFirst) { if (registry != null) { return registry; } } // Check environment as last resort return System.getenv("DOCKER_REGISTRY"); }
java
@Override public byte[] get(String table, String key) { String CQL = MessageFormat.format(CQL_SELECT_ONE, calcTableName(table)); Row row = getSessionManager().executeOne(CQL, getConsistencyLevelGet(), key); ByteBuffer data = row != null ? row.getBytes(columnValue) : null; return data...
java
private static IndexableExpression getIndexableExpressionFromFilters( ExpressionType targetComparator, ExpressionType altTargetComparator, AbstractExpression coveringExpr, int coveringColId, StmtTableScan tableScan, List<AbstractExpression> filtersToCover, boolean allowIndexedJoinFilters...
python
def add_deviation_element(keyword, element): """Add an element to the <keyword>'s list of deviations. Can be used by plugins that add support for specific extension statements.""" if keyword in _valid_deviations: _valid_deviations[keyword].append(element) else: _valid_deviations[keyword] = [eleme...
java
public void updateConfigInfo(final HttpServletRequest request, final XSLTConfig xcfg) throws ServletException { PresentationState ps = getPresentationState(request); if (ps == null) { // Still can't do a thing return; } if (xcfg.nextCfg == null) { ...
python
def fetch_gene_fasta(gene_bed, fasta_obj): """Retreive gene sequences in FASTA format. Parameters ---------- gene_bed : BedLine BedLine object representing a single gene fasta_obj : pysam.Fastafile fasta object for index retreival of sequence Returns ------- gene_fasta ...
python
def delete_cloud_integration(self, id, **kwargs): # noqa: E501 """Delete a specific cloud integration # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_c...
java
public void trim(int ntrees) { if (ntrees > trees.size()) { throw new IllegalArgumentException("The new model size is larger than the current size."); } if (ntrees <= 0) { throw new IllegalArgumentException("Invalid new model size: " + ntrees); } ...
python
def to_df(self, variables=None, format='wide', sparse=True, sampling_rate=None, include_sparse=True, include_dense=True, **kwargs): ''' Merge columns into a single pandas DataFrame. Args: variables (list): Optional list of variable names to retain; ...
java
public static <T> String toJson(T t) { if (Objects.isNull(t)) { log.warn("t is blank. "); return ""; } try { return OBJECT_MAPPER.writeValueAsString(t); } catch (Exception e) { log.error(e.getMessage(), e); return ""; } ...
java
public Observable<Void> validateWorkflowAsync(String resourceGroupName, String workflowName, WorkflowInner validate) { return validateWorkflowWithServiceResponseAsync(resourceGroupName, workflowName, validate).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(Serv...
java
public static void checkXerbla() { double[] x = new double[9]; System.out.println("Check whether we're catching XERBLA errors. If you see something like \"** On entry to DGEMM parameter number 4 had an illegal value\", it didn't work!"); try { NativeBlas.dgemm('N', 'N', 3, -1, 3, 1...
java
private final int getLowestSetBit() { if (intLen == 0) return -1; int j, b; for (j=intLen-1; (j > 0) && (value[j+offset] == 0); j--) ; b = value[j+offset]; if (b == 0) return -1; return ((intLen-1-j)<<5) + Integer.numberOfTrailingZeros(...
java
public String generate(Config config) { isNotNull(config, "Config"); StringBuilder xml = new StringBuilder(); XmlGenerator gen = new XmlGenerator(xml); xml.append("<hazelcast ") .append("xmlns=\"http://www.hazelcast.com/schema/config\"\n") .append("xmlns...
python
def compile_dir(env, src_path, dst_path, pattern=r'^.*\.html$', encoding='utf-8', base_dir=None): """Compiles a directory of Jinja2 templates to python code. :param env: a Jinja2 Environment instance. :param src_path: path to the source directory. :param dst_path: path to the destination directory. :param ...
python
def publish(self, event, *args, **kwargs): """ Publish a event and return a list of values returned by its subscribers. :param event: The event to publish. :param args: The positional arguments to pass to the event's subscribers. :param kwargs: The k...
python
def delete(self, *names: str, pipeline=False): """Delete one or more keys specified by names. Args: names (str): Names of keys to delete pipeline (bool): True, start a transaction block. Default false. """ if pipeline: self._pipeline.delete(*names) ...
python
def standardGeographyQuery(self, sourceCountry=None, optionalCountryDataset=None, geographyLayers=None, geographyIDs=None, geographyQuery=None, ...
java
public void marshall(CreateResourceServerRequest createResourceServerRequest, ProtocolMarshaller protocolMarshaller) { if (createResourceServerRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshal...
python
def relaxation_operators(p): """ Return the amplitude damping Kraus operators """ k0 = np.array([[1.0, 0.0], [0.0, np.sqrt(1 - p)]]) k1 = np.array([[0.0, np.sqrt(p)], [0.0, 0.0]]) return k0, k1
java
private boolean getBooleanAttributeValue(Node source) { Attr attribute = (Attr)source; String value = attribute.getValue(); return "true".equalsIgnoreCase(value); }
java
private void handleHttpResponse(HttpResponse response, Class<? extends Response> responseClass, KickflipCallback cb) throws IOException { //Object parsedResponse = response.parseAs(responseClass); if (isSuccessResponse(response)) { // Http Success handleKickflipResponse(response,...
java
synchronized void onExport(ExportTraceServiceRequest request) { if (isCompleted() || exportRequestObserver == null) { return; } try { exportRequestObserver.onNext(request); } catch (Exception e) { // Catch client side exceptions. onComplete(e); } }
java
public Locale getLocale() throws JspException { Locale loc = null; if (_language != null || _country != null) { // language is required if (_language == null) { String s = Bundle.getString("Tags_LocaleRequiresLanguage", new Object[]{_country}); ...
python
def listdir(store, path=None): """Obtain a directory listing for the given path. If `store` provides a `listdir` method, this will be called, otherwise will fall back to implementation via the `MutableMapping` interface.""" path = normalize_storage_path(path) if hasattr(store, 'listdir'): # ...
java
public INDArray[] output(boolean train, @NonNull INDArray[] input, INDArray[] inputMasks){ return output(train, input, inputMasks, null); }
java
private boolean matches(File file, byte[] digest, Configuration conf) throws IOException { byte[] fileDigest = getDigest(file, conf); return Arrays.equals(fileDigest, digest); }
java
private boolean allConnectionsFromOtherStage(final ExecutionGroupVertex groupVertex, final boolean forward) { if (forward) { for (int i = 0; i < groupVertex.getNumberOfBackwardLinks(); i++) { if (this.stage == groupVertex.getBackwardEdge(i).getSourceVertex().getStageNumber()) { return false; } } ...
java
@Override public void eUnset(int featureID) { switch (featureID) { case SimpleAntlrPackage.OPTIONS__OPTION_VALUES: getOptionValues().clear(); return; } super.eUnset(featureID); }
python
def validate_submission(self, filename): """Validates submission. Args: filename: submission filename Returns: submission metadata or None if submission is invalid """ self._prepare_temp_dir() # Convert filename to be absolute path, relative path might cause problems # with mou...
python
def _categorize(self, category): """Remove torrents with unwanted category from self.torrents""" self.torrents = [result for result in self.torrents if result.category == category]
java
@Override public String getMessage() { if (getCause() instanceof UnknownHostException) { return "Host (" + getHost() + ") is unreachable !!!!"; } if (getCause() instanceof ConnectException) { return "Host (" + getHost() + ") is unreachable at Port (" + getPort() + ")!!!!"; } return getCause().getMessag...
python
def _set_country(self, c): """ callback if we used Tor's GETINFO ip-to-country """ self.location.countrycode = c.split()[0].split('=')[1].strip().upper()
java
private static boolean authenticateAuthorizationHeader(Map<String,String> headers) { String hdr = headers.get(Listener.AUTHORIZATION_HEADER_NAME); if (hdr == null) hdr = headers.get(Listener.AUTHORIZATION_HEADER_NAME.toLowerCase()); headers.remove(Listener.AUTHORIZATION_HEADER_NAME)...
python
def update_features(self, poly): """Evaluate wavelength at xpos using the provided polynomial.""" for feature in self.features: feature.wavelength = poly(feature.xpos)
java
@Override public void writeStringData(String value, int offset, int length) { char []cBuf = _charBuffer; int cBufLength = cBuf.length; for (int i = 0; i < length; i += cBufLength) { int sublen = Math.min(length - i, cBufLength); value.getChars(offset + i, offset + i + sublen, cBu...
java
public WxCardAPISignature createWxCardJsAPISignature(WxCardAPISignature wxCardAPISignature){ if(wxCardAPITicket == null || wxCardAPITicket.expired()) { getWxCardAPITicket(); } long timestamp = System.currentTimeMillis() / 1000; String nonce = RandomStringGenerator.getR...
java
public static synchronized ILoadBalancer getNamedLoadBalancer(String name) { ILoadBalancer lb = namedLBMap.get(name); if (lb != null) { return lb; } else { try { lb = registerNamedLoadBalancerFromclientConfig(name, getNamedConfig(name)); } catc...
java
public void setContainer(DatePickerContainer container) { this.container = container; options.container = container == DatePickerContainer.SELF ? getElement().getId() : container.getCssName(); }
java
private static String adopt2JavaPattern(String pattern) { pattern = normalizePath(pattern); // any character except '/', one or more times pattern = pattern.replaceAll("\\" + ANY_NAME, "[^/]+"); // any character except '/' exactly one time pattern = pattern.replaceAll(ANY_CHAR, "[^/]{...
java
@Override public void start() { mTerminated = false; mStarted = true; // First, sort the nodes (if necessary). This will ensure that sortedNodes // contains the animation nodes in the correct order. sortNodes(); int numSortedNodes = mSortedNodes.size(); for ...
java
public static <R> Func0<R> toFunc(final Action0 action, final R result) { return new Func0<R>() { @Override public R call() { action.call(); return result; } }; }
java
public void invalidate(@Nullable Uri uri) { if (uri != null) { cache.clearKeyUri(uri.toString()); } }
java
public Content throwsTagOutput(Element element, DocTree throwsTag) { ContentBuilder body = new ContentBuilder(); CommentHelper ch = utils.getCommentHelper(element); Element exception = ch.getException(configuration, throwsTag); Content excName; if (exception == null) { ...
java
public DenseMatrix inverse() { int m = lu.nrows(); int n = lu.ncols(); if (m != n) { throw new IllegalArgumentException(String.format("Matrix is not square: %d x %d", m, n)); } DenseMatrix inv = Matrix.zeros(n, n); for (int i = 0; i < n; i++) { i...
python
def sign(self, encoded): """ Return authentication signature of encoded bytes """ signature = self._hmac.copy() signature.update(encoded) return signature.hexdigest().encode('utf-8')
java
public static SameDiff restoreFromTrainingConfigZip(File file) throws IOException { ZipFile zipFile = new ZipFile(file); ZipEntry config = zipFile.getEntry(TRAINING_CONFIG_JSON_ZIP_ENTRY_NAME); TrainingConfig trainingConfig = null; try(InputStream stream = zipFile.getInputStream(config))...
python
def dframe(self, dimensions=None, multi_index=False): """Convert dimension values to DataFrame. Returns a pandas dataframe of columns along each dimension, either completely flat or indexed by key dimensions. Args: dimensions: Dimensions to return as columns mul...
python
def function(self, rule, args, **kwargs): """ Callback method for rule tree traversing. Will be called at proper time from :py:class:`pynspect.rules.FunctionRule.traverse` method. :param pynspect.rules.Rule rule: Reference to rule. :param args: Optional function arguments. ...
java
@Override @SuppressWarnings("unchecked") public PlainDate apply(PlainDate entity) { ChronoOperator<PlainDate> operator = (ChronoOperator<PlainDate>) this.opDelegate; return operator.apply(entity); }
java
protected void doPropagateAssertObject(InternalFactHandle factHandle, PropagationContext context, InternalWorkingMemory workingMemory, ObjectSink sink) { sink.assertObject( factHandle...
python
def reshape(x,input_dim): ''' Reshapes x into a matrix with input_dim columns ''' x = np.array(x) if x.size ==input_dim: x = x.reshape((1,input_dim)) return x
java
public Date getThere(Date start, Distance distance) { TimeSpan timeSpan = getTimeSpan(distance); return timeSpan.addDate(start); }
java
public static <T, E> AtomFeedParser<T, E> create( HttpResponse response, XmlNamespaceDictionary namespaceDictionary, Class<T> feedClass, Class<E> entryClass) throws IOException, XmlPullParserException { InputStream content = response.getContent(); try { Atom.checkContentType(...
python
def _invariant(self, rank, n): """Computes the delta value for the sample.""" minimum = n + 1 for i in self._invariants: delta = i._delta(rank, n) if delta < minimum: minimum = delta return math.floor(minimum)
java
protected Uberspect instantiateUberspector(String classname) { Object o = null; try { o = ClassUtils.getNewInstance(classname); } catch (ClassNotFoundException e) { this.log.warn(String.format("The specified uberspector [%s]" + " does not exist or is n...
python
def pad(self, minibatch): """Pad a batch of examples using this field. If ``self.nesting_field.sequential`` is ``False``, each example in the batch must be a list of string tokens, and pads them as if by a ``Field`` with ``sequential=True``. Otherwise, each example must be a list of lis...
python
def make_funcs(dataset, setdir, store): """Functions available for listing columns and filters.""" return { 'cat': lambda *lists: [x for lst in lists for x in lst], 'comments': lambda: None, 'detail_route': detail_route, 'format': lambda fmt, *args: fmt.format(*args), 'ge...
python
def _get_sorted_inputs(filename, delimiter="\n"): """Returning inputs sorted according to decreasing length. This causes inputs of similar lengths to be processed in the same batch, facilitating early stopping for short sequences. Longer sequences are sorted first so that if you're going to get OOMs, you'll...
java
@Override public GetSizeConstraintSetResult getSizeConstraintSet(GetSizeConstraintSetRequest request) { request = beforeClientExecution(request); return executeGetSizeConstraintSet(request); }
python
def basis_selector_oracle(qubits: List[int], bitstring: str) -> Program: """ Defines an oracle that selects the ith element of the computational basis. Flips the sign of the state :math:`\\vert x\\rangle>` if and only if x==bitstring and does nothing otherwise. :param qubits: The qubits the oracle...
python
def ResolvePrefix(self, subject, attribute_prefix, timestamp=None, limit=None): """Resolve all attributes for a subject starting with a prefix.""" subject = utils.SmartUnicode(subject) if timestamp in [None, self.NEWEST_TIMESTAMP, self.ALL_TIMESTAMPS]: start, end = 0, (2**63) - 1 ...
java
public ClassLoader getExternalClassLoader() { Map<String,String> opts = _ap.getAnnotationProcessorEnvironment().getOptions(); String classpath = opts.get("-classpath"); if ( classpath != null ) { String [] cpEntries = classpath.split( File.pathSeparator ); Ar...
java
private void addFile(File root, File file, String prefix, ZipOutputStream zos) throws IOException { FileInputStream fis = new FileInputStream(file); ZipEntry jarEntry = new ZipEntry(prefix + normalizePath(root, file)); zos.putNextEntry(jarEntry); StreamUtils.copyStream(fis, zos, false); ...
python
def recurse(self, value, max_depth=6, _depth=0, **kwargs): """ Given ``value``, recurse (using the parent serializer) to handle coercing of newly defined values. """ string_max_length = kwargs.get('string_max_length', None) _depth += 1 if _depth >= max_depth: ...
python
def __EncodedAttribute_decode_gray8(self, da, extract_as=ExtractAs.Numpy): """Decode a 8 bits grayscale image (JPEG_GRAY8 or GRAY8) and returns a 8 bits gray scale image. :param da: :class:`DeviceAttribute` that contains the image :type da: :class:`DeviceAttribute` :param extract_as: defaul...
python
def isometric(lat: float, ell: Ellipsoid = None, deg: bool = True): """ computes isometric latitude of a point on an ellipsoid Parameters ---------- lat : float or numpy.ndarray of float geodetic latitude ell : Ellipsoid, optional reference ellipsoid (default WGS84) ...
java
private TTTState<I, D> getAnyState(Iterable<? extends I> suffix) { return getAnySuccessor(hypothesis.getInitialState(), suffix); }
java
@Override public byte[] getValue() { StringBuilder sb = new StringBuilder(64); sb.append(component).append(MetricUtils.AT).append(taskId).append(MetricUtils.AT) .append(streamId).append(MetricUtils.AT).append(metricType).append(MetricUtils.AT) .append(host).append(Met...
python
def or_where(self, key, operator, value): """Make or_where clause :@param key :@param operator :@param value :@type key, operator, value: string :@return self """ if len(self._queries) > 0: self._current_query_index += 1 self.__store_...
java
public Geometry getGeometryN(int n) { if (isEmpty()) { return null; } if (n >= 0 && n < points.length) { return points[n]; } throw new ArrayIndexOutOfBoundsException(n); // return this; }
python
def coombs_winners(self, profile): """ Returns an integer list that represents all possible winners of a profile under Coombs rule. :ivar Profile profile: A Profile object that represents an election profile. """ elecType = profile.getElecType() if elecType == "soc" or e...
java
private static boolean postAggregatorDirectColumnIsOk( final RowSignature aggregateRowSignature, final DruidExpression expression, final RexNode rexNode ) { if (!expression.isDirectColumnAccess()) { return false; } // Check if a cast is necessary. final ExprType toExprType =...
java
public void trace(final Marker marker, final String message) { log.trace(marker, sanitize(message)); }
python
def post(self, path, payload, callback=None, timeout=None, no_response=False, **kwargs): # pragma: no cover """ Perform a POST on a certain path. :param path: the path :param payload: the request payload :param callback: the callback function to invoke upon response :pa...
python
def find_lines(config=None, config_path=None, regex=None, saltenv='base'): ''' Return all the lines (as text) that match the expression in the ``regex`` argument. config The configuration sent as text. .. note:: This argument is ignored when ``config_path`` is specified. ...
python
def get_vpn(self, vpn_name): """Returns a specific VPN name details from CPNR server.""" request_url = self._build_url(['VPN', vpn_name]) return self._do_request('GET', request_url)
java
@Override public GetReplicationJobsResult getReplicationJobs(GetReplicationJobsRequest request) { request = beforeClientExecution(request); return executeGetReplicationJobs(request); }
java
public Stream<String> containing(double lat, double lon) { return shapes.keySet().stream() // select if contains lat lon .filter(name -> shapes.get(name).contains(lat, lon)); }
java
private String zeroEndByteArrayToString(byte[] bytes) throws IOException { int i = 0; for ( i = 0; i < bytes.length && bytes[i] != 0; i++ ); return new String( bytes, 0, i ); }
python
def to_pngs(pdf_path): ''' Converts a multi-page pdfs to a list of pngs via the `sips` command :returns: A list of converted pngs ''' pdf_list = split_pdf(pdf_path) pngs = [] for pdf in pdf_list: pngs.append(to_png(pdf)) os.remove(pdf) # Clean up return pngs
python
def is_date(value, minimum = None, maximum = None, coerce_value = False, **kwargs): """Indicate whether ``value`` is a :class:`date <python:datetime.date>`. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is on...
java
private boolean tryResolve(final CLClause c, final int pivot, final CLClause d) { assert !c.dumped() && !c.satisfied(); assert !d.dumped() && !d.satisfied(); boolean res = true; assert this.seen.empty(); this.stats.steps++; for (int i = 0; i < c.lits().size(); i++) { ...
python
def add(self, val): """Add the element *val* to the list.""" _lists = self._lists _keys = self._keys _maxes = self._maxes key = self._key(val) if _maxes: pos = bisect_right(_maxes, key) if pos == len(_maxes): pos -= 1 ...
java
@SuppressWarnings("rawtypes") @Override protected Object convertToType(Class type, Object value) throws Throwable { return KeyFactory.stringToKey(value.toString()); }
java
public void close() { LOGGER.entering(CLASS_NAME, "close"); synchronized (lock) { if (serviceAgent != null) { serviceRegistration.unregister(); if (LOGGER.isLoggable(Level.FINER)) LOGGER.finer("Service Agent " + this + " stopping...")...
python
def begin_training(self, get_gold_tuples=None, sgd=None, component_cfg=None, **cfg): """Allocate models, pre-process training data and acquire a trainer and optimizer. Used as a contextmanager. get_gold_tuples (function): Function returning gold data component_cfg (dict): Config paramet...
python
def get_keygrip(user_id, sp=subprocess): """Get a keygrip of the primary GPG key of the specified user.""" args = gpg_command(['--list-keys', '--with-keygrip', user_id]) output = check_output(args=args, sp=sp).decode('utf-8') return re.findall(r'Keygrip = (\w+)', output)[0]
java
public DirectedMultigraph<String> readDirectedMultigraph( File f, Indexer<String> vertexLabels) throws IOException { throw new UnsupportedOperationException(); }
python
def _set_range_common(self, k_sugar, k_start, k_end, value): """ Checks to see if the client-side convenience key is present, and if so converts the sugar convenience key into its real server-side equivalents. :param string k_sugar: The client-side convenience key :param...
python
def remove_words(self, words): """ Remove a list of words from the word frequency list Args: words (list): The list of words to remove """ for word in words: self._dictionary.pop(word.lower()) self._update_dictionary()
java
@Override public void saturate(IAtomContainer atomContainer) throws CDKException { logger.info("Saturating atomContainer by adjusting bond orders..."); boolean allSaturated = allSaturated(atomContainer); if (!allSaturated) { logger.info("Saturating bond orders is needed..."); ...
python
def view_task(self, task): """View the given task :param task: the task to view :type task: :class:`jukeboxcore.djadapter.models.Task` :returns: None :rtype: None :raises: None """ log.debug('Viewing task %s', task.name) self.cur_task = None ...
python
def _bse_cli_list_basis_sets(args): '''Handles the list-basis-sets subcommand''' metadata = api.filter_basis_sets(args.substr, args.family, args.role, args.data_dir) if args.no_description: liststr = metadata.keys() else: liststr = format_columns([(k, v['description']) for k, v in metad...
python
def enable_mfa_device(self, user_name, serial_number, authentication_code_1, authentication_code_2): """Enable MFA Device for user.""" user = self.get_user(user_name) if serial_number in user....
python
def create_with_validation (raw_properties): """ Creates new 'PropertySet' instances after checking that all properties are valid and converting implicit properties into gristed form. """ assert is_iterable_typed(raw_properties, basestring) properties = [property.create_from_string(s) fo...
java
private long pendingVideoMessages() { IMessageOutput out = msgOutReference.get(); if (out != null) { OOBControlMessage pendingRequest = new OOBControlMessage(); pendingRequest.setTarget("ConnectionConsumer"); pendingRequest.setServiceName("pendingVideoCount"); ...