language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def zonalstats(features, raster, all_touched, band, categorical, indent, info, nodata, prefix, stats, sequence, use_rs): '''zonalstats generates summary statistics of geospatial raster datasets based on vector features. The input arguments to zonalstats should be valid GeoJSON Features. (see...
python
def change_weights(self): """ Changes the weights according to the error values calculated during backprop(). Learning must be set. """ dw_count, dw_sum = 0, 0.0 if len(self.cacheLayers) != 0: changeLayers = self.cacheLayers else: changeLay...
java
public static IJedisPool createJedisPool(String server, int timeout, int maxActive, String password) { if (maxActive <= 0) { maxActive = 128; } if (timeout <= 0) { timeout = 10000; } String[] serverInfo = server.split(":"); String host = serverInfo[0].trim(); int port; try { port =...
python
def _updateItemComboBoxIndex(self, item, column, num): """Callback for comboboxes: notifies us that a combobox for the given item and column has changed""" item._combobox_current_index[column] = num item._combobox_current_value[column] = item._combobox_option_list[column][num][0]
java
protected static boolean haveSameAspectRatio(RectF r1, RectF r2) { // Reduces precision to avoid problems when comparing aspect ratios. float srcRectRatio = MathUtils.truncate(MathUtils.getRectRatio(r1), 3); float dstRectRatio = MathUtils.truncate(MathUtils.getRectRatio(r2), 3); ...
python
def find_column(self, t): """ Returns token position in current text, starting from 1 """ cr = max(self.text.rfind(l, 0, t.lexpos) for l in self.line_terminators) if cr == -1: return t.lexpos + 1 return t.lexpos - cr
java
protected StyledString text(SarlAction element) { final JvmIdentifiableElement jvmElement = this.jvmModelAssociations.getDirectlyInferredOperation(element); final String simpleName = element.getName(); if (simpleName != null) { final QualifiedName qnName = QualifiedName.create(simpleName); final QualifiedNa...
python
def register(config, pconn): """ Do registration using basic auth """ username = config.username password = config.password authmethod = config.authmethod auto_config = config.auto_config if not username and not password and not auto_config and authmethod == 'BASIC': logger.debug...
java
@Nonnull @ReturnsMutableCopy public static byte [] decode (@Nonnull final byte [] aSource, final int nOfs, final int nLen, final int nOptions) throws IOException { // Lots of error checking and exception throwing ...
python
def query_saved_screenshot_info(self, screen_id): """Returns available formats and size of the screenshot from saved state. in screen_id of type int Saved guest screen to query info from. out width of type int Image width. out height of type int Ima...
python
def reset(vm_, **kwargs): ''' Reset a VM by emulating the reset button on a physical machine :param vm_: domain name :param connection: libvirt connection URI, overriding defaults .. versionadded:: 2019.2.0 :param username: username to connect with, overriding defaults .. versiona...
python
def get_vertex_string(self, i): """Return a string based on the atom number""" number = self.numbers[i] if number == 0: return Graph.get_vertex_string(self, i) else: # pad with zeros to make sure that string sort is identical to number sort return "%03...
java
public static <T, R extends Resource<T>> T getEntity(R resource) { return resource.getEntity(); }
python
def cli(env, snapshot_id): """Deletes a snapshot on a given volume""" file_storage_manager = SoftLayer.FileStorageManager(env.client) deleted = file_storage_manager.delete_snapshot(snapshot_id) if deleted: click.echo('Snapshot %s deleted' % snapshot_id)
python
def print_stack(pid, include_greenlet=False, debugger=None, verbose=False): """Executes a file in a running Python process.""" # TextIOWrapper of Python 3 is so strange. sys_stdout = getattr(sys.stdout, 'buffer', sys.stdout) sys_stderr = getattr(sys.stderr, 'buffer', sys.stderr) make_args = make_gd...
java
public static String getAction (String command) { int cidx = StringUtil.isBlank(command) ? -1 : command.indexOf(':'); return (cidx == -1) ? command : command.substring(cidx+1); }
java
public static <S extends Storable> Filter<S> filterFor(Class<S> type, String expression) { SoftValuedCache<Object, Filter<S>> filterCache = getFilterCache(type); synchronized (filterCache) { Filter<S> filter = filterCache.get(expression); if (filter == null) { ...
python
def get_plugin_actions(self): """Return a list of actions related to plugin.""" create_client_action = create_action( self, _("New console (default settings)"), icon=ima.icon('ipython_console'),...
java
private void loadCSVFile(TableDefinition tableDef, File file) throws IOException { try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), Utils.UTF8_CHARSET)) ) { loadCSVFromReader(tableDef, file.getAbsolutePath(), file.length(), reader); ...
python
def show_and_save_image(img, save_path): """Shows an image using matplotlib and saves it.""" try: import matplotlib.pyplot as plt # pylint: disable=g-import-not-at-top except ImportError as e: tf.logging.warning( "Showing and saving an image requires matplotlib to be " "installed: %s", e)...
python
def polygonize(self, width, cap_style_line=CAP_STYLE.flat, cap_style_point=CAP_STYLE.round): """Turns line or point into a buffered polygon.""" shape = self._shape if isinstance(shape, (LineString, MultiLineString)): return self.__class__( shape.buffer(width / 2, cap_...
python
def stutter(args): """ %prog stutter a.vcf.gz Extract info from lobSTR vcf file. Generates a file that has the following fields: CHR, POS, MOTIF, RL, ALLREADS, Q """ p = OptionParser(stutter.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_h...
python
def parseFASTAFilteringCommandLineOptions(args, reads): """ Examine parsed FASTA filtering command-line options and return filtered reads. @param args: An argparse namespace, as returned by the argparse C{parse_args} function. @param reads: A C{Reads} instance to filter. @return: The fi...
python
def transformer_decoder_layers(inputs, encoder_output, num_layers, hparams, self_attention_bias=None, encoder_decoder_attention_bias=None, ...
python
def _GetSourceFileSystem(self, source_path_spec, resolver_context=None): """Retrieves the file system of the source. Args: source_path_spec (dfvfs.PathSpec): source path specification of the file system. resolver_context (dfvfs.Context): resolver context. Returns: tuple: contai...
java
public void sendFlushedMessage(SIBUuid8 ignore, SIBUuid12 streamID) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "sendFlushedMessage", new Object[]{ignore, streamID}); ControlFlushed flushMsg = createControlFlushed(_targetMEUuid, ...
java
private <T extends ProgramElementDoc> void mapTypeParameters(Map<String,List<T>> map, Object doc, T holder) { TypeVariable[] typeVariables; if (doc instanceof ClassDoc) { typeVariables = ((ClassDoc) doc).typeParameters(); } else if (doc instanceof WildcardType) { ...
java
private static List<UserCustomColumn> createColumns() { List<UserCustomColumn> columns = new ArrayList<>(); columns.addAll(createRequiredColumns()); int index = columns.size(); columns.add(UserCustomColumn.createColumn(index++, COLUMN_NAME, GeoPackageDataType.TEXT, false, null)); columns.add(UserCustomC...
java
public void setTarget(String target) { ExtendedInfo info = getInfo(target); if (info != null) info._target = target; }
java
private synchronized void compile(Token tok) { if (this.operations != null) return; this.numberOfClosures = 0; this.operations = this.compile(tok, null, false); }
java
public void start() throws ServerLifecycleException { try { contextHandlerCollection.addHandler(contextHandler); contextHandlerCollection.mapContexts(); contextHandler.start(); LOG.info("WebDavServlet started: " + contextPath); } catch (Exception e) { throw new ServerLifecycleException("Servlet could...
java
public void readAcceleration(Callback<Acceleration> callback) { addCallback(BeanMessageID.CC_ACCEL_READ, callback); sendMessageWithoutPayload(BeanMessageID.CC_ACCEL_READ); }
java
public CloudhopperBuilder systemType(String... systemType) { for (String s : systemType) { if (s != null) { systemTypes.add(s); } } return this; }
java
@Override public boolean eIsSet(int featureID) { switch (featureID) { case SimpleExpressionsPackage.NOT_EXPRESSION__EXPRESSION: return expression != null; } return super.eIsSet(featureID); }
java
protected int readFully(InputStream in, byte buffer[]) throws java.io.IOException { for (int i = 0; i < buffer.length; i++) { int q = in.read(); if (q == -1) return i; buffer[i] = (byte)q; } return buffer.length; }
java
private void initJobs() { List<MasterSlaveNodeData> masterSlaveNodeDataList = masterSlaveApiFactory.nodeApi().getAllNodes(); if (!ListHelper.isEmpty(masterSlaveNodeDataList)) { return; } List<MasterSlaveJobData> masterSlaveJobDataList = new ArrayList<>(); try { ...
java
private void resetStoreDefinitions(Set<String> storeNamesToDelete) { // Clear entries in the metadata cache for(String storeName: storeNamesToDelete) { this.metadataCache.remove(storeName); this.storeDefinitionsStorageEngine.delete(storeName, null); this.storeNames.re...
python
def values(self): """return a list of all state values""" values = [] for __, data in self.items(): values.append(data) return values
java
@Override public RemoveListenerCertificatesResult removeListenerCertificates(RemoveListenerCertificatesRequest request) { request = beforeClientExecution(request); return executeRemoveListenerCertificates(request); }
java
public static String checkNotEmpty(String str, String message) { if (checkNotNull(str).isEmpty()) { throw new IllegalArgumentException(message); } return str; }
python
def zcross(seq, hysteresis=0, first_sign=0): """ Zero-crossing stream. Parameters ---------- seq : Any iterable to be used as input for the zero crossing analysis hysteresis : Crossing exactly zero might happen many times too fast due to high frequency oscilations near zero. To avoid this, you ...
python
def do_insertions(insertions, tokens): """ Helper for lexers which must combine the results of several sublexers. ``insertions`` is a list of ``(index, itokens)`` pairs. Each ``itokens`` iterable should be inserted at position ``index`` into the token stream given by the ``tokens`` argument...
python
def define_udp(self, name, valid_type, valid_components=None, default=None): """ Pre-define a user-defined property. This is the equivalent to the following RDL: .. code-block:: none property <name> { type = <valid_type>; component = <valid_...
java
public void setOrderFlags(final int flags) { orderFlags = Arrays. stream(BitfinexOrderFlag.values()) .filter(f -> ((f.getFlag() & flags) == f.getFlag())) .collect(Collectors.toSet()); }
python
def send_keys(self, element, x): """ Sends keys to the element. This method takes care of handling modifiers keys. To press and release a modifier key you must include it twice: once to press, once to release. """ ActionChains(self.driver) \ .send_keys_to_elem...
java
public Stream<T> stream() { if (thread == null) { synchronized (this) { if (thread == null) { thread = new Thread(() -> read(queue)); thread.setDaemon(true); thread.start(); } } } @Nullable final Iterator<T> iterator = new AsyncListIterator<>(queue, ...
java
public void init(PMContext context) throws Exception { // init default values if (getDriver() == null) { setDriver(DERBY_EMBEDDED_DRIVER); } if (getDatabaseType() == null) { setDatabaseType("derby"); } if (getUrl() == null) { setUrl("jd...
python
def validate_driver(f): """Check driver on""" def check_driver(request): drivers = get_all_driver() drivers = filter(drivers, request) if drivers: return f(request, drivers) else: raise Exception('Driver is not found') return check_driver
python
def on_error(self, headers, body): """ Increment the error count. See :py:meth:`ConnectionListener.on_error` :param dict headers: headers in the message :param body: the message content """ if log.isEnabledFor(logging.DEBUG): log.debug("received an error %s [...
java
public static TraceComponent register( Class<?> aClass, String group, String resourceBundleName) { return Tr.register(aClass, group, resourceBundleName); }
java
public static String extName(File file) { if (null == file) { return null; } if (file.isDirectory()) { return null; } return extName(file.getName()); }
java
public static ChronoFunction<Moment, PlainTimestamp> apparentAt(ZonalOffset offset) { return context -> { PlainTimestamp meanSolarTime = onAverage(context, offset); double eot = equationOfTime(context); long secs = (long) Math.floor(eot); int nanos = (int) ((eot ...
python
def get_response(self, url, timeout=None): """Return http request response. """ if not timeout: timeout = self.default_timeout if self.default_sleeptime: time.sleep(self.default_sleeptime) try: return self.auth.get(url, headers=self.default_h...
java
public static boolean isConfirmRemove() { Map<String, String> params = CmsCoreProvider.get().getAdeParameters(); String removeMode = params.get(PARAM_REMOVEMODE); return (removeMode == null) || removeMode.equals("confirm"); }
java
public Observable<ServiceResponse<Page<StampCapacityInner>>> listCapacitiesSinglePageAsync(final String resourceGroupName, final String name) { if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (na...
python
def dropna(self, dim, how='any', thresh=None, subset=None): """Returns a new dataset with dropped labels for missing values along the provided dimension. Parameters ---------- dim : str Dimension along which to drop missing values. Dropping along multiple...
java
public Range<T> intersectionWith(Range<T> other) { if (!this.isOverlappedBy(other)) { throw new IllegalArgumentException(String.format( "Cannot calculate intersection with non-overlapping range %s", other)); } if (this.equals(other)) { return this; } T min = this.comparator.compare(this.min, other.m...
java
public void registerCollectionSizeGauge( CollectionSizeGauge collectionSizeGauge) { String name = createMetricName(LocalTaskExecutorService.class, "queue-size"); metrics.register(name, collectionSizeGauge); }
python
def _api_path(self, item): """Get the API path for the current cursor position.""" if self.base_url is None: raise NotImplementedError("base_url not set") path = "/".join([x.blob["id"] for x in item.path]) return "/".join([self.base_url, path])
python
def trim_filter(filter, levels=1): '''Trim @ref levels levels from the front of each path in @filter.''' trimmed = [f[levels:] for f in filter] return [f for f in trimmed if f]
java
public void set(String key, String value) { if(key == null) throw new IllegalArgumentException("Null keys not allowed."); if(value == null) throw new IllegalArgumentException("Null values not allowed."); ArrayList<String> vals = new ArrayList<String>(); vals...
python
def _run(self): """Internal function to run the impact function with profiling.""" LOGGER.info('ANALYSIS : The impact function is starting.') step_count = len(analysis_steps) self.callback(0, step_count, analysis_steps['initialisation']) # Set a unique name for this impact ...
python
def check(self, check_url=None): """ Checks whether a server is running. :param str check_url: URL where to check whether the server is running. Default is ``"http://{self.host}:{self.port}"``. """ if check_url is not None: self.check_url = s...
java
protected void connectCloseToChannelClose() { nettyChannel.closeFuture() .addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { closeNow(); // Clos...
java
@Override protected void preparePaintComponent(final Request request) { super.preparePaintComponent(request); if (content != null) { switch (getMode()) { case EAGER: { // Always visible content.setVisible(true); AjaxHelper.registerContainer(getId(), getId() + "-content", content.getId()); ...
java
private WebSocketScope getScope(WebSocketConnection conn) { if (log.isTraceEnabled()) { log.trace("Scopes: {}", scopes); } log.debug("getScope: {}", conn); WebSocketScope wsScope; String path = conn.getPath(); if (!scopes.containsKey(path)) { // ch...
java
public List<double[]> addToClusteringCenters(List<double[]> clustering) { if (center != null && getClusteringFeature() != null) { clustering.add(getClusteringFeature().toClusterCenter()); } for (ClusteringTreeNode child : children) { child.addToClusteringCenters(clustering); } return clustering; }
java
public Observable<Void> deleteAtSubscriptionLevelAsync(String lockName) { return deleteAtSubscriptionLevelWithServiceResponseAsync(lockName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body();...
java
@Override public TableSchema getResultSetMetadata(OperationHandle opHandle) throws HiveSQLException { TableSchema tableSchema = sessionManager.getOperationManager() .getOperation(opHandle).getParentSession().getResultSetMetadata(opHandle); LOG.debug(opHandle + ": getResultSetMetadata()"); re...
python
def plot_clicked(self, event): """left-click chooses a cell, right-click flips cell to other view""" flip = False choose = False zoom = False replot = False items = self.win.scene().items(event.scenePos()) posx = 0 posy = 0 iplot = 0 if sel...
java
private Video generateRandomVideo() { Video video = new Video(); configureFavoriteStatus(video); configureLikeStatus(video); configureLiveStatus(video); configureTitleAndThumbnail(video); return video; }
python
def rot_from_vectors(start_vec, end_vec): """Return the rotation matrix to rotate from one vector to another.""" dot = start_vec.dot(end_vec) # TODO: check if dot is a valid number angle = math.acos(dot) # TODO: check if angle is a valid number cross = start_vec.cross(en...
java
private static void runExample( AdWordsServicesInterface services, AdWordsSession session, long merchantId, long budgetId, long userListId) throws IOException { Campaign campaign = createCampaign(services, session, merchantId, budgetId); System.out.printf( "Campaign w...
python
def _Open(self, path_spec=None, mode='rb'): """Opens the file-like object defined by path specification. Args: path_spec (PathSpec): path specification. mode (Optional[str]): file access mode. Raises: AccessError: if the access to open the file was denied. IOError: if the file-like...
java
public static boolean isPrimitiveFieldWithDefaultValue(final Object object, final Field field) throws IllegalAccessException { Class<?> fieldType = field.getType(); if (!fieldType.isPrimitive()) { return false; } Object fieldValue = getFieldValue(object, field); if (f...
python
def to_local(self, dt): """Convert any timestamp to local time (with tzinfo).""" if dt.tzinfo is None: dt = dt.replace(tzinfo=self.utc) return dt.astimezone(self.local)
python
def add_image(self, im): """ Add a image to a screenshot object """ for im_tmp in self.images: if im_tmp.kind == im.kind: self.images.remove(im_tmp) break self.images.append(im)
java
protected DataSource getDataSource( HttpServletRequest request, String key ) { // Return the requested data source instance return ( DataSource ) getServletContext().getAttribute( key + getModuleConfig().getPrefix() ); }
java
public void splitQueryAndUnescape(I invocation, byte []rawURIBytes, int uriLength) throws IOException { for (int i = 0; i < uriLength; i++) { if (rawURIBytes[i] == '?') { i++; // XXX: should be the host encoding? ...
java
@SuppressWarnings("unchecked") public <T extends ElementType> Character consume(T... expected) { Character lookahead = lookahead(1); for (ElementType type : expected) { if (type.isMatchedBy(lookahead)) { return consume(); } } throw new Unexpect...
java
public byte[] generate() { if (outputDex == null) { DexOptions options = new DexOptions(); options.minSdkVersion = DexFormat.API_NO_EXTENDED_OPCODES; outputDex = new DexFile(options); } for (TypeDeclaration typeDeclaration : types.values()) { outp...
java
protected Object[] getChildren() { if (mDebugVariables == null) { return null; } if (children != null) { return children; } Object[] returnc = new Object[mDebugVariables.size()]; int i = 0; for (DebugVariable debugVariable : mDebugVariables...
java
@Override public RegionLocator getRegionLocator(TableName tableName) throws IOException { RegionLocator locator = getCachedLocator(tableName); if (locator == null) { locator = new BigtableRegionLocator(tableName, getOptions(), getSession().getDataClientWrapper()) { @Override public Sam...
java
public void saveSoundPreferences(final boolean flush) { if (Strings.isNotEmpty(musicPreferences)) { if (Strings.isNotEmpty(soundVolumePreferenceName)) { saveInPreferences(musicPreferences, soundVolumePreferenceName, soundVolume); } if (Strings.isNotEmpty(sound...
java
private static long getLong(final char[] charArr, final int index, final int rem) { long out = 0L; for (int i = rem; i-- > 0;) { //i= 3,2,1,0 final char c = charArr[index + i]; out ^= (c & 0xFFFFL) << (i * 16); //equivalent to |= } return out; }
java
public static String getUnqualifiedKey (String qualifiedKey) { if (!qualifiedKey.startsWith(QUAL_PREFIX)) { throw new IllegalArgumentException( qualifiedKey + " is not a fully qualified message key."); } int qsidx = qualifiedKey.indexOf(QUAL_SEP); if (qsi...
java
@Beta public static <T> T checkIsInstance(Class<T> class_, Object reference) { return checkIsInstance(class_, reference, "Expected reference to be instance of %s, got %s", class_ == null ? "null" : class_.getName(), reference == null ? "null" : reference.getClass().getName()); }
java
@Override public void removePointOfInterest(PointOfInterest poi) { try { if (this.deletePoiLocStatement == null) { this.deletePoiLocStatement = this.conn.prepareStatement(DbConstants.DELETE_INDEX_STATEMENT); } if (this.deletePoiDataStatement == null) { ...
python
def translate_rects(self, rects): """ Translate rect position and size to screen coordinates. Respects zoom level. Will be returned in order passed as Rects. :return: list """ retval = list() append = retval.append sx, sy = self.get_center_offset() if s...
python
def import_egg(string): """ Import a controller class from an egg. Uses the entry point group "appathy.controller". """ # Split the string into a distribution and a name dist, _sep, name = string.partition('#') return pkg_resources.load_entry_point(dist, 'appathy.controller', name)
java
protected SAXReader createXmlReader() { SAXReader xmlReader = new SAXReader(); xmlReader.setMergeAdjacentText(true); xmlReader.setStripWhitespaceText(true); xmlReader.setIgnoreComments(true); try { xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype...
java
public LegalHoldInner setLegalHold(String resourceGroupName, String accountName, String containerName, List<String> tags) { return setLegalHoldWithServiceResponseAsync(resourceGroupName, accountName, containerName, tags).toBlocking().single().body(); }
java
public void marshall(GetAppRequest getAppRequest, ProtocolMarshaller protocolMarshaller) { if (getAppRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(getAppRequest.getAppId(), APPID_BINDING)...
java
public void open() { Futures.transform(lcm, new Subscribe(subscriber)); publishTask = Futures.transform(lcm, publisher); }
python
def _section_end_points(structure_block, id_map): '''Get the section end-points''' soma_idx = structure_block[:, TYPE] == POINT_TYPE.SOMA soma_ids = structure_block[soma_idx, ID] neurite_idx = structure_block[:, TYPE] != POINT_TYPE.SOMA neurite_rows = structure_block[neurite_idx, :] soma_end_pts...
java
@JRubyMethod(name = {"initialize", "reset"}, optional = 1) public static IRubyObject reset(IRubyObject self, IRubyObject[] args) { Ruby runtime = self.getRuntime(); ThreadContext ctx = runtime.getCurrentContext(); Emitter emitter = (Emitter)self.dataGetStructChecked(); Extra bonus = ...
python
def is_valid(self, t: URIRef) -> bool: """ Raise an exception if 't' is unrecognized :param t: metadata URI """ if not self.has_type(t): raise TypeError("Unrecognized FHIR type: {}".format(t)) return True
java
public long convertIPBytes(byte[] ipBytes) { if (ipBytes.length == 4) { long ipLong = (((long)ipBytes[0]) << 24); ipLong |= (((long)ipBytes[1]) << 16); ipLong |= (((long)ipBytes[2]) << 8); ipLong |= (long)ipBytes[3]; return ipLong; } re...
java
public void marshall(DeregisterRdsDbInstanceRequest deregisterRdsDbInstanceRequest, ProtocolMarshaller protocolMarshaller) { if (deregisterRdsDbInstanceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshalle...
python
async def helo(self, from_host=None): """ Sends a SMTP 'HELO' command. - Identifies the client and starts the session. If given ``from_host`` is None, defaults to the client FQDN. For further details, please check out `RFC 5321 § 4.1.1.1`_. Args: from_host ...