language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def p_var_decl(p): """ var_decl : DIM idlist typedef """ for vardata in p[2]: SYMBOL_TABLE.declare_variable(vardata[0], vardata[1], p[3]) p[0] = None
java
public void setKeepAliveConfiguration(KeepAliveConfiguration keepAliveConfiguration) { if(keepAliveConfiguration != null) client.setConnectionPool(new ConnectionPool(keepAliveConfiguration.getMaxIdleConnections(), keepAliveConfiguration.getKeepAliveDurationMs())); }
java
@Override public StopAutomationExecutionResult stopAutomationExecution(StopAutomationExecutionRequest request) { request = beforeClientExecution(request); return executeStopAutomationExecution(request); }
python
def _get_satellite_tile(self, x_tile, y_tile, z_tile): """Load up a single satellite image tile.""" cache_file = "mapscache/{}.{}.{}.jpg".format(z_tile, x_tile, y_tile) if cache_file not in self._tiles: if not os.path.isfile(cache_file): url = _IMAGE_URL.format(z_tile...
python
def parse_table(fq_table: str) -> Tuple[str, str]: """Parse a tablename into tuple(<schema>, <table>). Schema defaults to doc if the table name doesn't contain a schema. >>> parse_table('x.users') ('x', 'users') >>> parse_table('users') ('doc', 'users') """ parts = fq_table.split('.')...
python
def getBox(box, pagesize): """ Parse sizes by corners in the form: <X-Left> <Y-Upper> <Width> <Height> The last to values with negative values are interpreted as offsets form the right and lower border. """ box = str(box).split() if len(box) != 4: raise Exception("box not defined...
java
public static autoscaleprofile get(nitro_service service, String name) throws Exception{ autoscaleprofile obj = new autoscaleprofile(); obj.set_name(name); autoscaleprofile response = (autoscaleprofile) obj.get_resource(service); return response; }
python
def split_csp_str(val): """ Split comma separated string into unique values, keeping their order. :returns: list of splitted values """ seen = set() values = val if isinstance(val, (list, tuple)) else val.strip().split(',') return [x for x in values if x and not (x in seen or seen.add(x))]
java
public ValueHolder<V> resolve(ServerStoreProxy.ChainEntry entry, K key, long now) { return resolve(entry, key, now, 0); }
python
def snapshots(self, xml_bytes): """Parse the XML returned by the C{DescribeSnapshots} function. @param xml_bytes: XML bytes with a C{DescribeSnapshotsResponse} root element. @return: A list of L{Snapshot} instances. TODO: ownersSet, restorableBySet, ownerId, volumeSize, des...
python
def add_segmented_colorbar(da, colors, direction): """ Add 'non-rastered' colorbar to DrawingArea """ nbreak = len(colors) if direction == 'vertical': linewidth = da.height/nbreak verts = [None] * nbreak x1, x2 = 0, da.width for i, color in enumerate(colors): ...
java
protected boolean invokeTraceRouters(RoutedMessage routedTrace) { boolean retMe = true; LogRecord logRecord = routedTrace.getLogRecord(); /* * Avoid any feedback traces that are emitted after this point. * The first time the counter increments is the first pass-through. ...
python
def archive(self, ostream, treeish=None, prefix=None, **kwargs): """Archive the tree at the given revision. :param ostream: file compatible stream object to which the archive will be written as bytes :param treeish: is the treeish name/id, defaults to active branch :param prefix: is the...
java
public void marshall(DescribeInterconnectsRequest describeInterconnectsRequest, ProtocolMarshaller protocolMarshaller) { if (describeInterconnectsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.mars...
python
def ridgecircle(self, x, expo=0.5): """happy cat by HG Beyer""" a = len(x) s = sum(x**2) return ((s - a)**2)**(expo / 2) + s / a + sum(x) / a
java
public static String escapeStringForJsRegexp(String input) { JsString string = uncheckedCast(input); return string.replace(ESCAPE_JS_STRING_REGEXP, "\\$&"); }
python
def save_data(X, y, path): """Save data as a CSV, LibSVM or HDF5 file based on the file extension. Args: X (numpy or scipy sparse matrix): Data matrix y (numpy array): Target vector. If None, all zero vector will be saved. path (str): Path to the CSV, LibSVM or HDF5 file to save data. ...
python
def set_window_close_callback(window, cbfun): """ Sets the close callback for the specified window. Wrapper for: GLFWwindowclosefun glfwSetWindowCloseCallback(GLFWwindow* window, GLFWwindowclosefun cbfun); """ window_addr = ctypes.cast(ctypes.pointer(window), c...
java
private static boolean nonEmptyIntersection(String[] a, String[] b) { if (a == null || b == null || a.length == 0 || b.length == 0) { return false; } for (String toFind : a) { if (contains(b, toFind)) { return true; } } return false; }
python
def repo_groups(self, project_key, repo_key, limit=99999, filter_str=None): """ Get repository Groups :param project_key: :param repo_key: :param limit: OPTIONAL: The limit of the number of groups to return, this may be restricted by fixed system limit...
java
public static double meanTruncLower(double mu, double sigma, double lowerBound) { double alpha = (lowerBound - mu) / sigma; double phiAlpha = densityNonTrunc(alpha, 0, 1.0); double cPhiAlpha = cumulativeNonTrunc(alpha, 0, 1.0); return mu + sigma * phiAlpha / (1.0 - cPhiAlpha); }
java
public static double[] ttbd(double target, double[] lower, double[] upper, RandomGenerator randomGenerator) { // Check dimension match: if (lower.length != upper.length) { throw new IllegalArgumentException("Lower and upper bounds must be of same length."); } // Get indices ...
python
def geo_length(arg, use_spheroid=None): """ Compute length of a geo spatial data Parameters ---------- arg : geometry or geography use_spheroid : default None Returns ------- length : double scalar """ op = ops.GeoLength(arg, use_spheroid) return op.to_expr()
python
def validate_argsort_with_ascending(ascending, args, kwargs): """ If 'Categorical.argsort' is called via the 'numpy' library, the first parameter in its signature is 'axis', which takes either an integer or 'None', so check if the 'ascending' parameter has either integer type or is None, since 'asce...
python
def devices(self, timeout=None): """Executes adb devices -l and returns a list of objects describing attached devices. :param timeout: optional integer specifying the maximum time in seconds for any spawned adb process to complete before throwing an ADBTimeoutError. This timeou...
python
def resample(grid, wl, flux): """ Resample spectrum onto desired grid """ flux_rs = (interpolate.interp1d(wl, flux))(grid) return flux_rs
java
public void init(final SQLRouteResult routeResult) throws SQLException { setSqlStatement(routeResult.getSqlStatement()); getExecuteGroups().addAll(obtainExecuteGroups(routeUnits)); }
java
protected Cluster<BiclusterModel> defineBicluster(BitSet rows, BitSet cols) { ArrayDBIDs rowIDs = rowsBitsetToIDs(rows); int[] colIDs = colsBitsetToIDs(cols); return new Cluster<>(rowIDs, new BiclusterModel(colIDs)); }
python
def help_center_article_subscriptions(self, article_id, locale=None, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/subscriptions#list-article-subscriptions" api_path = "/api/v2/help_center/articles/{article_id}/subscriptions.json" api_path = api_path.format(article_id=artic...
python
def _get_shift_matrix(self): """np.array: The Camera's lens-shift matrix.""" return np.array([[1., 0., self.x_shift, 0.], [0., 1., self.y_shift, 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]], dtype=np.float32)
python
def validate(self, **kwargs): """ Validates each entry (passing the provided arguments down to them and also tries to resolve all cross-references between the entries. """ self.check_crossrefs() for value in self.values(): value.validate(**kwargs)
python
def child_(self, ctx): """ If the root resource is requested, return the primary application's front page, if a primary application has been chosen. Otherwise return 'self', since this page can render a simple index. """ if self.frontPageItem.defaultApplication i...
python
def tkvrsn(item): """ Given an item such as the Toolkit or an entry point name, return the latest version string. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tkvrsn_c.html :param item: Item for which a version string is desired. :type item: str :return: the latest version strin...
java
public static HtmlPage toHtmlPage(InputStream inputStream) { try { return toHtmlPage(IOUtils.toString(inputStream)); } catch (IOException e) { throw new RuntimeException("Error creating HtmlPage from InputStream.", e); } }
python
def copy(self): """Adds menus to itself, required by ViewBox""" # copied from pyqtgraph ViewBoxMenu m = QtGui.QMenu() for sm in self.subMenus(): if isinstance(sm, QtGui.QMenu): m.addMenu(sm) else: m.addAction(sm) m.setTitle(...
java
public static BigDecimal abs(EvaluationContext ctx, Object number) { return Conversions.toDecimal(number, ctx).abs(); }
python
def escape_html(text, escape_quotes=False): """Escape all HTML tags, avoiding XSS attacks. < => &lt; > => &gt; & => &amp: @param text: text to be escaped from HTML tags @param escape_quotes: if True, escape any quote mark to its HTML entity: " => &quot; ...
python
def getFileKeys(self): """ Retrieve a list of file keys that have been read into the database. This is a utility method that can be used to programmatically access the GsshaPy file objects. Use these keys in conjunction with the dictionary returned by the getFileObjects method. ...
python
def extract_ids(text, extractors): """ Uses `extractors` to extract citation identifiers from a text. :Parameters: text : str The text to process extractors : `list`(`extractor`) A list of extractors to apply to the text :Returns: `iterable` -- a generat...
java
public boolean isMaterialized(Object object) { IndirectionHandler handler = getIndirectionHandler(object); return handler == null || handler.alreadyMaterialized(); }
java
public static Instance findInstanceByPath( AbstractApplication application, String instancePath ) { Collection<Instance> currentList = new ArrayList<> (); if( application != null ) currentList.addAll( application.getRootInstances()); List<String> instanceNames = new ArrayList<> (); if( instancePath != null...
java
@Override public Node insertChildAt(Node toInsert, int index) { if (toInsert instanceof Element && getDocumentElement() != null) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Only one root element allowed"); } if (toInsert instanceof DocumentType &...
java
@Override public ListV2LoggingLevelsResult listV2LoggingLevels(ListV2LoggingLevelsRequest request) { request = beforeClientExecution(request); return executeListV2LoggingLevels(request); }
java
protected <T extends AbstractResource> void addStandardHeaders(URLConnection con, T resource) { con.setRequestProperty("User-Agent", userAgent); con.setRequestProperty("Accept", resource.getAcceptedTypes()); }
java
public static com.liferay.commerce.product.model.CPInstance updateCPInstance( com.liferay.commerce.product.model.CPInstance cpInstance) { return getService().updateCPInstance(cpInstance); }
java
private ConstraintNetwork[] samplingPeakCollection(HashMap<SymbolicVariableActivity, SpatialFluent> aTOsf) { Vector<SymbolicVariableActivity> observation = new Vector<SymbolicVariableActivity>(); Vector<SymbolicVariableActivity> activities = new Vector<SymbolicVariableActivity>(); for (SymbolicVariableActivity...
python
def play(self, sox_effects=()): """ Play the segment. """ audio_data = self.getAudioData() logging.getLogger().info("Playing speech segment (%s): '%s'" % (self.lang, self)) cmd = ["sox", "-q", "-t", "mp3", "-"] if sys.platform.startswith("win32"): cmd.extend(("-t", "waveaudio")) cmd.extend...
java
@NonNull public static <T> PutResults<T> newInstance(@NonNull Map<T, PutResult> putResults) { return new PutResults<T>(putResults); }
python
def get_lm_challenge_response(self): """ [MS-NLMP] v28.0 2016-07-14 3.3.1 - NTLM v1 Authentication 3.3.2 - NTLM v2 Authentication This method returns the LmChallengeResponse key based on the ntlm_compatibility chosen and the target_info supplied by the CHALLENGE_MESSAGE...
python
def getVariantAnnotationSet(self, id_): """ Returns the AnnotationSet in this dataset with the specified 'id' """ if id_ not in self._variantAnnotationSetIdMap: raise exceptions.AnnotationSetNotFoundException(id_) return self._variantAnnotationSetIdMap[id_]
java
public static <T> Level0ListOperator<List<T>,T> on(final List<T> target) { return onList(target); }
java
@Override public GetQualificationTypeResult getQualificationType(GetQualificationTypeRequest request) { request = beforeClientExecution(request); return executeGetQualificationType(request); }
java
public void setMessage(String message) { checkFrozen(); if (isEnabled() && CmsStringUtil.isEmptyOrWhitespaceOnly(message)) { throw new CmsIllegalArgumentException(Messages.get().container(Messages.ERR_LOGIN_MESSAGE_BAD_MESSAGE_0)); } m_message = message; }
python
def check_channel(fcn): """Decorator that ensures a valid channel passed in. Args: fcn (function): Function that has a ChannelResource as its second argument. Returns: (function): Wraps given function with one that checks for a valid channel. """ def wrapper(*args, **kwargs): ...
python
def message_handler(type_, from_): """ Deprecated alias of :func:`.dispatcher.message_handler`. .. deprecated:: 0.9 """ import aioxmpp.dispatcher return aioxmpp.dispatcher.message_handler(type_, from_)
java
private void saveToPropertyVfsBundle() throws CmsException { for (Locale l : m_changedTranslations) { SortedProperties props = m_localizations.get(l); LockedFile f = m_lockedBundleFiles.get(l); if ((null != props) && (null != f)) { try { B...
java
public static boolean isLineageEvent(GobblinTrackingEvent event) { String eventType = event.getMetadata().get(EVENT_TYPE); return StringUtils.isNotEmpty(eventType) && eventType.equals(LINEAGE_EVENT_TYPE); }
python
def get_edge_pathways(self, edge_id): """Get the pathways associated with an edge. Parameters ----------- edge_id : tup(int, int) Returns ----------- tup(str, str)|None, the edge as a pair of 2 pathways if the edge id is in this network """ ...
java
@Override public ExtendedSet<T> union(Collection<? extends T> other) { ExtendedSet<T> clone = clone(); clone.addAll(other); return clone; }
java
public static AdvancedCache failSilentReadCache(AdvancedCache cache) { return cache.withFlags( Flag.FAIL_SILENTLY, Flag.ZERO_LOCK_ACQUISITION_TIMEOUT ); }
python
def _create(self, rawtitle): """Create a page with this title, if it doesn't exist. This method first checks whether a page with the same slug (sanitized name) exists_on_disk. If it does, it doesn't do antyhing. Otherwise, the relevant attributes are created. Nothing is written ...
python
def compare(times_list=None, name=None, include_list=True, include_stats=True, delim_mode=False, format_options=None): """ Produce a formatted comparison of timing datas. Notes: If no times_list is provided, produces comparison reports on ...
java
public int read(byte []buffer, int offset, int length, long timeout) throws IOException { if (length == 0) { throw new IllegalArgumentException(); } long requestExpireTime = _requestExpireTime; if (requestExpireTime > 0 && requestExpireTime < CurrentTime.currentTime()) { close(); ...
java
public static boolean isValidJavaEncoding(String javaEncoding) { if (javaEncoding != null) { int length = javaEncoding.length(); if (length > 0) { for (int i = 1; i < length; i++) { char c = javaEncoding.charAt(i); if ((c < 'A' || c...
python
def vfr_hud_encode(self, airspeed, groundspeed, heading, throttle, alt, climb): ''' Metrics typically displayed on a HUD for fixed wing aircraft airspeed : Current airspeed in m/s (float) groundspeed : Current ground speed i...
java
public static Set<String> getTickets(Set<String> basedTickets, RoxableTest methodAnnotation, RoxableTestClass classAnnotation) { Set<String> tickets; if (basedTickets == null) { tickets = new HashSet<>(); } else { tickets = populateTickets(basedTickets, new HashSet<String>()); } if (classAnnotation...
python
def cut_selection(self): """ Return a (:class:`.Document`, :class:`.ClipboardData`) tuple, where the document represents the new document when the selection is cut, and the clipboard data, represents whatever has to be put on the clipboard. """ if self.selection: ...
python
def get_last_traded_dt(self, asset, dt): """ Get the latest minute on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : zipline.asset.Asset The asset for which to get the...
python
def parse(argv, level=0): """ Parse sub-arguments between `[` and `]` recursively. Examples -------- ``` >>> argv = ['--foo', 'bar', '--buz', '[', 'qux', '--quux', 'corge', ']'] >>> subarg.parse(argv) ['--foo', 'bar', '--buz', ['qux', '--quux', 'corge']] ``` Parameters ----...
python
def do_add_item(self, args): """Add item command help""" if args.food: add_item = args.food elif args.sport: add_item = args.sport elif args.other: add_item = args.other else: add_item = 'no items' self.poutput("You added {...
java
WritableByteChannel createInternal(URI path, CreateFileOptions options) throws IOException { // Validate the given path. false == do not allow empty object name. StorageResourceId resourceId = pathCodec.validatePathAndGetId(path, false); if (options.getExistingGenerationId() != StorageResourceId.UNKN...
python
def update_values(ims, image_id, iq_zeropt=True, comment=False, snr=False, commdict=None): """ Update a row in ossuary with :param ims: an ImageQuery, contains image table and a connector :param image_id: the primary key of the row to be updated :param iq_zeropt: Keyword set if iq and zeropoint are ...
java
private <T> T loadRequiredModel(Class<T> clzz, String location) throws MojoExecutionException { return ModelLoaderUtils.loadModel(clzz, getResourceLocation(location)); }
python
def update_letter(self, letter_id, letter_dict): """ Updates a letter :param letter_id: the letter id :param letter_dict: dict :return: dict """ return self._create_put_request( resource=LETTERS, billomat_id=letter_id, send_dat...
python
def get_objects_dex(self): """ Yields all dex objects inclduing their Analysis objects :returns: tuple of (sha256, DalvikVMFormat, Analysis) """ # TODO: there is no variant like get_objects_apk for digest, d in self.analyzed_dex.items(): yield digest, d, self...
python
def keyPressEvent(self, ev): """Check the event. Return True if processed and False otherwise """ if ev.key() in (Qt.Key_Shift, Qt.Key_Control, Qt.Key_Meta, Qt.Key_Alt, Qt.Key_AltGr, Qt.Key_CapsLock, Qt.Key_NumLock, Qt.Key_S...
java
public void addShardStart(TableDefinition tableDef, int shardNumber, Date startDate) { assert tableDef.isSharded() && shardNumber > 0; addColumn(SpiderService.termsStoreName(tableDef), SHARDS_ROW_KEY, Integer.toString(shardNumber), Utils.toBytes...
python
def run(self): """Start thread run here """ try: if self.command == "pxer": self.ipmi_method(command="pxe") if self.status == 0 or self.status == None: self.command = "reboot" else: return ...
java
private JSONObject addAttributeFromSingleValue(HistoryKey pKey, String pAttrName, Object pValue, long pTimestamp) { HistoryEntry entry = getEntry(pKey,pValue,pTimestamp); return entry != null ? addToHistoryEntryAndGetCurrentHistory(new JSONObject(), entry, pAttrName, pValue, pTimestamp) ...
python
def bfd_parse(data): """ Parse raw packet and return BFD class from packet library. """ pkt = packet.Packet(data) i = iter(pkt) eth_pkt = next(i) assert isinstance(eth_pkt, ethernet.ethernet) ipv4_pkt = next(i) assert isinstance(ipv4_pkt, ipv4.ip...
java
private void preDelete(User user) throws Exception { for (UserEventListener listener : listeners) { listener.preDelete(user); } }
python
def assign_reads_to_database(query, database_fasta, out_path, params=None): """Assign a set of query sequences to a reference database database_fasta_fp: absolute file path to the reference database query_fasta_fp: absolute file path to query sequences output_fp: absolute file path of the file to be ou...
java
public void free() { if (BaseApplet.getSharedInstance() != null) if (BaseApplet.getSharedInstance().getApplet() == null) if (this.getParent() != null) this.getParent().remove(this); // Remove from frame if (this.getHelpView() != null) this.getHelpView().fr...
java
public static Point spin(Point point, double angle) { return spin(Collections.singletonList(point), angle).get(0); }
java
private MappedClass addMappedClass(final MappedClass mc, final boolean validate) { addConverters(mc); if (validate && !mc.isInterface()) { mc.validate(this); } mappedClasses.put(mc.getClazz().getName(), mc); Set<MappedClass> mcs = mappedClassesByCollection.get(mc.g...
python
def username(elk, user_number): """Return name of user.""" if user_number >= 0 and user_number < elk.users.max_elements: return elk.users[user_number].name if user_number == 201: return "*Program*" if user_number == 202: return "*Elk RP*" if user_number == 203: return...
python
def compile_results(self): """Compile all results for the current test """ self._init_dataframes() self.total_transactions = len(self.main_results['raw']) self._init_dates()
java
@Path("{tunnel}") public TunnelResource getTunnel(@PathParam("tunnel") String tunnelUUID) throws GuacamoleException { Map<String, UserTunnel> tunnels = session.getTunnels(); // Pull tunnel with given UUID final UserTunnel tunnel = tunnels.get(tunnelUUID); if (tunnel == ...
python
def setup_dns(endpoint): """Setup site domain to route to static site""" print("Setting up DNS...") yass = Yass(CWD) target = endpoint.lower() sitename = yass.sitename if not sitename: raise ValueError("Missing site name") endpoint = yass.config.get("hosting.%s" % target) if n...
java
@Override public void closeLog() throws InternalLogException { if (tc.isEntryEnabled()) Tr.entry(tc, "closeLog", this); if (_logHandle != null) { // Only try to keypoint the recovery log if its in a valid state. If the service // is closing the log in...
java
@Override public boolean isSystem() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { SibTr.entry(tc, "isSystem"); SibTr.exit(tc, "isSystem", Boolean.valueOf(_isSystem)); } return _isSystem; }
java
public static FunctionalType primitiveUnaryOperator(PrimitiveType type) { switch (type.getKind()) { case INT: return new FunctionalType( Type.from(IntUnaryOperator.class), "applyAsInt", ImmutableList.of(type), type); case LONG: return new ...
java
private MatchedPair doMatch( SessionSchedulable schedulable, long now, long nodeWait, long rackWait) { schedulable.adjustLocalityRequirement(now, nodeWait, rackWait); for (LocalityLevel level : neededLocalityLevels) { if (level.isBetterThan(schedulable.getLastLocality())) { /** * Th...
python
def _init(self): """ Convert model metadata to class attributes. This function is called automatically after ``define()`` in new versions. :return: None """ assert self._name assert self._group # self.n = 0 self.u = [] self.name ...
python
def calculate_covariance_matrix(X): """Calculates the Variance-Covariance matrix Parameters: ----------- X : array-like, shape (m, n) - the data Returns: -------- variance_covariance_matrix : array-like, shape(n, n) """ n_features = X.shape[1] S = np.zeros((n_...
java
protected void evaluateFinalAuthentication(final AuthenticationBuilder builder, final AuthenticationTransaction transaction, final Set<AuthenticationHandler> authenticationHandlers) throws AuthenticationException { if ...
python
def parseEntityRef(self): """parse ENTITY references declarations [68] EntityRef ::= '&' Name ';' [ WFC: Entity Declared ] In a document without any DTD, a document with only an internal DTD subset which contains no parameter entity references, or a document with "stand...
java
protected void defaultFindOrderBy(Query<MODEL> query) { if (StringUtils.isNotBlank(defaultFindOrderBy)) { // see if we should use the default orderBy clause OrderBy<MODEL> orderBy = query.orderBy(); if (orderBy.isEmpty()) { query.orderBy(defaultFindOrderBy); ...
java
public static boolean is_pavargadi(String str) { String s1 = VarnaUtil.getAdiVarna(str); if (is_pavarga(s1)) return true; return false; }
java
public ApiResponse apiRequest(HttpMethod method, Map<String, Object> params, Object data, String... segments) { ApiResponse response = null; try { response = httpRequest(method, ApiResponse.class, params, data, segments); log.info("Client.apiReques...