language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private void exit(String command, Socket socket) throws IOException { lock.lock(); try { // We may exit before we get a chance to reply. DataOutputStream dout = new DataOutputStream(socket.getOutputStream()); dout.writeInt(BYTES_INT); dout.writeInt(1); ...
python
def initialize(cls): """ Initialize Axes logging and show version information. This method is re-entrant and can be called multiple times. It displays version information exactly once at application startup. """ if cls.logging_initialized: return cls...
python
def set(self, type_name, entity): """Sets an entity using the API. Shortcut for using call() with the 'Set' method. :param type_name: The type of entity. :type type_name: str :param entity: The entity to set. :type entity: dict :raise MyGeotabException: Raises when an ex...
python
def tgv_phantom(space, edge_smoothing=0.2): """Piecewise affine phantom. This phantom is taken from [Bre+2010] and includes both linearly varying regions and sharp discontinuities. It is designed to work well with Total Generalized Variation (TGV) type regularization. Parameters ---------- ...
java
@Override public IPeer selectPeer(List<IPeer> availablePeers) { int peerSize = availablePeers != null ? availablePeers.size() : 0; // Return none if empty, or first if only one member found if (peerSize <= 0) { return null; } if (peerSize == 1) { return availablePeers.iterator().next(...
python
def node(schema=None, header=None, group=None, version=None): """Turn function into node. Args: schema: capnproto schema describing the output messages format header: This parameter is currently not supported and only for internal usage. group (bool): A boolean indicating wh...
python
def transformer_decoder_attention_unit(x, hparams, encoder_output, decoder_self_attention_bias, encoder_decoder_attention_bias, ...
python
def _make_subclasshook(cls): """Construct a __subclasshook__ callable that incorporates the associated __extra__ class in subclass checks performed against cls. """ if isinstance(cls.__extra__, abc.ABCMeta): # The logic mirrors that of ABCMeta.__subclasscheck__. # Registered classes ...
python
def status(self): """Get the status of the responding member.""" status_request = etcdrpc.StatusRequest() status_response = self.maintenancestub.Status( status_request, self.timeout, credentials=self.call_credentials, metadata=self.metadata ...
java
public Config setExecutorConfigs(Map<String, ExecutorConfig> executorConfigs) { this.executorConfigs.clear(); this.executorConfigs.putAll(executorConfigs); for (Entry<String, ExecutorConfig> entry : executorConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } ...
python
def verify_ocsp_response(cert, path, validation_context, cert_description=None, end_entity_name_override=None): """ Verifies an OCSP response, checking to make sure the certificate has not been revoked. Fulfills the requirements of https://tools.ietf.org/html/rfc6960#section-3.2. :param cert: ...
python
def init_selection(self): """Call selection changed in the beginning, so signals get emitted once Emit shot_taskfile_sel_changed signal and asset_taskfile_sel_changed. :returns: None :raises: None """ si = self.shotverbrws.selected_indexes(0) if si: ...
python
def insert(self, idx, w, comment=''): '''insert a waypoint''' if idx >= self.count(): self.add(w, comment) return if idx < 0: return w = copy.copy(w) if comment: w.comment = comment w.seq = idx self.wpoints.insert(id...
python
def p_encaps_list(p): '''encaps_list : encaps_list encaps_var | empty''' if len(p) == 3: if p[1] == '': p[0] = p[2] else: p[0] = ast.BinaryOp('.', p[1], p[2], lineno=p.lineno(2)) else: p[0] = ''
python
def stop(self, timeout=5): """Stop notifying Listeners when new :class:`~can.Message` objects arrive and call :meth:`~can.Listener.stop` on each Listener. :param float timeout: Max time in seconds to wait for receive threads to finish. Should be longer than timeout given...
java
public static <T> T[] swap(T[] self, int i, int j) { T tmp = self[i]; self[i] = self[j]; self[j] = tmp; return self; }
python
def delete(name=None, group_id=None, region=None, key=None, keyid=None, profile=None, vpc_id=None, vpc_name=None): ''' Delete a security group. CLI example:: salt myminion boto_secgroup.delete mysecgroup ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ...
java
public UUID getMessageId() { final ByteBuffer wrap = ByteBuffer.wrap(messageIdBytes); return new UUID(wrap.asLongBuffer().get(0), wrap.asLongBuffer().get(1)); }
python
def pull(self, arm_id, success, failure): ''' Pull arms. Args: arm_id: Arms master id. success: The number of success. failure: The number of failure. ''' self.__beta_dist_dict[arm_id].observe(success, failure)
java
public Axis getAxis() { return options.orientation != null ? Axis.fromStyleName(options.orientation) : null; }
java
public String getProperty(String strProperty) { if (m_propTransport != null) if (m_propTransport.get(strProperty) != null) return (String)m_propTransport.get(strProperty); return super.getProperty(strProperty); }
java
public static void unJar(File jarFile, File toDir) throws IOException { JarFile jar = new JarFile(jarFile); try { Enumeration entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry entry = (JarEntry)entries.nextElement(); if (!entry.isDirectory()) { InputStre...
java
public void releaseConnection(SQLiteConnection connection) { synchronized (mLock) { AcquiredConnectionStatus status = mAcquiredConnections.remove(connection); if (status == null) { throw new IllegalStateException("Cannot perform this operation " + ...
python
def refresh_token(self, arguments): """ Refresh a user's access token, using existing the refresh token previously received in the auth flow. """ new_access_token = None auth = ExistAuth(self.client_id, self.client_secret) resp = auth.refresh_token(self.access_t...
java
protected final PrcAccEntrySave lazyGetPrcAccEntrySave( final Map<String, Object> pAddParam) throws Exception { @SuppressWarnings("unchecked") PrcAccEntrySave<RS> proc = (PrcAccEntrySave<RS>) this.processorsMap.get(PrcAccEntrySave.class.getSimpleName()); if (proc == null) { proc = new PrcAcc...
python
def find_max_pending_transfers(gas_limit): """Measure gas consumption of TokenNetwork.unlock() depending on number of pending transfers and find the maximum number of pending transfers so gas_limit is not exceeded.""" tester = ContractTester(generate_keys=2) tester.deploy_contract('SecretRegistry'...
python
def date(value): """ Returns a date literal if value is likely coercible to a date Parameters ---------- value : date value as string Returns -------- result : TimeScalar """ if isinstance(value, str): value = to_date(value) return literal(value, type=dt.date)
python
def reqPnL(self, account: str, modelCode: str = '') -> PnL: """ Start a subscription for profit and loss events. Returns a :class:`.PnL` object that is kept live updated. The result can also be queried from :meth:`.pnl`. https://interactivebrokers.github.io/tws-api/pnl.html ...
python
def cv(self, t, structure=None): """ Constant volume specific heat C_v at temperature T obtained from the integration of the DOS. Only positive frequencies will be used. Result in J/(K*mol-c). A mol-c is the abbreviation of a mole-cell, that is, the number of Avogadro times the a...
java
@Override public int queueSize() { BinaryJedisCommands jc = getBinaryJedisCommands(); try { Long result = jc.llen(getRedisListNameAsBytes()); return result != null ? result.intValue() : 0; } finally { closeJedisCommands(jc); } }
java
@Override public Set<Dataset> findDistinctDatasets() throws IOException { Set<Dataset> datasets = Sets.newHashSet(); for (FileStatus datasetsFileStatus : this.fs.globStatus(new Path(inputDir, subDirPattern))) { log.info("Scanning directory : " + datasetsFileStatus.getPath().toString()); if (datase...
java
public com.google.api.ads.admanager.axis.v201805.GrpSettings getGrpSettings() { return grpSettings; }
java
public boolean createSharedObject(IScope scope, String name, boolean persistent) { boolean added = hasSharedObject(scope, name); if (!added) { log.debug("Attempting to add shared object: {} to {}", name, scope.getName()); added = scope.addChildScope(new SharedObjectScope(scop...
python
def _extract_variants(address, variants_str): """Return the variants (if any) represented by the given variants_str. :returns: The variants or else `None` if there are none. :rtype: tuple of tuples (key, value) strings """ def entries(): for entry in variants_str.split(','): key, _, value = entry.p...
python
def asset(path): """ Join the given path with the STATIC_URL setting. Usage:: {% static path [as varname] %} Examples:: {% static "myapp/css/base.css" %} {% static variable_with_path %} {% static "myapp/css/base.css" as admin_base_css %} {% static variable_wit...
python
def unique_scene_labels(scene_list): """Find the unique scene labels Parameters ---------- scene_list : list, shape=(n,) A list containing scene dicts Returns ------- labels: list, shape=(n,) Unique labels in alphabetical order """ if isinstance(scene_list, dcase_u...
java
public void doFilter(ServletRequest request, ServletResponse response) throws ServletException, IOException { if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) logger.logp(Level.FINE, CLASS_NAME,"doFilter", "entry"); try { // if there are ...
python
def amplitude_from_polarizations(h_plus, h_cross): """Return gravitational wave amplitude Return the gravitation-wave amplitude from the h_plus and h_cross polarizations of the waveform. Parameters ---------- h_plus : TimeSeries An PyCBC TmeSeries vector that contains the plus polariza...
java
public void init(FilterConfig filterConfig) throws ServletException { // need the Context for Logging, instantiating ClassLoader, etc context = filterConfig.getServletContext(); StringBuilder sb = new StringBuilder(); StringBuilder err = new StringBuilder(); Object attr = context.getAttribute(Config.PATHFILT...
python
def get_local_independencies(self, latex=False): """ Returns all the local independencies present in the markov model. Local independencies are the independence assertion in the form of .. math:: {X \perp W - {X} - MB(X) | MB(X)} where MB is the markov blanket of all the random ...
python
def _text_filter_input(self, input_gen): """ Filters out the text input line by line to avoid parsing and processing metrics we know we don't want to process. This only works on `text/plain` payloads, and is an INTERNAL FEATURE implemented for the kubelet check :param input_get: ...
java
int distanceTo(final byte byteValue, final int fromIndex) { assert 0 <= fromIndex && fromIndex < byteArray.length; int index = fromIndex; for (; index < byteArray.length; ++index) { if (byteValue == byteArray[index]) { break; } } return ind...
java
@Override public JacksonWrapperSerializer createSerializer(OutputStream out, JsonEncoding encoding) { try { JsonGenerator generator = innerFactory.createGenerator(out, encoding); // generator.setPrettyPrinter(new MinimalPrettyPrinter()); return new JacksonWrapperSerializer(generator, getSupportedFormat()); ...
python
def qsize(self): """ Returns the number of items currently in the queue :return: Integer containing size of the queue :exception: ConnectionError if queue is not connected """ if not self.connected: raise QueueNotConnectedError("Queue is not Connected") ...
python
def write(self, bytes): """Write data to the memory. .. note:: Writes beyond the specified memory range will be truncated and a :py:exc:`.TruncationWarning` is produced. These warnings can be converted into exceptions using :py:func:`warnings.simplefilter`:: ...
python
async def shutdown(self): """ Shut down this Looper. """ logger.display("Looper shutting down now...", extra={"cli": False}) self.running = False start = time.perf_counter() if not self.runFut.done(): await self.runFut self.stopall() lo...
java
public Engine execute() throws ScanAgentException { Engine engine = null; try { engine = executeDependencyCheck(); if (!this.updateOnly) { if (this.generateReport) { generateExternalReports(engine, new File(this.reportOutputDirectory)); ...
java
public final int strNCmp(byte[]bytes, int p, int end, byte[]ascii, int asciiP, int n) { while (n-- > 0) { if (p >= end) return ascii[asciiP]; int c = mbcToCode(bytes, p, end); int x = ascii[asciiP] - c; if (x != 0) return x; asciiP++; p +=...
python
def __save_output(self): """Saves the output into a native OOo document format. """ out = zipfile.ZipFile(self.outputfilename, 'w') for info_zip in self.infile.infolist(): if info_zip.filename in self.templated_files: # Template file - we have edited these. ...
python
def make_simulation(tax_benefit_system, nb_persons, nb_groups, **kwargs): """ Generate a simulation containing nb_persons persons spread in nb_groups groups. Example: >>> from openfisca_core.scripts.simulation_generator import make_simulation >>> from openfisca_france import Countr...
python
def main(*arguments): """ Performs a natural sort on entries given on the command-line. Arguments are read from sys.argv. """ from argparse import ArgumentParser, RawDescriptionHelpFormatter from textwrap import dedent parser = ArgumentParser( description=dedent(main.__doc__), for...
java
public static <T extends Enum<T>> ConfigurationOptionBuilder<T> enumOption(Class<T> clazz) { final ConfigurationOptionBuilder<T> optionBuilder = new ConfigurationOptionBuilder<T>(new EnumValueConverter<T>(clazz), clazz); for (T enumConstant : clazz.getEnumConstants()) { optionBuilder.addValidOption(enumConstant)...
python
def insert(self, index, x): """ See :meth:`list.insert()` method Calls observer ``self.observer(UpdateType.CREATED, item, index)`` """ self.real_list.insert(index, x) self.observer(UpdateType.CREATED, x, index)
java
public void validate(JavaScriptObject newValues, final I_CmsJavaScriptObjectCallback onSuccess) { AsyncCallback<Map<String, String>> rpcCallback = new AsyncCallback<Map<String, String>>() { @SuppressWarnings("synthetic-access") public void onFailure(Throwable caught) { ...
python
def from_dp(cls, text, use_unicode_for_glyphs=True): """ Create a new instance of ColorString from a darkplaces-formatted text :param text: darkplaces text string (either str or bytes) :param use_unicode_for_glyphs: convert unicode glyphs to ascii :return: ColorString instance ...
python
def fn_arg_hash_function(fn): """Creates a hash function which will return the same hashable value if passed a set of *args and **kwargs which are equivalent from the perspective of a function call. That is, the order of keyword arguments, or the fact that an argument without a default was c...
python
def cleanup(self): """ Cleanup references to the movie when this button is destroyed. """ if self._movie is not None: self._movie.frameChanged.disconnect(self._updateFrame) self._movie = None
java
BigInteger getBigInteger(int len, boolean makePositive) throws IOException { if (len > available()) throw new IOException("short read of integer"); if (len == 0) { throw new IOException("Invalid encoding: zero length Int value"); } byte[] bytes = new byte[len]; ...
python
def to_pb(self): """Converts the intersection into a single GC rule as a protobuf. :rtype: :class:`.table_v2_pb2.GcRule` :returns: The converted current object. """ intersection = table_v2_pb2.GcRule.Intersection( rules=[rule.to_pb() for rule in self.rules] )...
python
def make_bin_array(bins) -> np.ndarray: """Turn bin data into array understood by HistogramXX classes. Parameters ---------- bins: array_like Array of edges or array of edge tuples Examples -------- >>> make_bin_array([0, 1, 2]) array([[0, 1], [1, 2]]) >>> make_b...
python
def pickle_all(self, path): """Back up entire JSS to a Python Pickle. For each object type, retrieve all objects, and then pickle the entire smorgasbord. This will almost certainly take a long time! Pickling is Python's method for serializing/deserializing Python object...
python
def blastparse(self): """ Parse the blast results, and store necessary data in dictionaries in sample object """ logging.info('Parsing BLAST results') # Load the NCBI 16S reference database as a dictionary for sample in self.runmetadata.samples: if sample.gene...
java
public static String parseTemplate(String template, Object paramObj) { String output; try { output = (String) TemplateRuntime.eval(template, paramObj); } catch (Exception e) { throw new ParseExpressionException("解析Mvel模板异常,解析出错的模板为:" + template, e); } retu...
python
def list(self, priority=values.unset, assignment_status=values.unset, workflow_sid=values.unset, workflow_name=values.unset, task_queue_sid=values.unset, task_queue_name=values.unset, evaluate_task_attributes=values.unset, ordering=values.unset, has_addons=values.unse...
java
@Override protected Object openConnection() throws ConnectionException { qConnection = null; qSession = null; queue = null; try { String server_url = this.getAttributeValueSmart(SERVER_URL); if ("THIS_SERVER".equals(server_url)) server_url = null; ...
java
public static int decodeSequence(ByteBuffer buf) { DerId id = DerId.decode(buf); if (!id.matches(DerId.TagClass.UNIVERSAL, DerId.EncodingType.CONSTRUCTED, ASN1_SEQUENCE_TAG_NUM)) { throw new IllegalArgumentException("Expected SEQUENCE identifier, received " + id); } int len =...
java
public NamespaceAlias getNamespaceAlias(int i) throws ArrayIndexOutOfBoundsException { if (null == m_prefix_aliases) throw new ArrayIndexOutOfBoundsException(); return (NamespaceAlias) m_prefix_aliases.elementAt(i); }
python
def add_edge(self, fr, to): """ Add an outward edge to a vertex :param fr: The source vertex. :param to: The name of the outward edge. """ if fr not in set(self.graph.vs): # ToDo: find out why item can be in set but not dict raise ValueError('can not connect unknown...
java
public <T> Navigator with(Class<T> type, Preparer<T> preparer) throws MvcGraphException { with(type, null, preparer); return this; }
python
def getSets(self): """ Get all the sets declared. """ sets = lock_and_call( lambda: self._impl.getSets(), self._lock ) return EntityMap(sets, Set)
java
@Override public UpdateDeviceDefinitionResult updateDeviceDefinition(UpdateDeviceDefinitionRequest request) { request = beforeClientExecution(request); return executeUpdateDeviceDefinition(request); }
python
def earth_accel2_df(IMU,IMU2,ATT): '''return earth frame acceleration vector from df log''' r = rotation_df(ATT) accel1 = Vector3(IMU.AccX, IMU.AccY, IMU.AccZ) accel2 = Vector3(IMU2.AccX, IMU2.AccY, IMU2.AccZ) accel = 0.5 * (accel1 + accel2) return r * accel
python
def set_target(self, target): '''Set the target to use (one of buildozer.targets, such as "android") ''' self.targetname = target m = __import__('buildozer.targets.{0}'.format(target), fromlist=['buildozer']) self.target = m.get_target(self) self.ch...
python
def layer_post_save(instance, *args, **kwargs): """ Used to do a layer full check when saving it. """ if instance.is_monitored and instance.service.is_monitored: # index and monitor if not settings.REGISTRY_SKIP_CELERY: check_layer.delay(instance.id) else: check_...
python
def sun_utc(self, date, latitude, longitude, observer_elevation=0): """Calculate all the info for the sun at once. All times are returned in the UTC timezone. :param date: Date to calculate for. :type date: :class:`datetime.date` :param latitude: Latitude - Northe...
python
def get_methods_class(self, class_name): """ Return all methods of a specific class :param class_name: the class name :type class_name: string :rtype: a list with :class:`EncodedMethod` objects """ l = [] for i in self.classes.class_def: ...
java
public int read(byte b[], int off, int len) throws IOException { if (pos >= this.len) { // EOF return -1; } int num = (int) Math.min(len - off, this.len - pos); in.readBytes(b, off, num); pos += num; return num; }
java
@SneakyThrows public static void generateQRCode(final OutputStream stream, final String key, final int width, final int height) { val hintMap = new EnumMap<EncodeHintType, Object>(EncodeHintType.class); hintMap.put(EncodeHintType.CHARACTER_SET, StandardCharsets....
java
public Context merge(final Vars vars, final Out out) { try { return prepareAst() .execute(this, out, vars); } catch (Exception e) { throw completeException(e); } }
python
def _normalize_group_attrs(self, attrs): """Normalize the attributes used to set groups If it's a list of one element, it just become this element. It raises an error if the attribute doesn't exist or if it's multivaluated. """ for key in self.group_attrs_keys: ...
python
def remove_member(self, member): """ Remove a single member to the scope. :param member: single username to be removed from the scope list of members :type member: basestring :raises APIError: when unable to update the scope member """ select_action = 'remove_mem...
python
def Concat(self: Iterable, *others): """ [ { 'self': [1, 2, 3], ':args': [[4, 5, 6], [7, 8, 9]], 'assert': lambda ret: list(ret) == [1, 2, 3, 4, 5, 6, 7, 8, 9] } ] """ return concat_generator(self, *[unbox_if_flow(other) for other in others])
java
public int read(byte []read_buffer, int offset, int length) throws IOException { // Copy as much as possible from the read buffer if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) { //306998.15 logger.logp(Level.FINE, CLASS_NAME,"read", "read length -->"+length); ...
python
def get_from_postcode(self, postcode, distance, skip_cache=False): """ Calls `postcodes.get_from_postcode` but checks correctness of `distance`, and by default utilises a local cache. :param skip_cache: optional argument specifying whether to skip the cache ...
python
def _parse_status_code(response): """ Return error string code if the response is an error, otherwise ``"OK"`` """ # This happens when a status response is expected if isinstance(response, string_types): return response # This happens when a list of structs are expected is_single_l...
java
public static void register (String prefix, ObjectActionHandler handler) { // make sure we know about potential funny business if (_oahandlers.containsKey(prefix)) { log.warning("Warning! Overwriting previous object action handler registration, all " + "hell could...
java
protected void addResourceAceRules(Digester digester, String xpath) { String xp_ace = xpath + N_ACCESSCONTROL_ENTRIES + "/" + N_ACCESSCONTROL_ENTRY; digester.addCallMethod(xp_ace, "addAccessControlEntry"); digester.addCallMethod(xp_ace + "/" + N_ACCESSCONTROL_PRINCIPAL, "setAcePrincipalId", 0);...
python
def create_permission(self): """Get an instance of permission services facade.""" return Permission( self.networkapi_url, self.user, self.password, self.user_ldap)
java
public void guiceManage(final Class<?> type) { if (JerseyBinding.isHK2Managed(type, options.get(JerseyExtensionsManagedByGuice))) { throw new WrongContextException("Guice creates service %s which must be managed by HK2.", type.getName()); } guiceManaged.add(type);...
java
public boolean process( I image ) { if( stitchedImage == null ) { stitchedImage = (I)image.createNew(widthStitch, heightStitch); workImage = (I)image.createNew(widthStitch, heightStitch); } if( motion.process(image) ) { update(image); // check to see if an unstable and improbably solution was genera...
python
def serialize(self): """Serialize into JSONable dict, and associated locations data.""" api_metadata = OrderedDict() # $ char makes this come first in sort ordering api_metadata['$version'] = self.current_version locations = {} for svc_name, group in self.groups(): ...
python
def print_featurelist(feature_list): """ Print the feature_list in a human-readable form. Parameters ---------- feature_list : list feature objects """ input_features = sum(map(lambda n: n.get_dimension(), feature_list)) print("## Features (%i)" % input_features) print("```"...
python
def get_partition_name(cls, region=None): """ Gets the name of the partition given the region name. If region name is not provided, this method will use Boto3 to get name of the region where this code is running. This implementation is borrowed from AWS CLI https://github.com/aw...
python
def _parse_pet_record(self, root): """ Given a <pet> Element from a pet.get or pet.getRandom response, pluck out the pet record. :param lxml.etree._Element root: A <pet> tag Element. :rtype: dict :returns: An assembled pet record. """ record = { ...
python
def _scp_file(self, source_file, dest_file, file_system): """ SCP file to remote device. Return (status, msg) status = boolean msg = details on what happened """ return self._xfer_file( source_file=source_file, dest_file=dest_file, ...
java
@Inject @Provides @Singleton public ResponseHandler provideResponseHandler(PageResponseWriter pageResponseWriter, ApiResponseWriter apiResponseWriter, BinaryResponseWriter binaryResponseWriter, RedirectResponseWriter redirectResponseWriter, ExceptionStatusMapper exceptionStatusMapper) { return new...
java
private List<Class<? extends RelationshipInterface>> getRelationClassCandidatesForRelType(final String relType) { List<Class<? extends RelationshipInterface>> candidates = new ArrayList(); for (final Class<? extends RelationshipInterface> candidate : getRelationshipEntities().values()) { Relation rel = instan...
java
public NotificationChain basicSetDateTimeParameter(DateTimeParameterType newDateTimeParameter, NotificationChain msgs) { return ((FeatureMap.Internal)getMixed()).basicAdd(BpsimPackage.Literals.DOCUMENT_ROOT__DATE_TIME_PARAMETER, newDateTimeParameter, msgs); }
java
void replaceTaskWithResult(int sequence, Object response) { int index = toIndex(sequence); // If sequence is not equal then it is disposed externally if (sequences[index] != sequence) { return; } ringItems[index] = response; isTask[index] = false; call...
python
def on_electrode_states_set(self, states): ''' Render and draw updated **static** electrode actuations layer on canvas. ''' if (self.canvas_slave.electrode_states .equals(states['electrode_states'])): return self.canvas_slave.electrode_states ...