language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static <T> T instantiate(final Class<T> tClass, final T defaultEntity) { final T t = instantiate(tClass); return (t == null) ? defaultEntity : t; }
python
def reg(self, data: ['SASdata', str] = None, add: str = None, by: str = None, code: str = None, id: str = None, lsmeans: str = None, model: str = None, out: [str, bool, 'SASdata'] = None, random: str = None, repe...
java
@Override public UserToUserInformationMessage createUSR() { UserToUserInformationMessage msg = new UserToUserInformationMessageImpl(_U2U_HOLDER.mandatoryCodes, _U2U_HOLDER.mandatoryVariableCodes, _U2U_HOLDER.optionalCodes, _U2U_HOLDER.mandatoryCodeToIndex, _U2U_HOLDER.mandato...
java
public ManagedBuffer getBlockData( String appId, String execId, int shuffleId, int mapId, int reduceId) { ExecutorShuffleInfo executor = executors.get(new AppExecId(appId, execId)); if (executor == null) { throw new RuntimeException( String.format("Executor is not reg...
python
def get_prt_fmt(self, alt=False): """Return the format for printing GO named tuples and their related information.""" # prt_fmt = [ # rcnt # '{GO} # {NS} L{level:02} D{depth:02} {GO_name}', # '{GO} # {NS} {dcnt:6,} L{level:0...
java
public static Instant lastInstant(Instant instant, Schedule schedule) { final ExecutionTime executionTime = ExecutionTime.forCron(cron(schedule)); final ZonedDateTime utcDateTime = instant.atZone(UTC); // executionTime.isMatch ignores seconds for unix cron // so we fail the check immediately if there i...
java
@Requires({ "method != null", "parameters != null", "!parameters.contains(null)" }) public static void copyParameters(MethodModel method, List<? extends VariableModel> parameters) { ArrayList<VariableModel> list = new ArrayList<VariableModel>(parameters); for ...
java
public static void main( String [] args ) throws IOException { String filename = args[0]; String param = args[1]; String value = args[2]; try (FileReader fr = new FileReader( filename )) { String templateText = SimpleTemplate.getStringFromStream( fr ); Simple...
python
def detect(self, color_im, depth_im, cfg, camera_intr, T_camera_world, vis_foreground=False, vis_segmentation=False, segmask=None): """Detects all relevant objects in an rgbd image pair using foreground masking. Parameters ---------- color_im : :obj:`ColorI...
java
@Action(name = "List Item Grabber", outputs = { @Output(RESULT_TEXT), @Output(RESPONSE), @Output(RETURN_RESULT), @Output(RETURN_CODE) }, responses = { @Response(text = SUCCESS, field =...
java
public boolean submitTopology(String appConf) { if (this.isVerbose) { LOG.log(Level.INFO, "Topology conf is: " + appConf); } // Marathon atleast till 1.4.x does not allow upper case jobids if (!this.topologyName.equals(this.topologyName.toLowerCase())) { LOG.log(Level.SEVERE, "Marathon sche...
python
def setup_logger(debug, color): """Configure the logger.""" if debug: log_level = logging.DEBUG else: log_level = logging.INFO logger = logging.getLogger('exifread') stream = Handler(log_level, debug, color) logger.addHandler(stream) logger.setLevel(log_level)
python
def validate_multiple_of(value, divisor, **kwargs): """ Given a value and a divisor, validate that the value is divisible by the divisor. """ if not decimal.Decimal(str(value)) % decimal.Decimal(str(divisor)) == 0: raise ValidationError( MESSAGES['multiple_of']['invalid'].format(...
python
def _checkgrad(self, target_param=None, verbose=False, step=1e-6, tolerance=1e-3, df_tolerance=1e-12): """ Check the gradient of the ,odel by comparing to a numerical estimate. If the verbose flag is passed, individual components are tested (and printed) :param verbose: If True...
python
def _fake_deleteclass(self, namespace, **params): """ Implements a mock server responder for :meth:`~pywbem.WBEMConnection.DeleteClass` Delete a class in the class repository if it exists. Emulates WBEMConnection.DeleteClass(...)) This is simplistic in that it ignores i...
python
def do_help(self, args): """Get help on commands 'help' or '?' with no arguments prints a list of commands for which help is available 'help <command>' or '? <command>' gives help on <command> """ if _debug: ConsoleCmd._debug("do_help %r", args) # the only reason to defi...
java
public void clear() { List<Socket> socketsToClear = new LinkedList<Socket>(); synchronized(multimap) { for (Socket sock : multimap.values()) { socketsToClear.add(sock); } multimap.clear(); } for (Socket sock : socketsToClear) { IOUtils.closeSocket(sock); } }
python
def construct_result_generator_middleware(result_generators): """ Constructs a middleware which intercepts requests for any method found in the provided mapping of endpoints to generator functions, returning whatever response the generator function returns. Callbacks must be functions with the sign...
java
final String debugId(long id) { byte[] buf = new byte[8]; ArrayUtil.writeLong(buf, 0, id); return HexUtil.toString(buf); }
java
public static final ULocale getFunctionalEquivalent(String keyword, ULocale locID, boolean isAvailable[]) { return ICUResourceBundle.getFunctionalEquivalent(BASE, ICUResourceBundle.ICU_DATA_CLASS_LOAD...
java
protected List<EquPart> negatize(final List<EquPart> equParts) { int left = 0; for (int right = 1; right < equParts.size(); right++) { left = right - 1; if (equParts.get(left) instanceof OpSubtract) if (left == 0) equParts.set(left...
java
@Fix(io.sarl.lang.validation.IssueCodes.UNREACHABLE_BEHAVIOR_UNIT) public void fixUnreachableBehaviorUnit(Issue issue, IssueResolutionAcceptor acceptor) { MemberRemoveModification.accept(this, issue, acceptor); }
python
def _assign_kwargs(self, kwargs): """ Assigns all keyword arguments to a given instance, raising an exception if one of the keywords is not already the name of a property. """ for k in kwargs: if not hasattr(self, k): raise AttributeError(k, 'Not valid for', self.__class__.__name...
java
public double[] toECEF () { double lon0r = toRadians(this.longitude); double lat0r = toRadians(this.latitude); double height = tools.feet2Meters(altitude); double v = a / Math.sqrt(1 - e2*Math.sin(lat0r)*Math.sin(lat0r)); return new double[] { (v + height) * Math.cos(lat0r) * Math.cos(lon0r), // x (...
java
public LocalCachedMapOptions<K, V> timeToLive(long timeToLive, TimeUnit timeUnit) { return timeToLive(timeUnit.toMillis(timeToLive)); }
java
protected void sendUnsubscribe(String topic) { JsonObject msg = Json.createObject().set(TYPE, "unregister").set(TOPIC, topic); send(msg); }
java
private void add(String pos, String s) { if(s.length()>maxLen) return; if(pos.length()==0) return; posSet.add(pos); if(dict.containsKey(s)){ TreeSet<String> sett = dict.get(s); sett.add(pos); }else{ TreeSet<String> sett = new TreeSet<String>(); sett.add(pos); dict.put(s, sett); } }
java
private static <E extends Element> Set<E> setFilter(Set<? extends Element> elements, Set<ElementKind> targetKinds, Class<E> clazz) { // Return set preserving iteration order of input set. Set<...
java
public Phenotype<G, C> withFitness(final C fitness) { return Phenotype.of( _genotype, _generation, _function, _scaler, fitness ); }
java
public void removeLifeCycleListener(EventListener listener) { if (listener != null) { if (listener instanceof javax.servlet.ServletContextListener) { // add to the context listener list servletContextListeners.remove(listener); } if (listener i...
python
def body_block_paragraph_content(text): "for formatting of simple paragraphs of text only, and check if it is all whitespace" tag_content = OrderedDict() if text and text != '': tag_content["type"] = "paragraph" tag_content["text"] = clean_whitespace(text) return tag_content
python
def replace_multiple_in_file(filename: str, replacements: List[Tuple[str, str]]) -> None: """ Replaces multiple from/to string pairs within a single file. Args: filename: filename to process (modifying it in place) replacements: list of ``(from_text, to_text)`` ...
java
public RElement<RElement<?>> existsPattern(IElement X) { ReturnExpression rx = getReturnExpression(); ReturnPattern pat = new ReturnPattern(); pat.setPatternExpression( XFactory.getExpression(X)); rx.setReturnValue(pat); RElement<RElement<?>> ret = new RElement<RElement<?>>(rx); return ret; }
java
public static String concatenate(String[] values, String sepStr) { assert values != null; assert sepStr != null; // Watch for the empty case first. if (values.length == 0) { return ""; } // This handles any size >= 1. StringBuilder buffer =...
java
private void processTaskData() throws IOException { FieldMap fieldMap = new FieldMap14(m_file.getProjectProperties(), m_file.getCustomFields()); fieldMap.createTaskFieldMap(m_projectProps); FieldMap enterpriseCustomFieldMap = new FieldMap14(m_file.getProjectProperties(), m_file.getCustomFields());...
java
public boolean addGroupEntities(String entityGroupName, Boolean createEntities, Entity... entities) { checkEntityGroupIsEmpty(entityGroupName); List<String> entitiesNames = new ArrayList<>(); for (Entity entity : entities) { entitiesNames.add(entity.getName()); } Quer...
python
def get_action_by_id(self, action_id): """ Получение детального описания события """ parsed_json, raw_json = self._call('getactionbyid', element_id=action_id) action = Action.object_from_api(parsed_json, raw_json) return action
java
private SofaRpcException cannotFoundService(String appName, String serviceName) { String errorMsg = LogCodes .getLog(LogCodes.ERROR_PROVIDER_SERVICE_CANNOT_FOUND, serviceName); LOGGER.errorWithApp(appName, errorMsg); return new SofaRpcException(RpcErrorType.SERVER_NOT_FOUND_INVOKER, ...
python
def write(self, data): """only put to stdout every now and then""" self._buffer.append(data) self._current_ticks += 1 # first entry ever will be flushed immediately flush=False if self._last_flush_time is None or \ (self._holdback_time is None and self._max_ticks == 0): fl...
python
def convex_hull_transform(image, levels=256, mask = None, chunksize = CONVEX_HULL_CHUNKSIZE, pass_cutoff = 16): '''Perform the convex hull transform of this image image - image composed of integer intensity values levels - # of levels that we separate the...
python
def get_extended_fsm_service(self): '''Get a reference to the ExtendedFsmService. @return A reference to the ExtendedFsmService object @raises InvalidSdoServiceError ''' with self._mutex: try: return self._obj.get_sdo_service(RTC.ExtendedFsmService._...
java
@SuppressWarnings("deprecation") private static RestApiConfig initRestApiConfig(HazelcastProperties properties, Config config) { boolean isAdvancedNetwork = config.getAdvancedNetworkConfig().isEnabled(); RestApiConfig restApiConfig = config.getNetworkConfig().getRestApiConfig(); boolean isRe...
java
public void factorize() throws Exception { m = A.rows(); n = A.columns(); if(this.rescaler != null){ double[] cn_00_original = null; double[] cn_2_original = null; double[] cn_00_scaled = null; double[] cn_2_scaled = null; if(log.isDebugEnabled()){ cn_00_original = ColtUtils.getCon...
java
public synchronized void put(T value) { cacheMap.put(value.getCacheKey(), new SoftReference<T>(value)); }
python
def is_active(self, name): """ Returns True if plugin exists and is active. If plugin does not exist, it returns None :param name: plugin name :return: boolean or None """ if name in self._plugins.keys(): return self._plugins["name"].active re...
python
def is_compatible(self, uri): """ Check if URI is compatible with this specification. Compatible URI has scheme name that matches specification scheme name, has all of the required components, does not have unsupported components and may have optional components :param uri: URI to check :return: bool """ ...
python
def maps_get_default_rules_output_rules_rbridgeid(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") maps_get_default_rules = ET.Element("maps_get_default_rules") config = maps_get_default_rules output = ET.SubElement(maps_get_default_rules, "output...
python
def _scroll_when_linewrapping(self, ui_content, width, height, cli): """ Scroll to make sure the cursor position is visible and that we maintain the requested scroll offset. Set `self.horizontal_scroll/vertical_scroll`. """ scroll_offsets_bottom = self.scroll_offsets.bot...
java
protected void putItem(final ItemData data) { cache.put(new CacheId(data.getIdentifier()), new CacheValue(data, System.currentTimeMillis() + liveTime)); cache.put(new CacheQPath(data.getParentIdentifier(), data.getQPath(), ItemType.getItemType(data)), new CacheValue(data, System.currentTimeMilli...
python
def write( stream_fragments, stream, normalize=True, book=None, sources=None, names=None, mappings=None): """ Given an iterable of stream fragments, write it to the stream object by using its write method. Returns a 3-tuple, where the first element is the mapping, second element is the ...
python
def call_missing_reference(cls, kb_app, sphinx_app: Sphinx, sphinx_env: BuildEnvironment, node, contnode, ): """ On doctree-resolved, do callbacks""" for callback in EventAction.g...
java
public DataWriterBuilder<S, D> writeInFormat(WriterOutputFormat format) { this.format = format; log.debug("writeInFormat : {}", this.format); return this; }
python
def getextensibleindex(self, key, name): """ Get the index of the first extensible item. Only for internal use. # TODO : hide this Parameters ---------- key : str The type of IDF object. This must be in ALL_CAPS. name : str The name of th...
python
def page_url(self, page): ''' Returns URL for page, page is included as query parameter. Can be redefined by keyword argument ''' if page is not None and page != 1: return self.url.qs_set(**{self.page_param: page}) elif page is not None: return se...
java
public static void reloadLibrary(String key) { if (key.startsWith(DicLibrary.DEFAULT)) { DicLibrary.reload(key); } else if (key.startsWith(StopLibrary.DEFAULT)) { StopLibrary.reload(key); } else if (key.startsWith(SynonymsLibrary.DEFAULT)) { SynonymsLibrary.re...
java
public Optional<V> get(K key) { if (cacheIsFull()) { Entry entry = mMap.get(key); if (entry == null) { return load(key); } return Optional.ofNullable(entry.mValue); } Entry result = mMap.compute(key, (k, entry) -> { if (entry != null) { entry.mReferenced = true;...
java
public List<BillingStats> getBillingStats(Group... groups) { List<BillingStats> result = new ArrayList<>(); List<Group> groupList = Arrays.asList(groups); groupList.forEach( group -> result.add( converter.convertBillingStats( client.getGroupBillin...
python
def clear_signal_handlers(self): '''Undo :meth:`set_signal_handlers`. Not only must this be done on shutdown, but after every fork call too. ''' signal.signal(signal.SIGABRT, self.old_sigabrt) signal.signal(signal.SIGINT, self.old_sigint) signal.signal(signal.SI...
python
def extract_data(self): """ This will will extract the raw data from the response :return: None """ content_type = 'Exception in extracting content-type from header' try: content_type = self.response.headers.get('content-type', '') if 'application/...
python
def plot_interactive(mergepkl, noisepkl=None, thresh=6.0, thresh_link=7.0, ignoret=None, savehtml=True, url_path='plots'): """ Backwards compatible function for making interactive candidate summary plot """ data = readdata(mergepkl) circleinds = calcinds(data, thresh, ignoret) crossinds = calcinds(data...
python
def _radix_int_handler_factory(radix_indicators, charset, parse_func): """Generates a handler co-routine which tokenizes a integer of a particular radix. Args: radix_indicators (sequence): The set of ordinals of characters that indicate the radix of this int. charset (sequence): Set of ordinals...
java
private boolean verify(Element element) { Interceptor interceptor = element.getAnnotation(Interceptor.class); // It must be implement the interface IInterceptor and marked with annotation Interceptor. return null != interceptor && ((TypeElement) element).getInterfaces().contains(iInterceptor); ...
java
public Slot insertSlotAt(final int position, @NonNull final Slot slot) { if (position < 0 || size < position) { throw new IndexOutOfBoundsException("New slot position should be inside the slots list. Or on the tail (position = size)"); } final Slot toInsert = new Slot(slot); ...
python
def collect_variables(self, variables: MultisetOfVariables) -> None: """Recursively adds all variables occuring in the expression to the given multiset. This is used internally by `variables`. Needs to be overwritten by inheriting container expression classes. This method can be used when gathe...
java
public static NestedMappingInfo loadNestedMappingInformation(XML xml, Class<?> targetClass,String nestedMappingPath, Class<?> sourceClass, Class<?> destinationClass, Field configuredField){ boolean isSourceClass = targetClass == sourceClass; NestedMappingInfo info = new NestedMappingInfo(isSourceClass); ...
java
@Override public SpanStore spanStore() { if (spanStore == null) { synchronized (this) { if (spanStore == null) { spanStore = new CassandraSpanStore(this); } } } return spanStore; }
java
public EClass getIfcElementQuantity() { if (ifcElementQuantityEClass == null) { ifcElementQuantityEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(200); } return ifcElementQuantityEClass; }
java
@Override protected void handleEvents(final String EVENT_TYPE) { super.handleEvents(EVENT_TYPE); if ("FINISHED".equals(EVENT_TYPE)) { if ( gauge.isHighlightSections() ) { redraw(); } } else if ("VISIBILITY".equals(EVENT_TYPE)) { Helper.enableNo...
java
private String utfIncludeCheck(String line, Boolean addatsign) { String checked = ""; boolean start = false; for (int i = 0; i < line.length(); i++) { if (isOneByte(line.substring(i, i + 1))) { if (start) { start = false; checked += (addatsign ? useJPNFont ? fontEnd + LST_ESCAPE...
java
public static boolean endsWith(CharSequence seq, CharSequence pattern, IntUnaryOperator op) { if (pattern.length() > seq.length()) { return false; } int ls = seq.length(); int lp = pattern.length(); for (int ii=1;ii<=lp;ii++) { ...
python
def is_binary_operator(oper): """returns True, if operator is binary operator, otherwise False""" # definition: # member in class # ret-type operator symbol(arg) # globally # ret-type operator symbol( arg1, arg2 ) symbols = [ ',', '()', '[]', '!=', '%', '%=', '&', '&&', '&=', '*', '*...
java
protected DataSource getDataSource() throws RepositoryException { try { return containerConfig.dsProvider.getDataSource(containerConfig.dbSourceName); } catch (NamingException e) { throw new RepositoryException("Datasource '" + containerConfig.dbSourceName ...
java
public VariableInstance setVariableInstance(Long procInstId, String name, Object value) throws DataAccessException { TransactionWrapper transaction = null; EngineDataAccessDB edao = new EngineDataAccessDB(); try { transaction = edao.startTransaction(); VariableInstanc...
java
public static boolean isInput(GraphQLType type) { GraphQLUnmodifiedType unmodifiedType = unwrapAll(type); return unmodifiedType instanceof GraphQLScalarType || unmodifiedType instanceof GraphQLEnumType || unmodifiedType instanceof GraphQLIn...
java
@Override public Connection getConnection() throws SQLException { if (isClosed()) { throw new SQLException("HikariDataSource " + this + " has been closed."); } if (fastPathPool != null) { return fastPathPool.getConnection(); } // See http://en.wikipedia.org/wiki/D...
java
public HelpTopicNode getPreviousSibling() { int i = getIndex() - 1; return i < 0 ? null : parent.children.get(i); }
java
public V remove(long key) { if (size == 0) { return null; } if (size == 1) { int posDiff = compare(key, rootKey); if (posDiff == -1) { size--; rootKey = 0; V prev = rootVal; rootVal = null; return prev; } return null; } Node<V> n = root; Node<V> parent = null; boolean is...
python
def create_record(self, name, content, username, password): ''' Create record ''' #headers = {'key': username, 'secret': password} req = requests.post(self.api_server + '/api/' + name, data=json.dumps(content), auth=(username, password)) return req
java
private void adaptSwitchPreferenceSummary(final boolean showValueAsSummary) { if (showValueAsSummary) { switchPreference.setSummaryOn(R.string.switch_preference_summary_on); switchPreference.setSummaryOff(R.string.switch_preference_summary_off); } else { switchPrefere...
java
private Config findAndLoadGlobalConfigInDirectory(Path path, Config fallback) throws IOException { FileStatus[] files = this.fs.listStatus(path, GLOBAL_PATH_FILTER); if (files == null) { log.warn("Could not list files at path " + path); return ConfigFactory.empty(); } if (files.length > 1) {...
java
public Observable<Page<WorkflowRunActionInner>> listAsync(final String resourceGroupName, final String workflowName, final String runName, final Integer top, final String filter) { return listWithServiceResponseAsync(resourceGroupName, workflowName, runName, top, filter) .map(new Func1<ServiceRespon...
java
private synchronized void legacyInitBuckets(SparseIntArray inUseCounts) { Preconditions.checkNotNull(inUseCounts); // clear out all the buckets mBuckets.clear(); // create the new buckets final SparseIntArray bucketSizes = mPoolParams.bucketSizes; if (bucketSizes != null) { for (int i = ...
python
def _frame_advance(self, action): """ Advance a frame in the emulator with an action. Args: action (byte): the action to press on the joy-pad Returns: None """ # set the action on the controller self.controllers[0][:] = action # ...
java
@Override void transfer(HashMapPro.Entry[] newTable) { int newCapacity = newTable.length; for (Entry<K, V> e = header.after; e != header; e = e.after) { // if (rehash) // e.hash = (e.key == null) ? 0 : hash(e.key); int index = indexFor(e.hash, newCapacity); e.next = newTable[index]; newTa...
java
private int getType(Resource file) { if (transferMode == FTPConstant.TRANSFER_MODE_BINARY) return AFTPClient.FILE_TYPE_BINARY; else if (transferMode == FTPConstant.TRANSFER_MODE_ASCCI) return AFTPClient.FILE_TYPE_TEXT; else { String ext = ResourceUtil.getExtension(file, null); if (ext == null || ListUtil.l...
java
public void process( I left , I right , GrayF32 imageDisparity ) { // check inputs and initialize data structures InputSanityCheck.checkSameShape(left,right,imageDisparity); this.imageLeft = left; this.imageRight = right; w = left.width; h = left.height; // Compute disparity for each pixel for( int y = ...
python
def max_word_width(myDict): ''' currd = {0:'AutoPauseSpeed', 125:'HRLimitLow', 6:'Activity'} max_wordwidth(currd) ''' maxValueWidth = 0 for each in myDict: eachValueWidth = myDict[each].__len__() if(eachValueWidth > maxValueWidth): maxValueWidth = eachValueWid...
python
def create_atype(self, ): """Create a atype and store it in the self.atype :returns: None :rtype: None :raises: None """ name = self.name_le.text() desc = self.desc_pte.toPlainText() try: atype = djadapter.models.Atype(name=name, description=d...
java
public static PoliciesCache fromFile(File singleFile, Set<Attribute> forcedContext) { return fromSourceProvider(YamlProvider.getFileProvider(singleFile), forcedContext); }
java
@Override public Set<ScriptArchive> getScriptArchives(Set<ModuleId> moduleIds) throws IOException { Set<ScriptArchive> archives = new LinkedHashSet<ScriptArchive>(moduleIds.size()*2); Path archiveOuputDir = getConfig().getArchiveOutputDirectory(); List<ModuleId> moduleIdList = new LinkedList...
java
private int matchingQuote(int i){ if(string.charAt(i)!='"') throw new UnsupportedOperationException(); ++i; boolean escape = false; while(i<string.length()){ char ch = string.charAt(i); if(escape) escape = false; else if(ch...
python
def findall(self, expr): """list of all matching (sub-)expressions in `expr` See also: :meth:`finditer` yields the matches (:class:`MatchDict` instances) for the matched expressions. """ result = [] try: for arg in expr.args: r...
python
def align_cg3_with_Text( lines, text, **kwargs ): ''' Aligns VISLCG3's output (a list of strings) with given EstNLTK\'s Text object. Basically, for each word position in the Text object, finds corresponding VISLCG3's analyses; Returns a list of dicts, where each dict has following attribute...
python
def create_group(cls, prefix: str, name: str) -> ErrorGroup: """Create a new error group and return it.""" group = cls.ErrorGroup(prefix, name) cls.groups.append(group) return group
java
public static Object resolveUnderlyingObject(Object obj) { while(obj instanceof Decorator) { obj = ((Decorator)obj).getDecoratedObject(); } return obj; }
python
def get_parser(): ''' Return the command-line parser ''' parser = argparse.ArgumentParser( description="Reverse, undo, and calculate CRC32 checksums") subparsers = parser.add_subparsers(metavar='action') poly_flip_parser = argparse.ArgumentParser(add_help=False) subparser_group = poly_flip_...
python
def _pop_key(self, key, has_default): """Remove an element by key.""" try: index, value = self._dict.pop(key) except KeyError: if has_default: return None, None else: raise key2, value2 = self._list.pop(index) assert key is key2 assert value is value2 return index, value
python
def purity(rho: Density) -> bk.BKTensor: """ Calculate the purity of a mixed quantum state. Purity, defined as tr(rho^2), has an upper bound of 1 for a pure state, and a lower bound of 1/D (where D is the Hilbert space dimension) for a competently mixed state. Two closely related measures are ...
java
@Override public AtomicValue evaluate() throws TTXPathException { // compute the function's result final byte[] value = computeResult(); // create an atomic value, add it to the list and move the cursor to it. AtomicValue val = new AtomicValue(value, mReturnType); final int...
python
def get_sensors_summary(self): """ This returns a dict of sensor of the source and their values """ sub_title_list = self.get_sensor_list() graph_vector_summary = OrderedDict() for graph_idx, graph_data in enumerate(self.last_measurement): val_str = str(round(graph_data, 1))...