language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def map_df(self, df): """ Map df """ if len(df) == 0: return aesthetics = set(self.aesthetics) & set(df.columns) for ae in aesthetics: df[ae] = self.map(df[ae]) return df
python
def _fileobj_lookup(self, fileobj): """Return a file descriptor from a file object. This wraps _fileobj_to_fd() to do an exhaustive search in case the object is invalid but we still have it in our map. This is used by unregister() so we can unregister an object that was previou...
python
def render_template(self, template, **kwargs): """ Use this method on your own endpoints, will pass the extra_args to the templates. :param template: The template relative path :param kwargs: arguments to be passed to the template """ kwargs["base...
java
private short getCellType(String value) { short ret = STRING_TYPE; if(value.equals("number")) ret = NUMBER_TYPE; else if(value.equals("datetime")) ret = DATETIME_TYPE; else if(value.equals("boolean")) ret = BOOLEAN_TYPE; return ret; }
java
public static Ifc4Factory init() { try { Ifc4Factory theIfc4Factory = (Ifc4Factory) EPackage.Registry.INSTANCE.getEFactory(Ifc4Package.eNS_URI); if (theIfc4Factory != null) { return theIfc4Factory; } } catch (Exception exception) { EcorePlugin.INSTANCE.log(exception); } return new Ifc4F...
java
public CertificateWithNonceDescriptionInner generateVerificationCode(String resourceGroupName, String resourceName, String certificateName, String ifMatch) { return generateVerificationCodeWithServiceResponseAsync(resourceGroupName, resourceName, certificateName, ifMatch).toBlocking().single().body(); }
java
public TableColumn copyBox() { TableColumn ret = new TableColumn(el, g, ctx); ret.copyValues(this); return ret; }
java
@Override public DeleteConferenceProviderResult deleteConferenceProvider(DeleteConferenceProviderRequest request) { request = beforeClientExecution(request); return executeDeleteConferenceProvider(request); }
java
public ClientTransaction sendRequest(Request request) throws SipException, TransactionUnavailableException { ensureCorrectDialogLocalTag(request); final ClientTransactionWrapper ctw = ra.getProviderWrapper().getNewDialogActivityClientTransaction(this,request); if (request.getMethod().equals(Request.INVITE)) la...
python
def initArgosApplicationSettings(app): # TODO: this is Argos specific. Move somewhere else. """ Sets Argos specific attributes, such as the OrganizationName, so that the application persistent settings are read/written to the correct settings file/winreg. It is therefore important to call this funct...
java
public static int getContainerPageTypeIdSafely() { try { return getContainerPageTypeId(); } catch (CmsLoaderException e) { if (LOG.isDebugEnabled()) { LOG.debug(e.getLocalizedMessage(), e); } return -1; } }
java
@Override public long getDuration() { final long end = running.get() ? System.nanoTime() : endTime.get(); return end - startTime.get(); }
python
def position_target_local_ned_encode(self, time_boot_ms, coordinate_frame, type_mask, x, y, z, vx, vy, vz, afx, afy, afz, yaw, yaw_rate): ''' Reports the current commanded vehicle position, velocity, and acceleration as specified by the autopilot. This sho...
java
public Map<String, Binding<?>> linkAll() { assertLockHeld(); if (linkedBindings != null) { return linkedBindings; } for (Binding<?> binding : bindings.values()) { if (!binding.isLinked()) { toLink.add(binding); } } linkRequested(); // This method throws if bindings are ...
python
def subquery(self, name=None): """ The recipe's query as a subquery suitable for use in joins or other queries. """ query = self.query() return query.subquery(name=name)
java
static String stripRules(String rules) { StringBuilder strippedRules = new StringBuilder(); int rulesLength = rules.length(); for (int idx = 0; idx < rulesLength;) { char ch = rules.charAt(idx++); if (ch == '#') { while (idx < rulesLength ...
java
protected Collection invokePage(int pPageIndex, int pPageSize) { if(mDao instanceof BaseSelectPageMapper) { return ((BaseSelectPageMapper)mDao).selectPage(createModel(),pPageIndex,pPageSize); } else if( mDao instanceof MysqlSelectPageMapper) { return ((Mys...
python
def _build(self, inputs, prev_state, **kwargs): """Connects the DeepRNN module into the graph. If this is not the first time the module has been connected to the graph, the Tensors provided as input_ and state must have the same final dimension, in order for the existing variables to be the correct siz...
python
def plot_d_delta_m(fignum, Bdm, DdeltaM, s): """ function to plot d (Delta M)/dB curves Parameters __________ fignum : matplotlib figure number Bdm : change in field Ddelta M : change in delta M s : specimen name """ plt.figure(num=fignum) plt.clf() if not isServer: ...
java
public static final void event(Object o, TraceComponent tc, String msg) { Tr.event(tc, getFullClassName(tc)+" "+getMEName(o) + " " + msg); }
java
@Restricted(DoNotUse.class) // WebOnly public HttpResponse doPlatformPluginList() throws IOException { SetupWizard setupWizard = Jenkins.get().getSetupWizard(); if (setupWizard != null) { if (InstallState.UPGRADE.equals(Jenkins.get().getInstallState())) { JSONArray initia...
python
def update(self, obj, size): '''Update this profile. ''' self.number += 1 self.total += size if self.high < size: # largest self.high = size try: # prefer using weak ref self.objref, self.weak = Weakref.ref(obj), True except Type...
python
def flanks(args): """ %prog flanks gaps.bed fastafile Create sequences flanking the gaps. """ p = OptionParser(flanks.__doc__) p.add_option("--extend", default=2000, type="int", help="Extend seq flanking the gaps [default: %default]") opts, args = p.parse_args(args) if...
python
def sphbear (lat1, lon1, lat2, lon2, tol=1e-15): """Calculate the bearing between two locations on a sphere. lat1 The latitude of the first location. lon1 The longitude of the first location. lat2 The latitude of the second location. lon2 The longitude of the second location...
java
public List<Object> stepsInstances(List<CandidateSteps> candidateSteps) { List<Object> instances = new ArrayList<>(); for (CandidateSteps steps : candidateSteps) { if (steps instanceof Steps) { instances.add(((Steps) steps).instance()); } } return ...
java
private int convertFocusDirectionToLayoutDirection(int focusDirection) { switch (focusDirection) { case View.FOCUS_BACKWARD: return RenderState.LAYOUT_START; case View.FOCUS_FORWARD: return RenderState.LAYOUT_END; case View.FOCUS_UP: ...
python
def _dispatch_container(self, textgroup, directory): """ Run the dispatcher over a textgroup within a try/except block .. note:: This extraction allows to change the dispatch routine \ without having to care for the error dispatching :param textgroup: Textgroup object that needs to...
python
def get_manifest_list_only_expectation(self): """ Get expectation for manifest list only :return: bool, expect manifest list only? """ if not self.workflow.postbuild_results.get(PLUGIN_GROUP_MANIFESTS_KEY): self.log.debug('Cannot check if only manifest list digest sh...
python
def _send_locked(self, cmd): """Sends the specified command to the lutron controller. Assumes self._lock is held. """ _LOGGER.debug("Sending: %s" % cmd) try: self._telnet.write(cmd.encode('ascii') + b'\r\n') except BrokenPipeError: self._disconnect_locked()
python
def reset(self): """Ensure all shards, configs, and routers are running and available.""" # Ensure all shards by calling "reset" on each. for shard_id in self._shards: if self._shards[shard_id].get('isReplicaSet'): singleton = ReplicaSets() elif self._shar...
python
def make_img_widget(cls, img, layout=Layout(), format='jpg'): "Returns an image widget for specified file name `img`." return widgets.Image(value=img, format=format, layout=layout)
python
def do_related(parser, token): """ Get N related models into a context variable optionally specifying a named related finder. **Usage**:: {% related <limit>[ query_type] [app.model, ...] for <object> as <result> %} **Parameters**:: ================================== ...
java
public GenericDataType[] getSchemaRow() { GenericDataType[] result = new GenericDataType[this.schemaRow.size()]; this.schemaRow.toArray(result); return result; }
python
def _private_packages_allowed(): """ Checks if the current user is allowed to create private packages. In the public cloud, the user needs to be on a paid plan. There are no restrictions in other deployments. """ if not HAVE_PAYMENTS or TEAM_ID: return True customer = _get_or_creat...
python
def _collect_data(self): """ Returns a list of all the data gathered from the engine iterable. """ all_data = [] for line in self.engine.run_engine(): logging.debug("Adding {} to all_data".format(line)) all_data.append(line.copy()) logg...
java
private void writeOpCode(@NonNull final BluetoothGattCharacteristic characteristic, @NonNull final byte[] value) throws DeviceDisconnectedException, DfuException, UploadAbortedException { writeOpCode(characteristic, value, false); }
java
protected void __invokeTag(int line, String name) { __engine.invokeTemplate(line, name, this, null, null, null); }
java
public void updateMorphTime(float delta) { for (int i=0;i<figures.size();i++) { Figure figure = (Figure) figures.get(i); MorphShape shape = (MorphShape) figure.getShape(); shape.updateMorphTime(delta); } }
python
def num_rows(self): """ Returns the number of rows. Returns ------- out : int Number of rows in the SFrame. """ if self._is_vertex_frame(): return self.__graph__.summary()['num_vertices'] elif self._is_edge_frame(): ret...
java
private void localChangeEnd(IManagedContext<?> managedContext, boolean silent, boolean deferCommit, ISurveyCallback callback) throws ContextException { if (pendingStack.isEmpty() || pendingStack.peek() != managedContext) { throw new ContextException("Illegal context ...
python
def master_for(self, service_name, redis_class=StrictRedis, connection_pool_class=SentinelConnectionPool, **kwargs): """ Returns a redis client instance for the ``service_name`` master. A SentinelConnectionPool class is used to retrive the master's address before esta...
java
public IType getByRelativeName(String relativeName, ITypeUsesMap typeUses) throws ClassNotFoundException { String relativeName1 = relativeName; IType type = FrequentUsedJavaTypeCache.instance( getExecutionEnv() ).getHighUsageType(relativeName1); if (type != null) { return type; } //## todo: co...
python
def validate_lang(ctx, param, lang): """Validation callback for the <lang> option. Ensures <lang> is a supported language unless the <nocheck> flag is set """ if ctx.params['nocheck']: return lang try: if lang not in tts_langs(): raise click.UsageError( "...
java
public Object invoke(MethodInvocation mi) throws Throwable { if (!Modifier.isPublic(mi.getMethod().getModifiers())) { return mi.proceed(); } Method searchMethod = mi.getMethod(); Object[] args = mi.getArguments(); String appid = AOPUtils.getFirstArgOfString(args); Method superMethod = null; Measured ...
python
def from_diff(diff, options=None, cwd=None): """Create a Radius object from a diff rather than a reposistory. """ return RadiusFromDiff(diff=diff, options=options, cwd=cwd)
python
def _geoid_radius(latitude: float) -> float: """Calculates the GEOID radius at a given latitude Parameters ---------- latitude : float Latitude (degrees) Returns ------- R : float GEOID Radius (meters) """ lat = deg2rad(latitude) return sqrt(1/(cos(lat) ** 2 / R...
python
def _send_and_receive(self, target, lun, netfn, cmdid, payload): """Send and receive data using RMCP interface. target: lun: netfn: cmdid: raw_bytes: IPMI message payload as bytestring Returns the received data as array. """ self._inc_sequence_nu...
python
def _add(self, uri, methods, handler, host=None, name=None): """Add a handler to the route list :param uri: path to match :param methods: sequence of accepted method names. If none are provided, any method is allowed :param handler: request handler function. When...
java
public FacebookPage addInstagramUser(String username) { ResourceParams parameterSet = newResourceParams(); parameterSet.set("id", username); parameterSet.set("type", "instagram_user"); return this; }
java
@Override protected boolean initiateClient() { String message = null; for (String host : hosts) { vaildateHostPort(host, port); Configuration hadoopConf = new Configuration(); hadoopConf.set("hbase.master", host + ":" + port); conn = HBaseP...
java
public void marshall(FacetAttributeDefinition facetAttributeDefinition, ProtocolMarshaller protocolMarshaller) { if (facetAttributeDefinition == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(facetAt...
python
def niggli_reduce(lattice, eps=1e-5): """Run Niggli reduction Args: lattice: Lattice parameters in the form of [[a_x, a_y, a_z], [b_x, b_y, b_z], [c_x, c_y, c_z]] eps: float: Tolerance to check if difference of norms of two basis ...
python
def _filter_attrs(self, feature, request): """ Remove some attributes from the feature and set the geometry to None in the feature based ``attrs`` and the ``no_geom`` parameters. """ if 'attrs' in request.params: attrs = request.params['attrs'].split(',') props = feat...
python
def get_unset_cache(self): """return : returns a tuple (num_of_not_None_caches, [list of unset caches endpoint]) """ caches = [] if self._cached_api_global_response is None: caches.append('global') if self._cached_api_ticker_response is None: caches.append...
python
def get_active_modifiers(self): """ Get a list of active keys. Uses XQueryKeymap. :return: list of charcodemap_t instances """ keys = ctypes.pointer(charcodemap_t()) nkeys = ctypes.c_int(0) _libxdo.xdo_get_active_modifiers( self._xdo, ctypes.byref(ke...
java
public T basic(String user, String password){ connection.setRequestProperty("Authorization", "Basic " + toBase64((user + ":" + password).getBytes())); return (T) this; }
python
def connect_ensime_server(self): """Start initial connection with the server.""" self.log.debug('connect_ensime_server: in') server_v2 = isinstance(self, EnsimeClientV2) def disable_completely(e): if e: self.log.error('connection error: %s', e, exc_info=True)...
java
public <T> T[] toArray(T[] a) { final ReentrantLock lock = this.lock; lock.lock(); try { return q.toArray(a); } finally { lock.unlock(); } }
java
public Collection<WsGetGroupsResult> getGroupsForSubjectId(final String subjectId) { try { val groupsClient = new GcGetGroups().addSubjectId(subjectId); val results = groupsClient.execute().getResults(); if (results == null || results.length == 0) { LOGGER.war...
java
public Set<Class<?>> findReferencedTypes(String typeName) { Set<Class<?>> referencedTypes = new HashSet<>(); // use the cached version if possible if (referencedTypesCache.containsKey(typeName)) { return referencedTypesCache.get(typeName); } try { CtClas...
python
def channel(self): """If no channel exists, a new one is requested.""" if not self._channel: self._channel_ref = weakref.ref(self.connection.get_channel()) return self._channel
java
public void setTarget( File target) { try { OutputStream targetStream = target==null? null : new FileOutputStream( target); setTarget( targetStream); } catch( Exception e) { throw new RuntimeException( "Can't create target stream", e); } }
python
def write_gif(dataset, filename, fps=10): """Write a NumPy array to GIF 89a format. Or write a list of NumPy arrays to an animation (GIF 89a format). - Positional arguments:: :param dataset: A NumPy arrayor list of arrays with shape rgb x rows x cols and integer values in ...
java
@Mode(TestMode.EXPERIMENTAL) @Test @AllowedFFDC // The tested exceptions cause FFDC so we have to allow for this. public void runFreshMasterBranchTck() throws Exception { File repoParent = new File(GIT_REPO_PARENT_DIR); File repo = new File(repoParent, GIT_REPO_NAME); MvnUtils.mvnC...
python
def is_valid_ipv6 (ip): """ Return True if given ip is a valid IPv6 address. """ # XXX this is not complete: check ipv6 and ipv4 semantics too here if not (_ipv6_re.match(ip) or _ipv6_ipv4_re.match(ip) or _ipv6_abbr_re.match(ip) or _ipv6_ipv4_abbr_re.match(ip)): return False ...
python
def effective_wavelength(self, binned=True, wavelengths=None, mode='efflerg'): """Calculate :ref:`effective wavelength <synphot-formula-effwave>`. Parameters ---------- binned : bool Sample data in native wavelengths if `False`. Else,...
java
void invokeAction(UrlInfo urlInfo, ResponseHelper responseHelper) throws ServletException { try { // May be there isn't any controller, so the page will be rendered // without calling any action if (urlInfo.getController() != null) { Strategy strategy = calcul...
java
public final <R extends Request<T>> R setShouldCache(boolean shouldCache) { checkIfActive(); this.shouldCache = shouldCache; return (R) this; }
python
def cli(env): """List options for creating Reserved Capacity""" manager = CapacityManager(env.client) items = manager.get_create_options() items.sort(key=lambda term: int(term['capacity'])) table = formatting.Table(["KeyName", "Description", "Term", "Default Hourly Price Per Instance"], ...
python
def _quickLevels(self, data): """ Estimate the min/max values of *data* by subsampling. """ while data.size > 1e6: ax = np.argmax(data.shape) sl = [slice(None)] * data.ndim sl[ax] = slice(None, None, 2) data = data[sl] return self._...
python
def get_zname(self, var, coords=None): """Get the name of the z-dimension This method gives the name of the z-dimension (which is not necessarily the name of the coordinate if the variable has a coordinate attribute) Parameters ---------- var: xarray.Variables ...
python
def Elasticsearch(*args, **kwargs): """Elasticsearch wrapper function Wrapper function around the official Elasticsearch class that adds a simple version check upon initialization. In particular it checks if the major version of the library in use match the one of the cluster that we are tring to i...
java
public String resolve(String key) { if (key.equals("HTTP_USER_AGENT")) { return request.getHeader("user-agent"); } else if (key.equals("HTTP_REFERER")) { return request.getHeader("referer"); } else if (key.equals("HTTP_COOKIE")) { return request.getHeader("coo...
python
def remove_event_source(event_source, lambda_arn, target_function, boto_session, dry=False): """ Given an event_source dictionary, create the object and remove the event source. """ event_source_obj, ctx, funk = get_event_source(event_source, lambda_arn, target_function, boto_session, dry=False) #...
python
def delimit_words(self): """This method takes the existing encoded binary string and returns a binary string that will pad it such that the encoded string contains only full bytes. """ bits_short = 8 - (len(self.buffer.getvalue()) % 8) #The string already falls o...
java
public List<PersonGroup> list(ListPersonGroupsOptionalParameter listOptionalParameter) { return listWithServiceResponseAsync(listOptionalParameter).toBlocking().single().body(); }
java
public void handleNotification(Notification notification, Object obj) { // handle JMX connection status notification if (notification instanceof JMXConnectionNotification) { JMXConnectionNotification jmxcNotification = (JMXConnectionNotification) notification; if (jmxcNotificatio...
java
private static <E extends Element> List<E> findTopLevelElementsRecurse(Class<E> elementType, Node node, List<E> matches) { for(Element elem : node.getChildElements()) { if(elementType.isInstance(elem)) { // Found match if(matches == null) matches = new ArrayList<>(); matches.add(elementType.cast(elem))...
java
@Override public List<Diagnostic> getDiagnostics(final int severity) { InputModel model = getComponentModel(); switch (severity) { case Diagnostic.ERROR: return model.errorDiagnostics; case Diagnostic.WARNING: return model.warningDiagnostics; case Diagnostic.INFO: return model.infoDiagnostics...
python
def gaps(args): """ %prog gaps agpfile Print out the distribution of gapsizes. Option --merge allows merging of adjacent gaps which is used by tidy(). """ from jcvi.graphics.histogram import loghistogram p = OptionParser(gaps.__doc__) p.add_option("--merge", dest="merge", default=False...
java
private synchronized void initializeAllFatClients() { updateCoordinatorMetadataWithLatestState(); // get All stores defined in the config file Map<String, Properties> storeClientConfigsMap = storeClientConfigs.getAllConfigsMap(); for(StoreDefinition storeDef: this.coordinatorMetadata.g...
python
def download(*packages, **kwargs): ''' Download packages to the local disk. refresh force a refresh if set to True. If set to False (default) it depends on zypper if a refresh is executed. root operate on a different root directory. CLI example: .. code-block:...
java
public ServiceCall<ValueCollection> listValues(ListValuesOptions listValuesOptions) { Validator.notNull(listValuesOptions, "listValuesOptions cannot be null"); String[] pathSegments = { "v1/workspaces", "entities", "values" }; String[] pathParameters = { listValuesOptions.workspaceId(), listValuesOptions.en...
python
def tags(self): """ :return: Returns tags from config and `JAEGER_TAGS` environment variable to use as process-wide tracer tags """ tags = self.config.get('tags', {}) env_tags = os.environ.get('JAEGER_TAGS', '') if env_tags: for kv in env_tags.split(',...
java
public static SingleItemSketch create(final byte[] data) { if ((data == null) || (data.length == 0)) { return null; } return new SingleItemSketch(hash(data, DEFAULT_UPDATE_SEED)[0] >>> 1); }
java
public static StringExpression groupConcat(Expression<String> expr) { return Expressions.stringOperation(SQLOps.GROUP_CONCAT, expr); }
java
public void destroy(GSSCredential credential, DestroyParams params) throws MyProxyException { if (credential == null) { throw new IllegalArgumentException("credential == null"); } if (params == null) { throw new IllegalArgumentException("...
python
def snmp_server_agtconfig_location(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp") agtconfig = ET.SubElement(snmp_server, "agtconfig") location = ET.Sub...
python
def btaddrtochars(addr): """ Takes a bluetooth address and returns a tuple with the corresponding char values. This can then be used to construct a IOBluetoothDevice object, providing the signature of the withAddress: selector has been set (as in _setpyobjcsignatures() in this module). For exam...
python
def parse(cls, src, dist=None): """Parse a single entry point from string `src` Entry point syntax follows the form:: name = some.module:some.attr [extra1, extra2] The entry name and module name are required, but the ``:attrs`` and ``[extras]`` parts are optional "...
java
@Override public com.liferay.commerce.product.type.virtual.model.CPDefinitionVirtualSetting createCPDefinitionVirtualSetting( long CPDefinitionVirtualSettingId) { return _cpDefinitionVirtualSettingLocalService.createCPDefinitionVirtualSetting(CPDefinitionVirtualSettingId); }
python
def ancovan(dv=None, covar=None, between=None, data=None, export_filename=None): """ANCOVA with n covariates. This is an internal function. The main call to this function should be done by the :py:func:`pingouin.ancova` function. Parameters ---------- dv : string Name of co...
python
def logged_timer(message): "Context manager for timing snippets of code. Echos to logging module." tick = time.time() yield tock = time.time() logging.info("%s: %.3f seconds", message, (tock - tick))
python
def _log_diff_memory_data(self, prefix, new_memory_data, old_memory_data): """ Computes and logs the difference in memory utilization between the given old and new memory data. """ def _vmem_used(memory_data): return memory_data['machine_data'].used def _proc...
python
def calc_evpo_v1(self): """Calculate land use and month specific values of potential evapotranspiration. Required control parameters: |NHRU| |Lnk| |FLn| Required derived parameter: |MOY| Required flux sequence: |ET0| Calculated flux sequence: |EvPo| A...
python
def visitTypeDirective(self, ctx: jsgParser.TypeDirectiveContext): """ directive: '.TYPE' name typeExceptions? SEMI """ self._context.directives.append('_CONTEXT.TYPE = "{}"'.format(as_token(ctx.name()))) self._context.has_typeid = True self.visitChildren(ctx)
java
public static NavigationAnimation create(MapPresenter mapPresenter, Trajectory trajectory, int millis) { return new NavigationAnimationImpl(mapPresenter.getViewPort(), mapPresenter.getEventBus(), trajectory, millis); }
java
private void replayLogs(Collection<TransactionLog> logs) { for (TransactionLog log : logs) { LOG.info("Replaying edits from transaction log " + log.getName()); int editCnt = 0; try { TransactionLogReader reader = log.getReader(); // reader may be null in the case of an empty file ...
python
def get_load(jid): ''' Return the load associated with a given job id ''' conn, mdb = _get_conn(ret=None) return mdb.jobs.find_one({'jid': jid}, {'_id': 0})
java
public void marshall(Category category, ProtocolMarshaller protocolMarshaller) { if (category == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(category.getCategoryId(), CATEGORYID_BINDING); ...