language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def build_kvasir_url( proto="https", server="localhost", port="8443", base="Kvasir", user="test", password="test", path=KVASIR_JSONRPC_PATH): """ Creates a full URL to reach Kvasir given specific data >>> build_kvasir_url('https', 'localhost', '8443', 'Kvasir', 'test', 'test') '...
python
def get_model_parser(top_rule, comments_model, **kwargs): """ Creates model parser for the given language. """ class TextXModelParser(Parser): """ Parser created from textual textX language description. Semantic actions for this parser will construct object graph represe...
python
def fast_sweep_steady_state(Ep, epsilonp, gamma, omega_level, rm, xi, theta, file_name=None, return_code=False): r"""Return an spectrum of density matrices in the steady state. We test a basic two-level system. >>> import numpy as np >>> from sym...
python
def format_type(t, includeOptional=True): """ Returns the type as a string. If the type is an array, then it is prepended with [] :Parameters: t The type as a dict. Keys: 'type', 'is_array' """ s = "" if t.has_key('is_array') and t['is_array']: s = "[]%s" % t['type'] ...
java
@Override public List<RecordParam> getAll () throws DatabaseException { try { List<RecordParam> result = new ArrayList<>(); try (ResultSet rs = psGetAll.executeQuery()) { while (rs.next()) { result.add(new RecordParam(rs.getLong(PARAMID), rs.getString(SITE), rs.getString(TYPE), rs.g...
python
def blocks_info(self, hashes, pending=False, source=False): """ Retrieves a json representations of **blocks** with transaction **amount** & block **account** :param hashes: List of block hashes to return info for :type hashes: list of str :param pending: If true, retur...
java
protected IDialogSettings getDialogSettings() { try { return (IDialogSettings) this.reflect.get(this, "fDialogSettings"); //$NON-NLS-1$ } catch (SecurityException | NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) { throw new Error(e); } }
java
public CompletableFuture<QueryResponse> query(QueryRequest request) { CompletableFuture<QueryResponse> future = new CompletableFuture<>(); if (context.isCurrentContext()) { sendRequest(request, protocol::query, future); } else { context.execute(() -> sendRequest(request, protocol::query, future)...
java
public List<Boolean> findBooleanValues(JvmAnnotationTarget op, Class<? extends Annotation> annotationType) { final JvmAnnotationReference reference = this.lookup.findAnnotation(op, annotationType); if (reference != null) { return findBooleanValues(reference); } return null; }
python
def host(self): '''Return the host committee. ''' _id = None for participant in self['participants']: if participant['type'] == 'host': if set(['participant_type', 'id']) < set(participant): # This event uses the id keyname "id". ...
java
@Benchmark public Class<?> benchmarkByteBuddy() { return new ByteBuddy() .with(TypeValidation.DISABLED) .ignore(any()) .subclass(baseClass) .make() .load(newClassLoader(), ClassLoadingStrategy.Default.INJECTION) ...
java
@SafeVarargs public static <E> List<List<E>> cartesianProduct(final Collection<? extends E>... cs) { return cartesianProduct(Arrays.asList(cs)); }
python
def describe(self): """ Describes this Categorical Returns ------- description: `DataFrame` A dataframe with frequency and counts by category. """ counts = self.value_counts(dropna=False) freqs = counts / float(counts.sum()) from pand...
java
public String registerSession (User user, int expireDays) throws PersistenceException { // look for an existing session for this user final String query = "select authcode from sessions where userId = " + user.userId; String authcode = execute(new Operation<String>() { pu...
python
def estimate_rotation_procrustes_ransac(x, y, camera, threshold, inlier_ratio=0.75, do_translation=False): """Calculate rotation between two sets of image coordinates using ransac. Inlier criteria is the reprojection error of y into image 1. Parameters ------------------------- x : array 2xN i...
python
def normal_cloud_im(self, ksize=3): """Generate a NormalCloudImage from the PointCloudImage using Sobel filtering. Parameters ---------- ksize : int Size of the kernel to use for derivative computation Returns ------- :obj:`NormalCloudImage` ...
java
public void save(File file) throws IOException { int deflt; if (labels.size() == 0) { throw new IllegalStateException("no functions defined"); } deflt = code.currentLabel(); illegalId(); code.fixup(switchFixup, TABLESWITCH, deflt, 0, labels.size() - 1, label...
python
def read_record(fp, first_line=None): """ Read a record from a file of AMOS messages On success returns a Message object On end of file raises EOFError """ if first_line is None: first_line = fp.readline() if not first_line: raise EOFError() match = _START.match(first...
java
public static <T> Transformer<Observable<T>, T> flatten() { return new Transformer<Observable<T>, T>() { @Override public Observable<T> call(Observable<Observable<T>> source) { return source.flatMap(Functions.<Observable<T>> identity()); } }; }
java
public static SymbolToken systemSymbol(final int sid) { if (sid < 1 || sid > ION_1_0_MAX_ID) { throw new IllegalArgumentException("No such system SID: " + sid); } return SYSTEM_TOKENS.get(sid - 1); }
java
@CheckReturnValue public RestAction<Void> moveVoiceMember(Member member, VoiceChannel voiceChannel) { Checks.notNull(member, "Member"); Checks.notNull(voiceChannel, "VoiceChannel"); checkGuild(member.getGuild(), "Member"); checkGuild(voiceChannel.getGuild(), "VoiceChannel"); ...
java
public Interval getIntervalOnlyIfExisting(String aName) { Interval interval = intervalsByName.get(aName); if (interval == null) { throw new UnknownIntervalException(aName); } return interval; }
python
def armor(blob, type_str): """See https://tools.ietf.org/html/rfc4880#section-6 for details.""" head = '-----BEGIN PGP {}-----\nVersion: GnuPG v2\n\n'.format(type_str) body = base64.b64encode(blob).decode('ascii') checksum = base64.b64encode(util.crc24(blob)).decode('ascii') tail = '-----END PGP {}-...
python
def LogoPlot(sites, datatype, data, plotfile, nperline, numberevery=10, allowunsorted=False, ydatamax=1.01, overlay=None, fix_limits={}, fixlongname=False, overlay_cmap=None, ylimits=None, relativestackheight=1, custom_cmap='jet', map_metric='kd', noseparator=False, underlay=Fals...
java
@Override public Object get(PageContext pc, Collection.Key key) throws PageException { return get(key); }
python
def pformat_ast(node, include_attributes=INCLUDE_ATTRIBUTES_DEFAULT, indent=INDENT_DEFAULT): """ Pretty-format an AST tree element Parameters ---------- node : ast.AST Top-level node to render. include_attributes : bool, optional Whether to include...
java
public void addEdge(int from, int to) { Set<Integer> outEdges = edges.get(from); if (outEdges == null) { outEdges = new TreeSet<Integer>(); edges.put(from, outEdges); } outEdges.add(to); }
python
def _env_to_bool(val): """ Convert *val* to a bool if it's not a bool in the first place. """ if isinstance(val, bool): return val val = val.strip().lower() if val in ("1", "true", "yes"): return True return False
python
def jr6_txt(mag_file, dir_path=".", input_dir_path="", meas_file="measurements.txt", spec_file="specimens.txt", samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt", user="", specnum=1, samp_con='1', location='unknown', lat='', lon='', noave=False, vol...
python
def check_raw_string(self, string, is_bstring=True): """ Check whether the given string is properly UTF-8 encoded (if ``is_bytes`` is ``True``), it is not empty, and it does not contain reserved characters. :param string string: the byte string or Unicode string to be ch...
java
public void collectMarkerSpecification(VariableSpecifications boundNames) { if (collectionElement != null) collectionElement.collectMarkerSpecification(boundNames); if (operator.equals(Operator.IN) && inValues != null) { for (Term value : inValues) va...
python
def create_diagnostic_request(self, message_id, mode, bus=None, pid=None, frequency=None, payload=None, wait_for_ack=True, wait_for_first_response=False, decoded_type=None): """Send a new diagnostic message request to the VI Required: message_id - The message ID (arbitr...
java
public static com.liferay.commerce.notification.model.CommerceNotificationQueueEntry createCommerceNotificationQueueEntry( long commerceNotificationQueueEntryId) { return getService() .createCommerceNotificationQueueEntry(commerceNotificationQueueEntryId); }
python
def get_gfe(self, annotation, locus): """ creates GFE from a sequence annotation :param locus: The gene locus :type locus: ``str`` :param annotation: An sequence annotation object :type annotation: ``List`` :rtype: ``List`` Returns: The GFE ...
java
public void addListener(Record record, FileListener listener) { if (this.getNextTable() != null) this.getNextTable().addListener(record, listener); }
java
private float getXEncodedLocation(float x, GriddedCoverageEncodingType encodingType) { float xLocation = x; switch (encodingType) { case CENTER: case AREA: xLocation += 0.5f; break; case CORNER: break; default: throw new GeoPackageException("Unsupported Encoding Type: " + encodingType)...
java
public void setCommittedMetrics() { for (MetricImpl.MetricType metricType : this.tranCoordinatedMetricTypes) { committedMetrics.put(metricType.name(), new MetricImpl(metricType, this.getMetric(metricType).getValue())); } }
java
@Override public void search(SearchExecutor se, NameClassPairCallbackHandler handler) { search(se, handler, new NullDirContextProcessor()); }
python
def serialize_query(func): """ Ensure any SQLExpression instances are serialized""" @functools.wraps(func) def wrapper(self, query, *args, **kwargs): if hasattr(query, 'serialize'): query = query.serialize() assert isinstance(query, basestring), 'Expected...
java
public void removeJob(JobID jobId) throws Exception { Preconditions.checkState(JobLeaderService.State.STARTED == state, "The service is currently not running."); Tuple2<LeaderRetrievalService, JobLeaderService.JobManagerLeaderListener> entry = jobLeaderServices.remove(jobId); if (entry != null) { LOG.info("R...
java
public <T extends CacheSpec<K, V>> T removalListener(RemovalListener<K, V> listener) { this.removalListener = listener; return Cast.as(this); }
python
def InterpolateValue(self, value, type_info_obj=type_info.String(), default_section=None, context=None): """Interpolate the value and parse it with the appropriate type.""" # It is only possible to interpolate strings......
java
@Override public ZipkinDependencies rename(String name) { return new ZipkinDependencies(DSL.name(name), null); }
python
def default_estimate( opt_meth: Type[OptimizationMethod], mo_prob: MOProblem, dp: int = 2 ) -> Tuple[List[float], List[float]]: """ The recommended nadir/ideal estimator - use a payoff table and then round off the result. """ return round_off(estimate_payoff_table(opt_meth, mo_prob), dp)
python
def create_hist(self, evclass, evtype, xsep, energy, ctheta, fill_sep=False, fill_evtype=False): """Load into a histogram.""" nevt = len(evclass) ebin = utils.val_to_bin(self._energy_bins, energy) scale = self._psf_scale[ebin] vals = [energy, ctheta] ...
python
def get_aspect(cx, aspect_name): """Return an aspect given the name of the aspect""" if isinstance(cx, dict): return cx.get(aspect_name) for entry in cx: if list(entry.keys())[0] == aspect_name: return entry[aspect_name]
java
public static void generate(Configuration configuration) throws DocFileIOException { PackageListWriter packgen = new PackageListWriter(configuration); packgen.generatePackageListFile(configuration.docEnv); }
python
def _get_child_relation(self, child_pid): """Retrieve the relation between this node and a child PID.""" return PIDRelation.query.filter_by( parent=self._resolved_pid, child=child_pid, relation_type=self.relation_type.id).one()
java
protected void error(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Status errorStatus) throws ExternalAuthenticationException, IOException { this.error(httpRequest, httpResponse, new IdpErrorStatusException(errorStatus)); }
python
def new(self, url, clone_from=None, bare=True): """ Creates a new Repo instance. :param url: Path or remote URL of new repo. :param clone_from: Path or URL of repo to clone from. :param bare: Create as bare repo. :returns: grit.Repo instance. For example: ...
python
def collect(self, step, content): '''given a name of a configuration key and the provided content, collect the required metadata from the user. Parameters ========== step: the key in the configuration. Can be one of: user_message_<name> ...
java
public DelegateEbeanServer withDelegate(EbeanServer delegate) { this.delegate = delegate; this.delegateQuery = new DelegateQuery(delegate, this); this.save = new DelegateSave(delegate); this.delete = new DelegateDelete(delegate); this.bulkUpdate = new DelegateBulkUpdate(delegate); this.find = ne...
python
def reset(self): """ Resets terminal screen""" self._cli.reset() self._cli.buffers[DEFAULT_BUFFER].reset() self._cli.renderer.request_absolute_cursor_position() self._cli._redraw()
java
public Observable<ServiceResponse<ImageIds>> getAllImageIdsWithServiceResponseAsync(String listId) { if (this.client.baseUrl() == null) { throw new IllegalArgumentException("Parameter this.client.baseUrl() is required and cannot be null."); } if (listId == null) { throw n...
python
def reader(self, stream, context): """ Read lines from a subprocess' output stream and either pass to a progress callable (if specified) or write progress information to sys.stderr. """ progress = self.progress verbose = self.verbose while True: s = st...
java
public static IHEAuditor getAuditor(String className, boolean useGlobalConfig, boolean useGlobalContext) { Class<? extends IHEAuditor> clazz = AuditorFactory.getAuditorClassForClassName(className); return getAuditor(clazz,useGlobalConfig, useGlobalContext); }
java
static int processCx(final String str, final CxSmilesState state) { final CharIter iter = new CharIter(str); if (!iter.nextIf('|')) return -1; while (iter.hasNext()) { switch (iter.next()) { case '$': // atom labels and values // des...
python
def gmdaOnes(shape, dtype, mask=None, numGhosts=1): """ ghosted distributed array one constructor @param shape the shape of the array @param dtype the numpy data type @param numGhosts the number of ghosts (>= 0) """ res = GhostedMaskedDistArray(shape, dtype) res.mask = mask res.setNu...
python
def sep(a1, b1, a2, b2): """Angular spearation between two points on a unit sphere. This will be an angle between [0, π] radians. Parameters ---------- a1, b1 : float Longitude-like and latitude-like angles defining the first point. Both are in radians. a2, b2 : float ...
java
protected void addLongValue(Document doc, String fieldName, Object internalValue) { long longVal = ((Long)internalValue).longValue(); doc.add(createFieldWithoutNorms(fieldName, LongField.longToString(longVal), PropertyType.LONG)); }
python
def load_existing_json(): """ Look for an existing json under :meth:`logger.get_logger_dir()` named "stats.json", and return the loaded list of statistics if found. Returns None otherwise. """ dir = logger.get_logger_dir() fname = os.path.join(dir, JSONWriter.FILENAME) ...
python
def set_environment_variable(self, key, val): """ Sets a variable if that variable is not already set """ if self.get_environment_variable(key) in [None, val]: self.__dict__['environment_variables'][key] = val else: raise Contradiction("Could not set environment variable ...
java
private void setImageOrPlaceholder(ImageView iv, ImageHolder imageHolder) { //cancel previous started image loading processes DrawerImageLoader.getInstance().cancelImage(iv); //set the placeholder iv.setImageDrawable(DrawerImageLoader.getInstance().getImageLoader().placeholder(iv.getCont...
java
@SuppressWarnings("unchecked") public <S, D> ConditionalConverter<S, D> getFirstSupported(Class<?> sourceType, Class<?> destinationType) { ConditionalConverter<S, D> firstPartialMatchConverter = null; for (ConditionalConverter<?, ?> converter : converters) { MatchResult matchResult = conver...
python
def get_all_run_phy_intf(): """Retrieve all physical interfaces that are operationally up. """ intf_list = [] base_dir = '/sys/class/net' dir_exist = os.path.exists(base_dir) if not dir_exist: LOG.error("Unable to get interface list :Base dir %s does not " "exist", base_dir...
python
def build_sanitiser_node_dict( cfg, sinks_in_file ): """Build a dict of string -> TriggerNode pairs, where the string is the sanitiser and the TriggerNode is a TriggerNode of the sanitiser. Args: cfg(CFG): cfg to traverse. sinks_in_file(list[TriggerNode]): list of TriggerNodes co...
java
public PGPRGPgFlgs createPGPRGPgFlgsFromString(EDataType eDataType, String initialValue) { PGPRGPgFlgs result = PGPRGPgFlgs.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; }
python
def vectorize_utterance_ohe(self, utterance): """ Take in a tokenized utterance and transform it into a sequence of one-hot vectors """ for i, word in enumerate(utterance): if not word in self.vocab_list: utterance[i] = '<unk>' ie_utterance = self.swa...
java
public synchronized Object get(Object key) { ConcurrentHashMap<Object, Object> tableRef = primaryTable; Entry curEntry = (Entry) primaryTable.get(key); // Not found in primary if (curEntry == null) { tableRef = secondaryTable; curEntry = (Entry) secondaryTable.ge...
python
def run(self): """ Find and load step definitions, and them find and load features under `base_path` specified on constructor """ try: self.loader.find_and_load_step_definitions() except StepLoadingError, e: print "Error loading step definitions:\n", e ...
java
public static void main(String[] args) throws Exception { final ParameterTool params = ParameterTool.fromArgs(args); if (!params.has("lineitem") && !params.has("customer") && !params.has("orders")) { System.err.println(" This program expects data from the TPC-H benchmark as input data."); System.err.printl...
java
private void copydata(InputStream in, OutputStream out) throws java.io.IOException { long timestamp= 0; long byteCount = 0; while (true) { try { byteCount = copyBytes(in, out,-1); timestamp= 0; if (byteCount == -...
python
def new_run(self): """Creates a new RunData object and increments pointers""" self.current_run += 1 self.runs.append(RunData(self.current_run + 1))
java
private List<T> unmarshallResponseHeaderToList( JsonUnmarshallerContext context) throws Exception { String headerValue = context.readText(); List<T> list = new ArrayList<T>(); String[] headerValues = headerValue.split("[,]"); for (final String headerVal : headerValues) { ...
python
def upload_file(upload_url, upload_fields, filepath, callback=None): """Upload a pre-signed file to Cloudsmith.""" upload_fields = list(six.iteritems(upload_fields)) upload_fields.append( ("file", (os.path.basename(filepath), click.open_file(filepath, "rb"))) ) encoder = MultipartEncoder(upl...
java
protected void validateRegex(String field, String regExpression, String errorKey, String errorMessage) { validateRegex(field, regExpression, true, errorKey, errorMessage); }
java
public static String getHistoryLink(CmsObject cms, CmsUUID structureId, String version) { String resourcePath; CmsResource resource; try { resource = cms.readResource(structureId, CmsResourceFilter.ALL); resourcePath = resource.getRootPath(); } catch (CmsExceptio...
java
public Marshaller getMarshaller(boolean reuse) throws JAXBException { if (!reuse || this.marshaller == null) { Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_ENCODING, "U...
python
def _compute_relative_probs(self, prob_dict): """ computes the relative probabilities for every state """ for transition_counts in prob_dict.values(): summed_occurences = sum(transition_counts.values()) if summed_occurences > 0: for token in transition_counts.keys...
java
public void setExtent( JGTProcessingRegion region ) { west = region.getWest(); east = region.getEast(); south = region.getSouth(); north = region.getNorth(); rows = region.getRows(); cols = region.getCols(); fixResolution(); fixRowsAndCols(); }
java
public int addValue(Object[] array) { int val = hashCode(); for (Object obj : array) { val = addValue(obj); } return val; }
java
@Override public Configuration getInstance(String configTreePath) { PropertyConfiguration conf = new PropertyConfiguration(configTreePath); conf.dumpConfiguration(); return conf; }
java
public Set<SQLProperty> getPropertyBySimpleName(String propertyName) { if (propertyName == null) return null; return this.propertyBySimpleName.get(propertyName.toLowerCase()); }
java
private void updateSchema(Connection conn, DependencyVersion appExpectedVersion, DependencyVersion currentDbVersion) throws DatabaseException { if (connectionString.startsWith("jdbc:h2:file:")) { LOGGER.debug("Updating database structure"); final String updateFile = String.f...
java
public void setAssociationFilterList(java.util.Collection<AssociationFilter> associationFilterList) { if (associationFilterList == null) { this.associationFilterList = null; return; } this.associationFilterList = new com.amazonaws.internal.SdkInternalList<AssociationFilt...
python
def get_format_suffix(self, **kwargs): """ Determine if the request includes a '.json' style format suffix """ if self.settings.FORMAT_SUFFIX_KWARG: return kwargs.get(self.settings.FORMAT_SUFFIX_KWARG)
python
def send(channel, message, **kwargs): """ Site: https://slack.com API: https://api.slack.com Desc: real-time messaging """ headers = { "Content-type": "application/x-www-form-urlencoded", "User-Agent": "DBMail/%s" % get_version(), } username = from_unicode(kwargs.pop("us...
python
def is_nonlinear(self): """If nonlinear properties are specified.""" return any( isinstance(p, NonlinearProperty) for p in [self.mod_reduc, self.damping])
java
public void insert(StringBuilder buffer, Object value, int index) { if (buffer == null) { throw new NullPointerException("buffer"); } buffer.insert(index, value); }
java
public Address add(String... addressParts) { if (addressParts != null) { if ((addressParts.length % 2) != 0) { throw new IllegalArgumentException("address is incomplete: " + Arrays.toString(addressParts)); } if (addressParts.length > 0) { for ...
java
@Override public boolean route(RoutedMessage routedTrace) { boolean logNormally = true; RERWLOCK.readLock().lock(); try { // Cache message for WsTraceHandlers that haven't registered yet. if (earlierTraces != null) { earlierTraces.add(route...
java
public static ConfigParams fromTuples(Object... tuples) { StringValueMap map = StringValueMap.fromTuplesArray(tuples); return new ConfigParams(map); }
java
@Deprecated public static ManagedObjectReference createMOR(String type, String value) { return MorUtil.createMOR(type, value); }
python
def clean_project(self, app_name=None, delete_all=False): """ Delete objects in current project in OpenShift cluster. If both parameters are passed, delete all objects in project. :param app_name: str, name of app :param delete_all: bool, if true delete all objects in current pro...
java
@Override public void sessionOpened(IoSession session) throws Exception { log.debug("Session opened for sensor {}.", session); if (this.sensorIoAdapter != null) { this.sensorIoAdapter.sensorConnected(session); } }
python
def certify(self, subject, level=SignatureType.Generic_Cert, **prefs): """ Sign a key or a user id within a key. :param subject: The user id or key to be certified. :type subject: :py:obj:`PGPKey`, :py:obj:`PGPUID` :param level: :py:obj:`~constants.SignatureType.Generic_Cert`, :...
java
protected @Nullable String getSrcSetRenditions(@NotNull Media media, @NotNull MediaFormat mediaFormat, long @NotNull... widths) { StringBuilder srcset = new StringBuilder(); for (long width : widths) { Optional<String> url = media.getRenditions().stream() .filter(rendition -> Ratio.matches(rend...
python
def cache_epsilons(dstore, oq, assetcol, riskmodel, E): """ Do nothing if there are no coefficients of variation of ignore_covs is set. Otherwise, generate an epsilon matrix of shape (A, E) and save it in the cache file, by returning the path to it. """ if oq.ignore_covs or not riskmodel.covs: ...
java
private boolean isCopyModel(I_CmsDraggable draggable) { if (!(draggable instanceof CmsResultListItem)) { return false; } return ((CmsResultListItem)draggable).getResult().isCopyModel(); }
java
@BetaApi public final Operation abandonInstancesRegionInstanceGroupManager( ProjectRegionInstanceGroupManagerName instanceGroupManager, RegionInstanceGroupManagersAbandonInstancesRequest regionInstanceGroupManagersAbandonInstancesRequestResource) { AbandonInstancesRegionInstanceGroupManager...