language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public boolean waitForRegistered(long timeout, TimeUnit unit) { try { if (this.registeredLatch.await(timeout, unit)) { return true; } } catch (InterruptedException e) { LOG.severe("Failed to wait for mesos framework got registered"); return false; } return false; }
python
def LoadData(self, data, custom_properties=None): """Loads new rows to the data table, clearing existing rows. May also set the custom_properties for the added rows. The given custom properties dictionary specifies the dictionary that will be used for *all* given rows. Args: data: The rows t...
python
def propagate_occur(self, node, value): """Propagate occurence `value` to `node` and its ancestors. Occurence values are defined and explained in the SchemaNode class. """ while node.occur < value: node.occur = value if node.name == "define": ...
java
protected final void write(PrintWriter printWriter, A a, Alphabet<I> inputs) { writeState(printWriter); writeEdge(printWriter); writeETF(printWriter, a, inputs); printWriter.close(); }
python
def projector_generator(ket, bra): """ Generate a Pauli Sum that corresponds to the projection operator |ket><bra| note: ket and bra are numerically ordered such that ket = [msd, ..., lsd] where msd == most significant digit and lsd = least significant digit. :param List ket: string of zeros...
python
def remove_all_lambda_permissions(app_name='', env='', region='us-east-1'): """Remove all foremast-* permissions from lambda. Args: app_name (str): Application name env (str): AWS environment region (str): AWS region """ session = boto3.Session(profile_name=env, region_name=regi...
java
public CreateElasticsearchDomainRequest withAdvancedOptions(java.util.Map<String, String> advancedOptions) { setAdvancedOptions(advancedOptions); return this; }
java
public CharSequence matchesPattern(final CharSequence input, final String pattern) { if (!Pattern.matches(pattern, input)) { fail(String.format(DEFAULT_MATCHES_PATTERN_EX, input, pattern)); } return input; }
python
def _update_fitness(self, action_set): """Update the fitness values of the rules belonging to this action set.""" # Compute the accuracy of each rule. Accuracy is inversely # proportional to error. Below a certain error threshold, accuracy # becomes constant. Accuracy values rang...
java
protected void createVersionHistory(ImportNodeData nodeData) throws RepositoryException { // Generate new VersionHistoryIdentifier and BaseVersionIdentifier // if uuid changed after UC boolean newVersionHistory = nodeData.isNewIdentifer() || !nodeData.isContainsVersionhistory(); if (newVersio...
python
def extract(self, member, path="", set_attrs=True): """Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. `member' may be a filename or a TarInfo object. You can specify a differen...
python
def _drop_labels_or_levels(self, keys, axis=0): """ Drop labels and/or levels for the given `axis`. For each key in `keys`: - (axis=0): If key matches a column label then drop the column. Otherwise if key matches an index level then drop the level. - (axis=1): If...
python
def _build(self, inputs, keep_prob=None, is_training=None, test_local_stats=True): """Connects the AlexNet module into the graph. The is_training flag only controls the batch norm settings, if `False` it does not force no dropout by overriding any input `keep_prob`. To avoid any confusion ...
python
def erase_line(method=EraseMethod.ALL, file=sys.stdout): """ Erase a line, or part of a line. See `method` argument below. Cursor position does not change. Esc[<method>K Arguments: method : One of these possible values: EraseMethod.END or 0: ...
python
def __generic_save_as(self): """Returns False if user has cancelled operation, otherwise True.""" page = self._get_page() if not page.editor.f: return True if page.editor.f.filename: d = page.editor.f.filename else: d = os.path.join(sel...
python
def get_block(self, usage_id, for_parent=None): """ Create an XBlock instance in this runtime. The `usage_id` is used to find the XBlock class and data. """ def_id = self.id_reader.get_definition_id(usage_id) try: block_type = self.id_reader.get_block_type(de...
java
public String getString(String name, String otherwise) { return data.getString(name, otherwise); }
python
def commit_handler(self, cmd): """Process a CommitCommand.""" # These pass through if they meet the filtering conditions interesting_filecmds = self._filter_filecommands(cmd.iter_files) if interesting_filecmds or not self.squash_empty_commits: # If all we have is a single del...
python
def setactive(self, scriptname): """Define the active script See MANAGESIEVE specifications, section 2.8 If scriptname is empty, the current active script is disabled, ie. there will be no active script anymore. :param scriptname: script's name :rtype: boolean ...
python
def add_request_ids_from_environment(logger, name, event_dict): """Custom processor adding request IDs to the log event, if available.""" if ENV_APIG_REQUEST_ID in os.environ: event_dict['api_request_id'] = os.environ[ENV_APIG_REQUEST_ID] if ENV_LAMBDA_REQUEST_ID in os.environ: event_dict['l...
java
public void doNewRecord(boolean bDisplayOption) { super.doNewRecord(bDisplayOption); try { if (this.getOwner().isOpen()) // Don't do first time! { boolean bOldEnableState = this.isEnabledListener(); this.setEnabledListener(false); // J...
java
public Date getTime( String key, Date defaultValue ) throws MissingResourceException { try { return getTime( key ); } catch( MissingResourceException mre ) { return defaultValue; } }
python
def portgroups_configured(name, dvs, portgroups): ''' Configures portgroups on a DVS. Creates/updates/removes portgroups in a provided DVS dvs Name of the DVS portgroups Portgroup dict representations (see module sysdocs) ''' datacenter = _get_datacenter_name() log.inf...
python
def is_domterm(cls): """ :return: whether we are inside DomTerm :rtype: bool """ import os if cls._is_domterm is not None: return cls._is_domterm if not os.environ.get("DOMTERM"): cls._is_domterm = False return False cls...
java
public static List<HistoryDTO> transformToDto(List<History> list) { if (list == null) { throw new WebApplicationException("Null entity object cannot be converted to Dto object.", Status.INTERNAL_SERVER_ERROR); } List<HistoryDTO> result = new ArrayList<HistoryDTO>(); for (Hi...
java
public void setBaselineDurationText(int baselineNumber, String value) { set(selectField(TaskFieldLists.BASELINE_DURATIONS, baselineNumber), value); }
java
public static Configuration get() { Configuration conf = new Configuration(); File cloudConfigPath; if (isWindows()) { cloudConfigPath = new File(getEnvironment().get("APPDATA"), "gcloud"); } else { cloudConfigPath = new File(System.getProperty("user.home"), ".config/gcloud"); } File...
java
public static CronetChannelBuilder forAddress(String host, int port, CronetEngine cronetEngine) { Preconditions.checkNotNull(cronetEngine, "cronetEngine"); return new CronetChannelBuilder(host, port, cronetEngine); }
python
def dir_tails_target(self, rr_id) -> str: """ Return target directory for revocation registry and tails file production. :param rr_id: revocation registry identifier :return: tails target directory """ return join(self.dir_tails_top(rr_id), rev_reg_id2cred_def_id(rr_id)...
java
public void renderIconImage(ImageTag.State state, TreeElement elem) { ArrayList al = _lists[TreeHtmlAttributeInfo.HTML_LOCATION_ICON]; assert(al != null); if (al.size() == 0) return; int cnt = al.size(); for (int i = 0; i < cnt; i++) { TreeHtmlAttrib...
python
def update_alias_verification(sender, instance, **kwargs): """ Flags a user's email as unverified if they change it. Optionally sends a verification token to the new endpoint. """ if isinstance(instance, User): if instance.id: if api_settings.PASSWORDLESS_USER_MARK_EMAIL_VERIFI...
java
public Producer<CloseableReference<PooledByteBuffer>> getLocalFileFetchEncodedImageProducerSequence() { synchronized (this) { if (FrescoSystrace.isTracing()) { FrescoSystrace.beginSection( "ProducerSequenceFactory#getLocalFileFetchEncodedImageProducerSequence"); } if (mLocalF...
python
def add(self, name: str, sig: Tuple, obj: object) -> None: """ Add a file to the cache :param name: name of the object to be pickled :param sig: signature for object :param obj: object to pickle """ if self._cache_directory is not None: if name in self...
java
@SuppressWarnings("unchecked") public EList<String> getPunchList() { return (EList<String>) eGet(Ifc2x3tc1Package.Literals.IFC_MOVE__PUNCH_LIST, true); }
java
public ServiceFuture<VirtualMachineExtensionsListResultInner> getExtensionsAsync(String resourceGroupName, String vmName, String expand, final ServiceCallback<VirtualMachineExtensionsListResultInner> serviceCallback) { return ServiceFuture.fromResponse(getExtensionsWithServiceResponseAsync(resourceGroupName, vm...
python
def _generate_nodes(self, name, command, templates=None): """Generate the relevant Sphinx nodes. Generates a section for the Tree datamodel. Formats a tree section as a list-table directive. Parameters: name (str): The name of the config to be documented, e...
python
def enable( self, cmd="enable", pattern="password", re_flags=re.IGNORECASE, default_username="manager", ): """Enter enable mode""" if self.check_enable_mode(): return "" output = self.send_command_timing(cmd) if ( "usern...
java
public static Map<CurrencyPair, Fee> adaptDynamicTradingFees( BitfinexTradingFeeResponse[] responses, List<CurrencyPair> currencyPairs) { Map<CurrencyPair, Fee> result = new HashMap<>(); for (BitfinexTradingFeeResponse response : responses) { BitfinexTradingFeeResponse.BitfinexTradingFeeResponseRow[...
python
def next_message(self): """Block until a message(request or notification) is available. If any messages were previously enqueued, return the first in queue. If not, run the event loop until one is received. """ msg = self._session.next_message() if msg: retur...
java
public void ifPropertyValueEquals(String template, Properties attributes) throws XDocletException { String value = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), attributes.getProperty(ATTRIBUTE_NAME)); String expected = attributes.getProperty(ATTRIBUTE_VALUE); if (value ...
python
def toggle_object_status(self, objname): """ Toggle boolean-valued sensor status between ``True`` and ``False``. """ o = getattr(self.system, objname) o.status = not o.status self.system.flush() return o.status
java
protected final void runOnGlThread(final Runnable r) { getGVRContext().runOnGlThread(new Runnable() { public void run() { FPSCounter.timeCheck("runOnGlThread <START>: " + r); r.run(); FPSCounter.timeCheck("runOnGlThread <END>: " + r); } ...
java
@Override public void mouseClicked(MouseEvent evt) { if (evt.getClickCount() == 2) { triggerMaximisation((Component) evt.getSource()); } }
python
def operates_on(self, qubits: Iterable[raw_types.Qid]) -> bool: """Determines if the moment has operations touching the given qubits. Args: qubits: The qubits that may or may not be touched by operations. Returns: Whether this moment has operations involving the qubits....
python
def update_file(filename, items): '''Edits the given file in place, replacing any instances of {key} with the appropriate value from the provided items dict. If the given filename ends with ".xml" values will be quoted and escaped for XML. ''' # TODO: Implement something in the templates to denote w...
java
public void setDatasource(Object datasource) throws PageException, ClassException, BundleException { if (datasource == null) return; data.rawDatasource = datasource; data.datasource = toDatasource(pageContext, datasource); }
java
private File createAttachFile(int pid) throws IOException { String fn = ".attach_pid" + pid; String path = "/proc/" + pid + "/cwd/" + fn; File f = new File(path); try { f.createNewFile(); } catch (IOException x) { f = new File(tmpdir, fn); f.cr...
java
public BinaryKey moveValue( BinaryKey key, String source, String destination ) throws BinaryStoreException { final BinaryStore sourceStore; if (source == null) { sourceStore = findBinaryStoreContainingKey(key); } else {...
python
def parse(query_string, unquote=True, normalized=False, encoding=DEFAULT_ENCODING): ''' Main parse function @param query_string: @param unquote: unquote html query string ? @param encoding: An optional encoding used to decode the keys and values. Defaults to utf-8, which the W3C declares as a d...
python
def resolve_object(self, object_arg_name, resolver): """ A helper decorator to resolve object instance from arguments (e.g. identity). Example: >>> @namespace.route('/<int:user_id>') ... class MyResource(Resource): ... @namespace.resolve_object( ... obj...
java
public boolean compatible( PropertySet properties) { boolean isCompatible; Iterator<IAssertion> assertions; for( assertions = getAssertions(), isCompatible = !assertions.hasNext(); !isCompatible && assertions.hasNext(); isCompatible = assertions.next().comp...
java
public <N, S extends Session<L>> void discoverChildren( Resource<L> parent, ResourceType<L> childType, Session<L> session, EndpointService<L, S> service, Consumer<Resource<L>> resourceConsumer) { try { L parentLocation = parent != null ? ...
java
@Nullable public static HourRange valueOf(@Nullable final String str) { if (str == null) { return null; } return new HourRange(str); }
python
def _forward_backward(self, logprob): """Runs forward-backward algorithm on observation log probs Given the log probability of each timepoint being generated by each event, run the HMM forward-backward algorithm to find the probability that each timepoint belongs to each event (based on...
java
public final static Reliability getReliabilityByName(String name) throws NullPointerException, IllegalArgumentException { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.info(tc, "Name = " + name); if (name == null) { throw new Nul...
python
def _get_doc_by_raw_offset(self, doc_id): """ Load document from xml using bytes offset information. XXX: this is not tested under Windows. """ bounds = self._get_meta()[str(doc_id)].bounds return xml_utils.load_chunk(self.filename, bounds)
python
def open01(x, limit=1.e-6): """Constrain numbers to (0,1) interval""" try: return np.array([min(max(y, limit), 1. - limit) for y in x]) except TypeError: return min(max(x, limit), 1. - limit)
java
@Override public void setBasicAuthCredential(Subject basicAuthSubject, String realm, String username, @Sensitive String password) throws CredentialException { CredentialProvider provider = basicAuthCredentialProvider.getService(); if (provider != null) { Hashtable<String, Object> hashtab...
python
def get_machine_id(machine, cwd): ''' returns the salt_id name of the Vagrant VM :param machine: the Vagrant machine name :param cwd: the path to Vagrantfile :return: salt_id name ''' name = __utils__['sdb.sdb_get'](_build_machine_uri(machine, cwd), __opts__) return name
java
public Optional<UUID> getId(final Object object) { return Optional.ofNullable(objectToId.get(object)); }
python
def from_content_type(cls, content_type): """ Build a serializer object from a MIME Content-Type string. :param str content_type: The Content-Type string to parse. :return: A new serializer instance. :rtype: :py:class:`.Serializer` """ name = content_type options = {} if ';' in content_type: name,...
java
public List<Attribute> getAttributes(String domain, String beanName, String[] attributes) throws Exception { checkClientConnected(); return getAttributes(ObjectNameUtil.makeObjectName(domain, beanName), attributes); }
java
@Override public Set<String> mergePossibleUserAttributeNames(final Set<String> toModify, final Set<String> toConsider) { toModify.addAll(toConsider); return toModify; }
java
public void addDefaultProperty(String key, String value) { if (StringUtils.isEmpty(key)) { return; } defaultProperties.put(key, value); }
python
def send(self, name, sender=None, **kwargs): """ Sends the signal. Return every function response\ that was hooked to hook-name as a list: [(func, response), ] :param str name: The hook name :param class sender: Optional sender __class__ to which\ registered callback sho...
python
def to_entity(entity_type, value, fields): """ Internal API: Returns an instance of an entity of type entity_type with the specified value and fields (stored in dict). This is only used by the local transform runner as a helper function. """ e = entity_type(value) for k, v in fields.items(): ...
python
def _main(args, prog_name): """Process the command line arguments of this script and dispatch.""" # get options and arguments ui = getUI(prog_name, args) if ui.optionIsSet("test"): # just run unit tests unittest.main(argv=[sys.argv[0]]) elif ui.optionIsSet("help"): # just show help ui.usage()...
python
def GetParentFileEntry(self): """Retrieves the parent file entry. Returns: APFSContainerFileEntry: parent file entry or None if not available. """ volume_index = apfs_helper.APFSContainerPathSpecGetVolumeIndex( self.path_spec) if volume_index is None: return None return sel...
python
def team_profiles(self, team): """ Get team's social media profiles linked on their TBA page. :param team: Team to get data on. :return: List of Profile objects. """ return [Profile(raw) for raw in self._get('team/%s/social_media' % self.team_key(team))]
java
private void retrieveNextPage() { if (this.pageSize < Long.MAX_VALUE || this.itemLimit < Long.MAX_VALUE) { this.request.query("limit", Math.min(this.pageSize, this.itemLimit - this.count)); } else { this.request.query("limit", null); } ResultBodyCollection<T> page...
java
public static DateTime parseDate(String dateString) { dateString = normalize(dateString); return parse(dateString, DatePattern.NORM_DATE_FORMAT); }
python
def cross_val_score(estimator, X, y=None, scoring=None, cv=None, n_jobs=1, verbose=0, fit_params=None, pre_dispatch='2*n_jobs'): """Evaluate a score by cross-validation Parameters ---------- estimator : estimator object implementing 'fit' The object to use to fit the data. ...
java
public void setXSIZE(Integer newXSIZE) { Integer oldXSIZE = xsize; xsize = newXSIZE; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.IDD__XSIZE, oldXSIZE, xsize)); }
java
@Beta public final void parse(Object destination, CustomizeJsonParser customizeParser) throws IOException { ArrayList<Type> context = new ArrayList<Type>(); context.add(destination.getClass()); parse(context, destination, customizeParser); }
python
def _get_event(receiver_id, event_id): """Find event and check access rights.""" event = Event.query.filter_by( receiver_id=receiver_id, id=event_id ).first_or_404() try: user_id = request.oauth.access_token.user_id except AttributeError: user...
java
BlockCommand getInvalidateBlocks(int maxblocks) { Block[] deleteList = null; synchronized (invalidateBlocks) { deleteList = invalidateBlocks.pollToArray(new Block[Math.min( invalidateBlocks.size(), maxblocks)]); } return (deleteList == null || deleteList.length == 0) ? null: new...
python
def get_fun(fun): ''' Return a dict of the last function called for all minions ''' serv = _get_serv(ret=None) sql = '''select first(id) as fid, first(full_ret) as fret from returns where fun = '{0}' group by fun, id '''.format(fun) data = serv.que...
java
public boolean get(String name, boolean defaultValue) throws IllegalArgumentException { ObjectSlot slot = findMandatorySlot(name, boolean.class); return slot.defaulted ? defaultValue : ((Boolean) slot.fieldValue).booleanValue(); }
python
def parse_args(argString=None): """Parses the command line options and arguments. :returns: A :py:class:`argparse.Namespace` object created by the :py:mod:`argparse` module. It contains the values of the different options. ====================== ====== =========================...
python
def detectSmartphone(self): """Return detection of a general smartphone device Checks to see whether the device is *any* 'smartphone'. Note: It's better to use DetectTierIphone() for modern touchscreen devices. """ return self.detectTierIphone() \ or self.detectS60Os...
java
@Override public Future<U> link(U current, BasicProfile to) { return toScala(doLink(current, to)); }
python
def add_actor(self, uinput, reset_camera=False, name=None, loc=None, culling=False): """ Adds an actor to render window. Creates an actor if input is a mapper. Parameters ---------- uinput : vtk.vtkMapper or vtk.vtkActor vtk mapper or vtk a...
python
def _set_box(self): """ Set the box size for the molecular assembly """ net_volume = 0.0 for idx, mol in enumerate(self.mols): length = max([np.max(mol.cart_coords[:, i])-np.min(mol.cart_coords[:, i]) for i in range(3)]) + 2.0 ne...
java
public java.lang.String getResource() { java.lang.Object ref = resource_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); resour...
java
public void fine( String sourceClass, String sourceMethod, String msg ) { logp(Level.FINE, sourceClass, sourceMethod, msg); }
python
def set_reviewing(self, hit_id, revert=None): """ Update a HIT with a status of Reviewable to have a status of Reviewing, or reverts a Reviewing HIT back to the Reviewable status. Only HITs with a status of Reviewable can be updated with a status of Reviewing. Similarly, only ...
python
def __set_workdir(self): """Set current script directory as working directory""" fname = self.get_current_filename() if fname is not None: directory = osp.dirname(osp.abspath(fname)) self.open_dir.emit(directory)
java
public static JournalManager createJournal(Configuration conf, URI uri, NamespaceInfo nsInfo, NameNodeMetrics metrics) { Class<? extends JournalManager> clazz = getJournalClass(conf, uri.getScheme()); try { Constructor<? extends JournalManager> cons = clazz.getConstructor( Configu...
python
def _generate_validator(self, field): """Emits validator if data type has associated validator.""" validator = self._determine_validator_type(field.data_type, fmt_var(field.name), field.has_default) ...
java
private ChocoConstraint build(Constraint cstr) throws SchedulerException { ChocoMapper mapper = params.getMapper(); ChocoConstraint cc = mapper.get(cstr); if (cc == null) { throw new SchedulerModelingException(origin, "No implementation mapped to '" + cstr.getClass().getSimpleName() ...
java
public static int cuStreamWriteValue32(CUstream stream, CUdeviceptr addr, int value, int flags) { return checkResult(cuStreamWriteValue32Native(stream, addr, value, flags)); }
java
@Override public T addAsManifestResource(URL resource, ArchivePath target) throws IllegalArgumentException { Validate.notNull(resource, "Resource should be specified"); Validate.notNull(target, "Target should be specified"); File file = new File(resource.getFile()); if (file.exists(...
python
def update(self, friendly_name=values.unset, identity=values.unset, deployment_sid=values.unset, enabled=values.unset): """ Update the DeviceInstance :param unicode friendly_name: A human readable description for this Device. :param unicode identity: An identifier of the ...
python
def _from_arrays(self, vertices, faces, deep=True, verts=False): """ Set polygons and points from numpy arrays Parameters ---------- vertices : np.ndarray of dtype=np.float32 or np.float64 Vertex array. 3D points. faces : np.ndarray of dtype=np.int64 ...
java
public JobRun withPredecessorRuns(Predecessor... predecessorRuns) { if (this.predecessorRuns == null) { setPredecessorRuns(new java.util.ArrayList<Predecessor>(predecessorRuns.length)); } for (Predecessor ele : predecessorRuns) { this.predecessorRuns.add(ele); } ...
java
public static final EnhancementsParser createDefaultParser(HttpResponse response) throws EnhancementParserException, IOException { ParserConfig config = new ParserConfig(); // Prevent malformed datetime values // TODO review - added to prevent errors when parsing invalid dates config.set...
python
def add_flow(self, flow): """ Add an :class:`Flow` flow to the scheduler. """ if hasattr(self, "_flow"): raise self.Error("Only one flow can be added to the scheduler.") # Check if we are already using a scheduler to run this flow flow.check_pid_file() ...
java
public BigMoney minusRetainScale(BigMoneyProvider moneyToSubtract, RoundingMode roundingMode) { BigMoney toSubtract = checkCurrencyEqual(moneyToSubtract); return minusRetainScale(toSubtract.getAmount(), roundingMode); }
java
@Override public void append(MapTile other, int offsetX, int offsetY) { Check.notNull(other); if (!map.isCreated()) { map.create(other.getTileWidth(), other.getTileHeight(), 1, 1); } if (other.getTileWidth() != map.getTileWidth() || other.getTileHeight() != ...
python
def d(self,value): """ set anisotropic scaling """ assert value.shape[0]==self._P*self._N, 'd dimension mismatch' self._d = value self.clear_cache('Yhat','Xhat','Areml','Areml_eigh','Areml_chol','Areml_inv','beta_hat','B_hat', 'LRLdiag_Xhat_tens','LRLdiag_Yhat','...