language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def chassis_info(self, chassis): """Get information about the specified chassis.""" if not chassis or not isinstance(chassis, str): raise RuntimeError('missing chassis address') self._check_session() status, data = self._rest.get_request('chassis', chassis) return dat...
python
def count_streets_per_node(G, nodes=None): """ Count how many street segments emanate from each node (i.e., intersections and dead-ends) in this graph. If nodes is passed, then only count the nodes in the graph with those IDs. Parameters ---------- G : networkx multidigraph nodes : iterabl...
python
def __managed_policy_map(self): """ This method is unused and a Work In Progress """ try: iam_client = boto3.client('iam') return ManagedPolicyLoader(iam_client).load() except Exception as ex: if self._offline_fallback: # If of...
java
public static void checkQuery(Query<?> query, Set<String> whitelist, Set<String> blacklist, InjectionManager manager) { ResourceInfo resource = manager.getInstance(ResourceInfo.class); Class<?> rc = resource.getResourceClass(); Set<String> wl = null, bl = null; ...
java
void performFlush() { // Conditions could have changed between enqueuing the task and when it is run. if (!shouldFlush()) { return; } logger.verbose("Uploading payloads in queue to Segment."); int payloadsUploaded = 0; Client.Connection connection = null; try { // Open a connect...
java
private YesNoDataType.Enum getYNQAnswer(Integer questionID) { String answer = getAnswer(questionID,answerHeaders); if (answer != null && !answer.equals(NOT_ANSWERED)) { return "Y".equals(answer) ? YesNoDataType.Y_YES : YesNoDataType.N_NO; } else { return n...
java
public void setTickMarkSectionsVisible(final boolean VISIBLE) { if (null == tickMarkSectionsVisible) { _tickMarkSectionsVisible = VISIBLE; fireUpdateEvent(REDRAW_EVENT); } else { tickMarkSectionsVisible.set(VISIBLE); } }
java
public final int applyUpgradesSince( int lastId, Context resources ) { int lastUpgradeId = lastId; for (UpgradeOperation op : operations) { if (op.getId() <= lastId) continue; LOGGER.debug("Upgrade {0}: starting", op); op.apply...
java
protected String subFormat(char ch, int count, int beginOffset, FieldPosition pos, DateFormatSymbols fmtData, Calendar cal) throws IllegalArgumentException { // Note: formatData is ignored return subFormat(ch, count, beginOffset, ...
java
public static Throwable getRootCause(Throwable t) { if (t == null) { return null; } while (t.getCause() != null) { t = t.getCause(); } return t; }
python
def with_name(self, name): """Sets the name scope for future operations.""" with self.g.as_default(), scopes.var_and_name_scope((name, None)) as ( name_scope, var_scope): return Layer(copy=self, name=self._name, scope=(name_scope, var_scope))
python
def _process_all_any(self, func, **kwargs): """Calculates if any or all the values are true. Return: A new QueryCompiler object containing boolean values or boolean. """ axis = kwargs.get("axis", 0) axis = 0 if axis is None else axis kwargs["axis"] = axis ...
java
public static byte[] sha256X16(String data, String encoding) { byte[] bytes = sha256(data, encoding); StringBuilder sha256StrBuff = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { if (Integer.toHexString(0xFF & bytes[i]).length() == 1) { sha256StrBuff.append("0").append( Integer.toHexSt...
java
private Cursor onGet(EnvKelp envKelp, RowCursor rowCursor, Boolean isFound) { if (Boolean.TRUE.equals(isFound)) { envKelp.test(rowCursor); CursorKraken cursor = new CursorKraken(table(), envKelp, rowCursor, _results); return cursor; } else { return null; } }
java
public com.google.cloud.datalabeling.v1beta1.LabelImageClassificationOperationMetadata getImageClassificationDetails() { if (detailsCase_ == 3) { return (com.google.cloud.datalabeling.v1beta1.LabelImageClassificationOperationMetadata) details_; } return com.google.cloud.datalabeling.v1...
java
private static boolean checkDownloadPath() { if (Checker.isNotEmpty(storageFolder)) { File file = new File(storageFolder); if (!file.exists() && file.mkdirs()) { logger.info("mkdir '" + storageFolder + "' success"); } return true; } ...
java
public void init(SessionImpl session, SessionDataManager itemMgr, QueryHandler handler, String statement, String language) throws InvalidQueryException { checkNotInitialized(); this.session = session; this.statement = statement; this.language = language; this.handler = handler; ...
python
def acl_remove_draft(self, id_vlan, type_acl): """ Remove Acl draft by type :param id_vlan: Identity of Vlan :param type_acl: Acl type v4 or v6 :return: None :raise VlanDoesNotExistException: Vlan Does Not Exist. :raise InvalidIdVlanExce...
python
def add_group(self, name, desc, status): """ Add a new group to a network. """ existing_group = get_session().query(ResourceGroup).filter(ResourceGroup.name==name, ResourceGroup.network_id==self.id).first() if existing_group is not None: raise HydraError("A resou...
java
public Map<String, Object> getCurrent() { Map<String, Object> result = null; QueryParameters params = innerGetCurrent(); result = processor.toMap(params); return result; }
java
@SuppressWarnings("unchecked") public <T> T[] getSpans(int queryStart, int queryEnd, Class<T> kind) { if (kind == null) return ArrayUtils.emptyArray(kind); int spanCount = mSpanCount; Object[] spans = mSpans; int[] starts = mSpanStarts; int[] ends = mSpanEnds; int[] ...
python
def seekend(self): """Set the current record position past the last vdata record. Subsequent write() calls will append records to the vdata. Args:: no argument Returns:: index of the last record plus 1 C library equivalent : no equivalent ...
python
def getTagMapNearPosition(self, idx): """Return ASN.1 types that are allowed at or past given field position. Some ASN.1 serialisation allow for skipping optional and defaulted fields. Some constructed ASN.1 types allow reordering of the fields. When recovering such objects it may be im...
python
def create_all_recommendations(self, cores, ip_views=False): """Calculate the recommendations for all records.""" global _store _store = self.store _create_all_recommendations(cores, ip_views, self.config)
java
@Override public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { throw f.unknown(); }
java
public static final int getShort(InputStream is) throws IOException { byte[] data = new byte[2]; is.read(data); return getShort(data, 0); }
python
def update(self): """ Updates topology Links are not deleted straightaway but set as "disconnected" """ from .link import Link # avoid circular dependency diff = self.diff() status = { 'added': 'active', 'removed': 'disconnected', ...
java
public void setMediaPackageSettings(java.util.Collection<MediaPackageOutputDestinationSettings> mediaPackageSettings) { if (mediaPackageSettings == null) { this.mediaPackageSettings = null; return; } this.mediaPackageSettings = new java.util.ArrayList<MediaPackageOutputD...
python
def page_view(self, data): """ Generator yields text to be displayed for the current unicode pageview. :param data: The current page's data as tuple of ``(ucs, name)``. :rtype: generator """ if self.term.is_a_tty: yield self.term.move(self.screen.row_begins, ...
java
@Override public GetCostForecastResult getCostForecast(GetCostForecastRequest request) { request = beforeClientExecution(request); return executeGetCostForecast(request); }
java
public static Extension newExtension(ObjectIdentifier extensionId, boolean critical, byte[] rawExtensionValue) throws IOException { Extension ext = new Extension(); ext.extensionId = extensionId; ext.critical = critical; ext.extensionValue = rawExtensionValue; return ext;...
python
def cache_control(self): """The Cache-Control general-header field is used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain. """ def on_update(cache_control): if not cache_control and 'cache-control' in self.headers:...
python
def south_field_triple(self): "Returns a suitable description of this field for South." from south.modelsinspector import introspector field_class = "django.db.models.fields.CharField" args, kwargs = introspector(self) return (field_class, args, kwargs)
java
static void addAttachObserver(HTMLElement element, ObserverCallback callback) { if (!ready) { startObserving(); } attachObservers.add(createObserver(element, callback, ATTACH_UID_KEY)); }
java
public static lbmonitor_binding[] get(nitro_service service, String monitorname[]) throws Exception{ if (monitorname !=null && monitorname.length>0) { lbmonitor_binding response[] = new lbmonitor_binding[monitorname.length]; lbmonitor_binding obj[] = new lbmonitor_binding[monitorname.length]; for (int i=0;i<...
python
def e(msg, *args, **kwargs): ''' log a message at error level; ''' return logging.log(ERROR, msg, *args, **kwargs)
java
protected PrivateKey getKey(KeyStore ks, String alias, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { return CertificateHelper.getKey(ks, alias, password); }
java
@VisibleForTesting boolean couldUseFlatGlob(Path fixedPath) { // Only works for filesystems where the base Hadoop Path scheme matches the underlying URI // scheme for GCS. if (!getUri().getScheme().equals(GoogleCloudStorageFileSystem.SCHEME)) { logger.atFine().log( "Flat glob is on, but do...
java
public Parameters omit(String... paths) { Parameters result = new Parameters(this); for (String path : paths) result.remove(path); return result; }
java
public void setReplicationInstancePrivateIpAddresses(java.util.Collection<String> replicationInstancePrivateIpAddresses) { if (replicationInstancePrivateIpAddresses == null) { this.replicationInstancePrivateIpAddresses = null; return; } this.replicationInstancePrivateIpA...
java
public static Result ok(URL object) { return status(Result.OK).render(new RenderableURL(object)); }
java
public final ListTopicSubscriptionsPagedResponse listTopicSubscriptions(String topic) { ListTopicSubscriptionsRequest request = ListTopicSubscriptionsRequest.newBuilder().setTopic(topic).build(); return listTopicSubscriptions(request); }
java
public static void main(final String[] args) { SortedIntArraySet s = new SortedIntArraySet(3); s.put(90); s.put(10); s.put(20); s.put(30); System.out.println("toString()=" + s.toString()); s.remove(10); s.put(40); System.out.println("toString()=" + s.toString()); System.out.println("first=" + s.firs...
java
public IntSet getNeighbors(int vertex) { EdgeSet<T> e = getEdgeSet(vertex); return (e == null) ? PrimitiveCollections.emptyIntSet() : PrimitiveCollections.unmodifiableSet(e.connected()); }
python
def flush_all(self) -> str: """ :return: """ # self.bytes_buffer.seek(0) # contents = self.bytes_buffer.read() # self.bytes_buffer.truncate(0) # self.bytes_buffer.seek(0) # if contents is None: # return '' contents = self.by...
java
public TaskCompletionEvent[] getTaskCompletionEvents(int startFrom ) throws IOException { ensureState(JobState.RUNNING); return info.getTaskCompletionEvents(startFrom); }
java
public String createParameterStringForSignature(Map<String, String> parameters) { if (parameters == null) { if (tc.isDebugEnabled()) { Tr.debug(tc, "Null parameters object provided; returning empty string"); } return ""; } Map<String, String> ...
java
private void inflateTabLayout(@NonNull final View headerView, @NonNull final View contentView) { LayoutInflater layoutInflater = LayoutInflater.from(getContext()); ViewGroup headerContentContainer = headerView.findViewById(R.id.header_content_container); ViewGroup contentContainer = contentView....
java
public static FileValue fileValue(File file){ String contentType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(file); return new FileValueBuilderImpl(file.getName()).file(file).mimeType(contentType).create(); }
java
public ByteSequenceIterator restartFrom(int node) { position = 0; bufferWrapper.clear(); nextElement = null; pushNode(node); return this; }
java
protected synchronized File getJsp() { if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINER)) { logger.logp(Level.FINER, CLASS_NAME, "getJsp", "enter"); } File[] children; try { if (_counter % _notify == 0) { i...
java
@Override public Enumeration<URL> findResources(final String name) throws IOException { if (name == null) { return null; } // On iOS, every resource is resolved by the SystemClassLoader, so // any URL in this class loader will, too. return Collections.enumeration(...
java
@Override public int executeBatch() { if (batchSize > 0) { boolean nodeAutoIndexingEnabled = indexer.isNodeAutoIndexingEnabled(factory.getConnection()); boolean relationshipAutoIndexingEnabled = indexer .isRelationshipAutoIndexingEnabled(factory.getCon...
python
def add_opt(self, opt, value=None): """ Add a option """ if value is not None: if not isinstance(value, File): value = str(value) self._options += [opt, value] else: self._options += [opt]
python
def main(): """ The main function that will be executed when running this as a stand alone script. """ my_name = os.path.basename(sys.argv[0]) if not my_name: my_name = "yhsm-validation-server" syslog.openlog(my_name, syslog.LOG_PID, syslog.LOG_LOCAL0) global args args = parse_a...
java
@Override public void afterServiceInvoke(Object serviceObject, boolean isSingleton, Object context) { @SuppressWarnings("unchecked") Map<Class<?>, ManagedObject<?>> newContext = (Map<Class<?>, ManagedObject<?>>) (context); ManagedObject<?> mo = newContext.get(serviceObject.getClass()); ...
python
def flux_consumers(F, rtol=1e-05, atol=1e-12): r"""Return indexes of states that are net flux producers. Parameters ---------- F : (n, n) ndarray Matrix of flux values between pairs of states. rtol : float relative tolerance. fulfilled if max(outflux-influx, 0) / max(outflux,influx)...
python
def end(self): """Mark the time at which this workunit ended.""" self.end_time = time.time() return self.path(), self.duration(), self._self_time(), self.has_label(WorkUnitLabel.TOOL)
java
AtomSymbol resize(double scaleX, double scaleY) { Point2D center = element.getCenter(); AffineTransform transform = new AffineTransform(); transform.translate(center.getX(), center.getY()); transform.scale(scaleX, scaleY); transform.translate(-center.getX(), -center.getY()); ...
java
public void recordPutTimeAndSize(long timeNS, long valueSize, long keySize) { recordTime(Tracked.PUT, timeNS, 0, valueSize, keySize, 0); }
python
def Main(): """The main program function. Returns: bool: True if successful or False if not. """ argument_parser = argparse.ArgumentParser( description='Validates dtFabric format definitions.') argument_parser.add_argument( 'source', nargs='?', action='store', metavar='PATH', default=None, ...
java
private String downJson(String url) { // 构造HttpClient的实例 HttpClient httpClient = new HttpClient(); // 创建GET方法的实例 GetMethod method = new GetMethod(url); try { // 执行GetMethod int statusCode = httpClient.executeMethod(method); LOGGER.info("响应代码:" ...
python
def householder(self): """Return Matrices u,b,v with self = ubv and b is in bidiagonal form The algorithm uses householder transformations. :return tuple (u,b,v): A tuple with the Matrix u, b and v. and self = ubv (except some rounding errors) u is a unitary mat...
python
def _add_layer_clicked(self): """Add layer clicked.""" layer = self.tree.selectedItems()[0] origin = layer.data(0, LAYER_ORIGIN_ROLE) if origin == FROM_ANALYSIS['key']: parent = layer.data(0, LAYER_PARENT_ANALYSIS_ROLE) key = layer.data(0, LAYER_PURPOSE_KEY_OR_ID_...
java
public static NetworkInterface getByInetAddress(InetAddress addr) throws SocketException { if (addr == null) { throw new NullPointerException(); } if (!(addr instanceof Inet4Address || addr instanceof Inet6Address)) { throw new IllegalArgumentException ("invalid address t...
java
DataSource lookupJtaDataSource() { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "lookupJtaDataSource : " + ivArchivePuId); DataSource jpaDS = getJPADataSource(ivJtaDataSourceJNDIName); if (isTraceOn && tc...
java
public static Executor monitor(MeterRegistry registry, String name, Tag... tags) { return monitor(registry, name, asList(tags)); }
python
def registerErrorHandler(f, ctx): """Register a Python written function to for error reporting. The function is called back as f(ctx, error). """ import sys if 'libxslt' not in sys.modules: # normal behaviour when libxslt is not imported ret = libxml2mod.xmlRegisterErrorHandler(f,ctx)...
java
public static List<Expression> transformArgsToList(String operator, Val<Expression>[] args) { List<Expression> et = Lists.newArrayListWithCapacity(args.length); for (Val<Expression> e : args) { if (e.object() instanceof Expression) { et.add(e.expr()); } else { ...
python
def drop_nan_columns(df, thresh=325): """Drop columns that are mostly NaNs Excel files can only have 256 columns, so you may have to drop a lot in order to get down to this """ if thresh < 1: thresh = int(thresh * df) return df.dropna(axis=1, thresh=thresh, inplace=False)
java
@Override protected PathHessian buildParentPath(QueryBuilder builder) { PathMapHessian pathMap = _parent.buildPathMap(builder); PathHessian subPath = pathMap.get(_name); if (subPath == null) { PathMapHessian pathMapSelf = buildPathMap(builder); subPath = new PathHessianField...
java
public static String removeChar(String s, char c) { int pos = s.indexOf(c); if (pos < 0) { return s; } StringBuilder sb = new StringBuilder(s.length() - 1); int prevPos = 0; do { sb.append(s, prevPos, pos); prevPos = pos + 1; pos = s.indexOf(c, pos + 1); } while (po...
python
def _make_A_and_part_of_b_adjacent(self, ref_crds): """ Make A and part of b. See docstring of this class for answer to "What are A and b?" """ rot = self._rotate_rows(ref_crds) A = 2*(rot - ref_crds) partial_b = (rot**2 - ref_crds**2).sum(1) return A, par...
java
@SuppressWarnings("unchecked") public static <T> Key<T> resolveKey(Class<T> injecteeClass, Class<? extends T> genericImplClass, Type... typeVariableClasses) { Optional<Annotation> qualifier = Annotations.on(genericImplClass) .findAll() .filter(AnnotationPredicates...
python
def logit(self, msg, pid, user, cname, priority=None): """Function for formatting content and logging to syslog""" if self.stream: print(msg, file=self.stream) elif priority == logging.WARNING: self.logger.warning("{0}[pid:{1}] user:{2}: WARNING - {3}".format(cname, pid,...
python
def save(self, filename): """ Saves the data for this settings instance to the given filename. :param filename | <str> """ dirname = os.path.dirname(filename) if not os.path.exists(dirname): os.makedirs(dirname) try: ...
java
private static void serializeElement(final String tag, final String content, final ContentHandler handler) throws SAXException { final AttributesImpl attributes = new AttributesImpl(); handler.startElement(null, tag, tag, attributes); handler.characters(content.toCharArray(), 0, content.length()); ...
python
def iterdecode(iterable, codec): """ Uses an incremental decoder to decode each chunk in iterable. This function is a generator. :param iterable: Iterable object which yields raw data to be decoded :param codec: An instance of codec """ decoder = codec.incrementaldecoder() for chunk in iter...
python
def should_handle(self, event_type, filename): """Check if an event should be handled. An event should be handled if a file in the searchpath was modified. :param event_type: a string, representing the type of event :param filename: the path to the file that triggered the event. ...
java
public void appendToFsb(org.apache.xml.utils.FastStringBuffer fsb) { XString xstring = (XString)xstr(); xstring.appendToFsb(fsb); }
python
def _make_request(self, request): """ Does the magic of actually sending the request and parsing the response """ # TODO: I'm sure all kinds of error checking needs to go here try: response_raw = urllib2.urlopen(request) except urllib2.HTTPError, e: ...
java
public static void basicExample003() throws Exception { // Generate a request again final SipRequest invite = SipRequest.invite("sip:alice@aboutsip.com") .withFromHeader("sip:bob@pkts.io") .build(); // Create a 200 OK to that INVITE and also add a generic ...
python
def windowed_sum_slow(arrays, span, t=None, indices=None, tpowers=0, period=None, subtract_mid=False): """Compute the windowed sum of the given arrays. This is a slow function, used primarily for testing and validation of the faster version of ``windowed_sum()`` Parameters --...
java
@Deprecated public void remove(final int rangeStart, final int rangeEnd) { if (rangeStart >= 0) { remove((long) rangeStart, (long) rangeEnd); } // rangeStart being -ve and rangeEnd being positive is not expected) // so assume both -ve remove(rangeStart & 0xFFFFFFFFL, rangeEnd & 0xFFFFFFFFL);...
python
def load_local_dataset(self, ds_str): ''' Returns a dataset instance for the local resource :param ds_str: Path to the resource ''' if cdl.is_cdl(ds_str): ds_str = self.generate_dataset(ds_str) if netcdf.is_netcdf(ds_str): return MemoizedDataset(...
java
Set<PolicyNodeImpl> getPolicyNodesExpected(int depth, String expectedOID, boolean matchAny) { if (expectedOID.equals(ANY_POLICY)) { return getPolicyNodes(depth); } else { return getPolicyNodesExpectedHelper(depth, expectedOID, matchAny); } }
java
private void insert(Geometry geom, GeometryIndex index, Geometry child) throws GeometryIndexNotFoundException { if (index.hasChild() && geom.getGeometries() != null && geom.getGeometries().length > index.getValue()) { insert(geom.getGeometries()[index.getValue()], index.getChild(), child); } else if (checkType(g...
java
private void readLinks2AccessTypes() throws CacheReloadException { Connection con = null; try { final List<Long> values = new ArrayList<>(); con = Context.getConnection(); PreparedStatement stmt = null; try { stmt = con.prepareS...
python
def clip_foreign(network): """ Delete all components and timelines located outside of Germany. Add transborder flows divided by country of origin as network.foreign_trade. Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA Returns ------- n...
python
def py_str2float(version): """Convert a Python version into a two-digit 'canonic' floating-point number, e.g. 2.5, 3.6. A runtime error is raised if "version" is not found. Note that there can be several strings that map to a single floating- point number. For example 3.2a1, 3.2.0, 3.2.2, 3.2.6 am...
java
public State state() { if (selectionsIterator == null) { return State.RESET; } else if (hasNext()) { return State.ITERATE; } else { return State.COMPLETE; } }
python
def authenticate(self, auth_url=None, **kwargs): """Authenticates a user via the Keystone Identity API.""" LOG.debug('Beginning user authentication') if not auth_url: auth_url = settings.OPENSTACK_KEYSTONE_URL auth_url, url_fixed = utils.fix_auth_url_version_prefix(auth_url...
python
def _make_query_from_terms(self, terms): """ Creates a query for dataset from decomposed search terms. Args: terms (dict or unicode or string): Returns: tuple: First element is str with FTS query, second is parameters of the query. """ expanded_terms =...
java
public void unsetScale() { double oldScale = scale; boolean oldScaleESet = scaleESet; scale = SCALE_EDEFAULT; scaleESet = false; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.UNSET, BpsimPackage.BETA_DISTRIBUTION_TYPE__SCALE, oldScale, SCALE_EDEFAULT, oldScaleESet)); }
python
def _method_complete(self, result): """Called after an extention method with the result.""" if isinstance(result, PrettyTensor): self._head = result return self elif isinstance(result, Loss): return result elif isinstance(result, PrettyTensorTupleMixin): self._head = result[0] ...
python
def cmd_usercheck(username, no_cache, verbose, wopen): """Check if the given username exists on various social networks and other popular sites. \b $ habu.usercheck portantier { "aboutme": "https://about.me/portantier", "disqus": "https://disqus.com/by/portantier/", "github": "h...
python
def sample_orbit(self, Npts=100, primary=None, trailing=True, timespan=None, useTrueAnomaly=True): """ Returns a nested list of xyz positions along the osculating orbit of the particle. If primary is not passed, returns xyz positions along the Jacobi osculating orbit (with mu = G*Minc, ...
python
def treenav_save_other_object_handler(sender, instance, created, **kwargs): """ This signal attempts to update the HREF of any menu items that point to another model object, when that objects is saved. """ # import here so models don't get loaded during app loading from django.contrib.contenttyp...
java
public PutObjectResponse putObject(PutObjectRequest request) { checkNotNull(request, "request should not be null."); assertStringNotNullOrEmpty(request.getKey(), "object key should not be null or empty"); InternalRequest internalRequest = this.createRequest(request, HttpMethodName.PUT); ...
java
public void println(String[] values) { for (int i = 0; i < values.length; i++) { print(values[i]); } out.println(); out.flush(); newLine = true; }