language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def inventory(self): """ Get inventory for all chassis. """ for chassis in self.chassis_list.values(): chassis.inventory(modules_inventory=True)
java
public void processFile(String fileName, boolean failOnFileNotFound) throws Exception { boolean fileFound = false; InputStream f = null; try { String furl = null; File file = new File(fileName); // files in filesystem if (!file.exists()) { URL url = classLoadHelper.getResource(fi...
java
public ScanRequest withScanFilter(java.util.Map<String, Condition> scanFilter) { setScanFilter(scanFilter); return this; }
java
private void scanTruncationSnapshots() { if (m_truncationSnapshotPath == null) { try { m_truncationSnapshotPath = new String(m_zk.getData(VoltZK.test_scan_path, false, null), "UTF-8"); } catch (Exception e) { return; } } Object...
python
def cli(env, title, subject_id, body, hardware_identifier, virtual_identifier, priority): """Create a support ticket.""" ticket_mgr = SoftLayer.TicketManager(env.client) if body is None: body = click.edit('\n\n' + ticket.TEMPLATE_MSG) created_ticket = ticket_mgr.create_ticket( title=tit...
java
public static double cosineOrHaversineDeg(double lat1, double lon1, double lat2, double lon2) { return cosineOrHaversineRad(deg2rad(lat1), deg2rad(lon1), deg2rad(lat2), deg2rad(lon2)); }
java
@Override public EClass getIfcOffsetCurve3D() { if (ifcOffsetCurve3DEClass == null) { ifcOffsetCurve3DEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(395); } return ifcOffsetCurve3DEClass; }
python
def MI_referenceNames(self, env, objectName, resultClassName, role): # pylint: disable=invalid-name """Return instance names of an association class. Implements the WBEM operation ReferenceNa...
java
public <T, E extends Exception> T doUntilResult(ExceptionalSupplier<T, E> task) throws InterruptedException, BackoffStoppedException, E { T result = task.get(); // give an immediate try return (result != null) ? result : retryWork(task); }
java
protected String getContextPath(){ if(context != null) return context; if(get("context_path") == null){ throw new ViewException("context_path missing - red alarm!"); } return get("context_path").toString(); }
python
def printSysLog(self, logString): """ Log one or more lines. Optionally, add them to logEntries list. Input: Strings to be logged. """ if zvmsdklog.LOGGER.getloglevel() <= logging.DEBUG: # print log only when debug is enabled if self.daemon =...
python
def _read_eeprom(self, address, size): '''Read EEPROM ''' self._intf.write(self._base_addr + self.CAL_EEPROM_ADD, array('B', pack('>H', address & 0x3FFF))) # 14-bit address, 16384 bytes n_pages, n_bytes = divmod(size, self.CAL_EEPROM_PAGE_SIZE) data = array('B') for _ i...
python
def prepare(self, strict=True): """ preparation for loaded json :param bool strict: when in strict mode, exception would be raised if not valid. """ self.__root = self.prepare_obj(self.raw, self.__url) self.validate(strict=strict) if hasattr(self.__root, 'schemes') and...
java
static Library getSharedLibrary(String id) { if (bundleContext == null) { return null; } // Filter the SharedLibrary service references by ID. String filter = "(" + "id=" + id + ")"; Collection<ServiceReference<Library>> refs = null; try { refs =...
python
def append_line(filename, **line): """Safely (i.e. with locking) append a line to the given file, serialized as JSON. """ global lock data = json.dumps(line, separators=(',', ':')) + '\n' with lock: with file(filename, 'a') as fp: fp.seek(0, SEEK_END) fp.write(da...
java
public static void wrongParameterNumber(String methodName, String className){ throw new ConversionParameterException(MSG.INSTANCE.message(conversionParameterException,methodName,className)); }
java
public final String getStartFormattedLong() { Granularity startGran = this.interval.getStartGranularity(); return formatStart(startGran != null ? startGran.getLongFormat() : null); }
java
@Override public StepStatus createStepStatus(long stepExecId) { logger.entering(CLASSNAME, "createStepStatus", stepExecId); Connection conn = null; PreparedStatement statement = null; StepStatus stepStatus = new StepStatus(stepExecId); try { conn = getConnection(); statement = conn.prepareState...
java
public static final String[] getKeywordValuesForLocale(String key, ULocale locale, boolean commonlyUsed) { // Note: The parameter commonlyUsed is not used. // The switch is in the method signature for consistency // with other locale ser...
python
def run(self, cmd, timeout=None, key=None): """ Run a command on the phablet device using ssh :param cmd: a list of strings to execute as a command :param timeout: a timeout (in seconds) for device discovery :param key: a path to a public ssh ...
python
def astype(self, dtype, copy=True): """ Cast to a NumPy array with 'dtype'. Parameters ---------- dtype : str or dtype Typecode or data-type to which the array is cast. copy : bool, default True Whether to copy the data, even if not necessary. If ...
python
def _set_request_user_id_metric(self, request): """ Add request_user_id metric Metrics: request_user_id """ if hasattr(request, 'user') and hasattr(request.user, 'id') and request.user.id: monitoring.set_custom_metric('request_user_id', request.user.id)
python
def from_ivorn(cls, ivorn, nside=256): """ Creates a `~mocpy.moc.MOC` object from a given ivorn. Parameters ---------- ivorn : str nside : int, optional 256 by default Returns ------- result : `~mocpy.moc.MOC` The resultin...
python
def get_version(self): # type: () -> str """ Retrieves the bundle version, using the ``__version__`` or ``__version_info__`` attributes of its module. :return: The bundle version, "0.0.0" by default """ # Get the version value version = getattr(self.__mod...
java
private String genReference(String id, ElementDefinition.TypeRefComponent typ) { ST shex_ref = tmplt(REFERENCE_DEFN_TEMPLATE); String ref = getTypeName(typ); shex_ref.add("id", id); shex_ref.add("ref", ref); references.add(ref); return shex_ref.render(); }
python
def _writeResponse(self, response, request, status=200): """ request -- request message response --- response message status -- HTTP Status """ request.setResponseCode(status) if self.encoding is not None: mimeType = 'text/xml; charset="%s"' % self.enc...
java
@VisibleForTesting public NamedType createNamedType( StaticTypedScope scope, String reference, String sourceName, int lineno, int charno) { return new NamedType(scope, this, reference, sourceName, lineno, charno); }
java
public ServiceFuture<AppServiceEnvironmentResourceInner> beginCreateOrUpdateAsync(String resourceGroupName, String name, AppServiceEnvironmentResourceInner hostingEnvironmentEnvelope, final ServiceCallback<AppServiceEnvironmentResourceInner> serviceCallback) { return ServiceFuture.fromResponse(beginCreateOrUpda...
java
public void addSession(String id, Session session) { synchronized (session) { SessionSchedulable schedulable = new SessionSchedulable(session, getType()); idToSession.put(id, schedulable); } }
java
public static Part buildFilePart(final String name, final File file) throws IOException { //Files.probeContentType(file.toPath()) always returns null due to unfixed jdk bug //using Tika to fetch file mime type instead final String type = new Tika().detect(file); final FileContent content = new FileContent(type,...
python
def xml_starttag (self, name, attrs=None): """ Write XML start tag. """ self.write(self.indent*self.level) self.write(u"<%s" % xmlquote(name)) if attrs: for name, value in attrs.items(): args = (xmlquote(name), xmlquoteattr(value)) ...
python
def _values(metadata, rel): """Searches a set <metadata> to find all relations <rel> Returns a list of the values of those relations (A list, because a rel can occur more than once)""" result = [] for r in metadata: if(r[REL] == rel): result.append(r[VAL]) return result
python
def _get_from_bin(self): """ Retrieves the Java library path according to the real installation of the java executable :return: The path to the JVM library, or None """ # Find the real interpreter installation path java_bin = os.path.realpath(self._java) ...
python
def _dispatch_commands(self, from_state, to_state, smtp_command): """This method dispatches a SMTP command to the appropriate handler method. It is called after a new command was received and a valid transition was found.""" #print from_state, ' -> ', to_state, ':', smtp_command ...
java
@Override public Map<String, List<String>> parameters() { Map<String, List<String>> result = new HashMap<>(); for (String key : request.params().names()) { result.put(key, request.params().getAll(key)); } return result; }
python
def get_plan_from_semi_dual(alpha, b, C, regul): """ Retrieve optimal transportation plan from optimal semi-dual potentials. Parameters ---------- alpha: array, shape = len(a) Optimal semi-dual potentials. b: array, shape = len(b) Second input histogram (should be non-negative a...
python
def read_bytes(self): """ reading bytes; update progress bar after 1 ms """ global exit_flag for self.i in range(0, self.length) : self.bytes[self.i] = i_max[self.i] self.maxbytes[self.i] = total_chunks[self.i] self.progress[self.i]["maximum"] = total_chunks[self.i] self.progress[self.i]["value"]...
java
public static String findEncodingFor(Writer w) { if (w instanceof OutputStreamWriter) { String enc = ((OutputStreamWriter) w).getEncoding(); /* [WSTX-146]: It is important that we normalize this, since * older JDKs return legacy encoding names ("UTF8" instead of ...
java
public static boolean verifyProjectType( SimpleFeatureType schema, IHMProgressMonitor pm ) { String searchedField = PipesTrentoP.ID.getAttributeName(); verifyFeatureKey(findAttributeName(schema, searchedField), searchedField, pm); searchedField = PipesTrentoP.DRAIN_AREA.getAttributeName(); ...
java
@Trivial // traced by caller public static CompletableFuture<Void> runAsync(Runnable action, Executor executor) { // Reject ManagedTask so that we have the flexibility to decide later how to handle ManagedTaskListener and execution properties if (action instanceof ManagedTask) throw new ...
java
private void detectImplmentedExtension() { if (isImplExtRegistered == false) { Object o = getThis(); Class thisClass = o.getClass(); // superclass interfaces Class[] declared = thisClass.getSuperclass().getInterfaces(); for (Class declare : dec...
java
public static Class getComponentJavaAccess(PageContext pc, Component component, RefBoolean isNew, boolean create, boolean writeLog, boolean suppressWSbeforeArg, boolean output, boolean returnValue) throws PageException { isNew.setValue(false); String classNameOriginal = component.getPageSource().getClassName(); ...
java
@RequestMapping(value="/{providerId}", method=RequestMethod.GET, params="error") public RedirectView oauth2ErrorCallback(@PathVariable String providerId, @RequestParam("error") String error, @RequestParam(value="error_description", required=false) String errorDescription, @RequestParam(value="error_uri", re...
java
@Override public void processXML() throws InjectionException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "processXML : " + this); List<? extends AdministeredObject> administeredObjectDefinitions = ivNameSp...
java
public ClassNode getClassNode() { if (classNode == null && GroovyObject.class.isAssignableFrom(theClass)) { // let's try load it from the classpath String groovyFile = theClass.getName(); int idx = groovyFile.indexOf('$'); if (idx > 0) { groovyFile...
python
def delete_vector(self, data, v=None): """ Deletes vector v and his id (data) in all matching buckets in the storage. The data argument must be JSON-serializable. """ # Delete data id in each hashes for lshash in self.lshashes: if v is None: k...
python
def _has_changed(instance): """ Check if some tracked fields have changed """ for field, value in instance._original_fields.items(): if field != 'pk' and \ not isinstance(instance._meta.get_field(field), ManyToManyField): try: if field in getattr(instance, ...
java
public Future<Map<String, Summoner>> getSummoners(String... names) { return new ApiFuture<>(() -> handler.getSummoners(names)); }
python
def handle_AnalysisRequest(self, instance): """Possible redirects for an AR. - If AR is sample_due: receive it before proceeding. - If AR belongs to Batch, redirect to the BatchBook view. - If AR does not belong to Batch: - if permission/workflow permit: go to AR manage_resul...
python
def solve_full(z, Fval, DPhival, G, A): M, N=G.shape P, N=A.shape """Total number of inequality constraints""" m=M """Primal variable""" x=z[0:N] """Multiplier for equality constraints""" nu=z[N:N+P] """Multiplier for inequality constraints""" l=z[N+P:N+P+M] """S...
java
public static void disposeSplash() { if (instance != null) { Container container = instance; while ((container = container.getParent()) != null) { if (container instanceof Window) ((Window)container).dispose(); } ins...
python
def status(ctx): """Print a status of this Lambda function""" status = ctx.status() click.echo(click.style('Policy', bold=True)) if status['policy']: line = ' {} ({})'.format( status['policy']['PolicyName'], status['policy']['Arn']) click.echo(click.style(line,...
python
def get(self, *args, **kwargs): """ Returns a single instance matching this query, optionally with additional filter kwargs. A DoesNotExistError will be raised if there are no rows matching the query A MultipleObjectsFoundError will be raised if there is more than one row matching the q...
python
def sign(self, byts): ''' Compute the ECC signature for the given bytestream. Args: byts (bytes): The bytes to sign. Returns: bytes: The RSA Signature bytes. ''' chosen_hash = c_hashes.SHA256() hasher = c_hashes.Hash(chosen_hash, default_...
python
def find_by_name(self, item_name, items_list, name_list=None): """ Return item from items_list with name item_name. """ if not name_list: names = [item.name for item in items_list if item] else: names = name_list if item_name in names: ...
python
def hash_array(vals, encoding='utf8', hash_key=None, categorize=True): """ Given a 1d array, return an array of deterministic integers. .. versionadded:: 0.19.2 Parameters ---------- vals : ndarray, Categorical encoding : string, default 'utf8' encoding for data & key when strings ...
java
public static appfwxmlcontenttype[] get_filtered(nitro_service service, String filter) throws Exception{ appfwxmlcontenttype obj = new appfwxmlcontenttype(); options option = new options(); option.set_filter(filter); appfwxmlcontenttype[] response = (appfwxmlcontenttype[]) obj.getfiltered(service, option); re...
java
public synchronized SSLConfig getOutboundDefaultSSLConfig() throws IllegalArgumentException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "getOutboundDefaultSSLConfig"); SSLConfig outboundDefaultSSLConfig = null; String outboundDefaultAlias = getGlo...
python
def _draw_lines(self, bg, colour, extent, line, xo, yo): """Draw a set of lines from a vector tile.""" coords = [self._scale_coords(x, y, extent, xo, yo) for x, y in line] self._draw_lines_internal(coords, colour, bg)
java
public static String queryEncode(String query, Charset charset) { return encodeReserved(query, FragmentType.QUERY, charset); /* spaces will be encoded as 'plus' symbols here, we want them pct-encoded */ // return encoded.replaceAll("\\+", "%20"); }
java
public <T> T update(InputHandler inputHandler, OutputHandler<T> outputHandler) throws SQLException { AssertUtils.assertNotNull(inputHandler, nullException()); AssertUtils.assertNotNull(outputHandler, nullException()); String sql = inputHandler.getQueryString(); return this.<T>update(th...
python
def is_friend(self): """:class:`bool`: Checks if the user is your friend. .. note:: This only applies to non-bot accounts. """ r = self.relationship if r is None: return False return r.type is RelationshipType.friend
java
public PhotoList<Photo> recentlyUpdated(Date minDate, Set<String> extras, int perPage, int page) throws FlickrException { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("method", METHOD_RECENTLY_UPDATED); parameters.put("min_date", Long.toString(minDate.getTi...
java
@Deprecated public static <V,T extends Exception> V impersonate(Authentication auth, Callable<V,T> body) throws T { SecurityContext old = impersonate(auth); try { return body.call(); } finally { SecurityContextHolder.setContext(old); } }
java
public double[] getMeanMonthly () { // --------------------------------------------- // Provides a per-month mean of data (across all years for that month). // e.g. 12 means returned- one for all days in January in all years, // one for all dats in Feb in all years, etc. ...
java
@Override public int removeAll(KTypePredicate<? super KType> predicate) { final int before = size(); if (hasEmptyKey) { if (predicate.apply(Intrinsics.<KType> empty())) { hasEmptyKey = false; values[mask + 1] = Intrinsics.<VType> empty(); } } final KType[] keys = Intrinsi...
java
public static MatFileHeader createHeader() { return new MatFileHeader( DEFAULT_DESCRIPTIVE_TEXT + (new Date()).toString(), DEFAULT_VERSION, DEFAULT_ENDIAN_INDICATOR, ByteOrder.BIG_ENDIAN ); }
java
private boolean isExternal(String filename) { boolean external = false; if (filename.indexOf("://") > 0) { external = true; } return external; }
java
@Override public GetUserAttributeVerificationCodeResult getUserAttributeVerificationCode(GetUserAttributeVerificationCodeRequest request) { request = beforeClientExecution(request); return executeGetUserAttributeVerificationCode(request); }
java
public boolean isPresolved() { // Check if the tool has added unsolved dependencies to this instance that need further resolution. boolean unsolvedDependenciesExist = getDirectDeps().stream().anyMatch(d -> !getTransientDeps(d).isEmpty()); return !unsolvedDependenciesExist; }
java
public static <T> String join(Iterator<T> iterator, CharSequence conjunction) { return IterUtil.join(iterator, conjunction); }
java
public void setPermissions(java.util.Collection<String> permissions) { if (permissions == null) { this.permissions = null; return; } this.permissions = new java.util.ArrayList<String>(permissions); }
python
def replace_pattern(name, pattern, repl, count=0, flags=8, bufsize=1, append_if_not_found=False, prepend_if_not_found=False, not_found_content=None, ...
python
def get_checkerboard_matrix(kernel_width, kernel_type="default", gaussian_param=0.1): """ example matrix for width = 2 -1 -1 1 1 -1 -1 1 1 1 1 -1 -1 1 1 -1 -1 :param kernel_type: :param kernel_width: :return: """ if kernel_type is "gaussian": ...
java
private Node tryMinimizeExprResult(Node n) { Node originalExpr = n.getFirstChild(); MinimizedCondition minCond = MinimizedCondition.fromConditionNode(originalExpr); MeasuredNode mNode = minCond.getMinimized(MinimizationStyle.ALLOW_LEADING_NOT); if (mNode.isNot()) { // Remove the leading NO...
python
def _TransmitBreakpointUpdates(self, service): """Tries to send pending breakpoint updates to the backend. Sends all the pending breakpoint updates. In case of transient failures, the breakpoint is inserted back to the top of the queue. Application failures are not retried (for example updating breakpo...
java
public Integer delInfoByIdListService(List<String> idList,String tableName){ int status=0; String tempDbType=calcuDbType(); String tempKeyId=calcuIdKey(); for(String id:idList){ int retStatus=getInnerDao().delObjByBizId(tableName, id, tempKeyId); status=status+retStatus; } return status; }
java
private static void appendThrown(StringBuilder message, LogRecord event) { final Throwable thrown = event.getThrown(); if (thrown != null) { final StringWriter sw = new StringWriter(); thrown.printStackTrace(new PrintWriter(sw)); message.append(sw);...
java
public java.util.List<DocumentServiceWarning> getWarnings() { if (warnings == null) { warnings = new com.amazonaws.internal.SdkInternalList<DocumentServiceWarning>(); } return warnings; }
python
def unstruct_strat(self): # type: () -> UnstructureStrategy """The default way of unstructuring ``attrs`` classes.""" return ( UnstructureStrategy.AS_DICT if self._unstructure_attrs == self.unstructure_attrs_asdict else UnstructureStrategy.AS_TUPLE )
java
@SuppressWarnings({"WeakerAccess", "unused"}) public void setDocumentPreserveAspectRatio(PreserveAspectRatio preserveAspectRatio) { if (this.rootElement == null) throw new IllegalArgumentException("SVG document is empty"); this.rootElement.preserveAspectRatio = preserveAspectRatio; ...
java
public void cleanupDisappearedTopology() throws Exception { StormClusterState clusterState = nimbusData.getStormClusterState(); List<String> activeTopologies = clusterState.active_storms(); if (activeTopologies == null) { return; } Set<String> cleanupIds = get_clean...
python
async def dbpoolStats(self, *args, **kwargs): """ Statistics on the Database client pool This method is only for debugging the ec2-manager This method is ``experimental`` """ return await self._makeApiCall(self.funcinfo["dbpoolStats"], *args, **kwargs)
java
@Override public DeleteTableVersionResult deleteTableVersion(DeleteTableVersionRequest request) { request = beforeClientExecution(request); return executeDeleteTableVersion(request); }
java
public static <K, V> QueuedKeyedResourcePool<K, V> create(ResourceFactory<K, V> factory, ResourcePoolConfig config) { return new QueuedKeyedResourcePool<K, V>(factory, config); }
java
@Override public CommerceSubscriptionEntry removeByC_C_C(String CPInstanceUuid, long CProductId, long commerceOrderItemId) throws NoSuchSubscriptionEntryException { CommerceSubscriptionEntry commerceSubscriptionEntry = findByC_C_C(CPInstanceUuid, CProductId, commerceOrderItemId); return remove(commerceSub...
python
def setupTxns(self, key, force: bool = False): """ Create base transactions :param key: ledger :param force: replace existing transaction files """ import data dataDir = os.path.dirname(data.__file__) # TODO: Need to get "test" and "live" from ENVS prope...
python
def coerce(val: t.Any, coerce_type: t.Optional[t.Type] = None, coercer: t.Optional[t.Callable] = None) -> t.Any: """ Casts a type of ``val`` to ``coerce_type`` with ``coercer``. If ``coerce_type`` is bool and no ``coercer`` specified it uses :func:`~django_...
python
def upper2_for_ramp_wall(self) -> Set[Point2]: """ Returns the 2 upper ramp points of the main base ramp required for the supply depot and barracks placement properties used in this file. """ if len(self.upper) > 5: # NOTE: this was way too slow on large ramps return set() # HAC...
java
@Pure @SuppressWarnings("static-method") public boolean isParameterExists(int index) { final String[] params = getCommandLineParameters(); return index >= 0 && index < params.length && params[index] != null; }
java
public void removeNodeMetaData(Object key) { if (key==null) throw new GroovyBugError("Tried to remove meta data with null key "+this+"."); if (metaDataMap == null) { return; } metaDataMap.remove(key); }
java
private static void displayResults(BufferedImage orig, Planar<GrayF32> distortedImg, ImageDistort allInside, ImageDistort fullView ) { // render the results Planar<GrayF32> undistortedImg = new Planar<>(GrayF32.class, distortedImg.getWidth(),distortedImg.getHeight(),distortedImg.getNumBa...
python
def rename_axis(self, mapper, axis, copy=True, level=None): """ Rename one of axes. Parameters ---------- mapper : unary callable axis : int copy : boolean, default True level : int, default None """ obj = self.copy(deep=copy) obj....
python
def genenare_callmap_sif(self, filepath): """ Generate a sif file from the call map """ graph = self.call_map if graph is None: raise AngrGirlScoutError('Please generate the call graph first.') f = open(filepath, "wb") for src, dst in graph.edges():...
python
def oem_name(self, value): """The oem_name property. Args: value (string). the property value. """ if value == self._defaults['ai.device.oemName'] and 'ai.device.oemName' in self._values: del self._values['ai.device.oemName'] else: sel...
java
public ServiceFuture<SummarizeResultsInner> summarizeForSubscriptionLevelPolicyAssignmentAsync(String subscriptionId, String policyAssignmentName, QueryOptions queryOptions, final ServiceCallback<SummarizeResultsInner> serviceCallback) { return ServiceFuture.fromResponse(summarizeForSubscriptionLevelPolicyAssig...
java
public Host getRandomHost(Set<Host> activeHosts) { Random random = new Random(); List<Host> hostsUp = new ArrayList<Host>(CollectionUtils.filter(activeHosts, new Predicate<Host>() { @Override public boolean apply(Host x) { return x.isUp(); } })); return hostsUp.get(random.nextInt(hostsUp.size())...
python
def scroll_deck(self, decknum, scroll_x, scroll_y): """Move a deck.""" self.scroll_deck_x(decknum, scroll_x) self.scroll_deck_y(decknum, scroll_y)
python
async def set_async(self, type_name, entity): """Sets an entity asynchronously using the API. Shortcut for using async_call() with the 'Set' method. :param type_name: The type of entity :param entity: The entity to set :raise MyGeotabException: Raises when an exception occurs on the MyG...
python
async def _executemany(self, query, dps, cursor): """ executemany """ result_map = None if isinstance(query, str): await cursor.executemany(query, dps) elif isinstance(query, DDLElement): raise exc.ArgumentError( "Don't mix sqla...