language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
protected LightweightTypeReference toLightweightTypeReference(JvmType type, EObject context) { final StandardTypeReferenceOwner owner = new StandardTypeReferenceOwner(getServices(), context); final LightweightTypeReferenceFactory factory = new LightweightTypeReferenceFactory(owner, false); return factory.toLightw...
java
private void updateConnecting() throws IOException { if (clientId == -1) { // Receive id clientId = in.readByte(); // Send the name out.writeByte(NetworkMessageSystemId.CONNECTING); out.writeByte(clientId); final byte[] data = c...
python
def check_output(args): """Runs command and returns the output as string.""" log.debug('run: %s', args) out = subprocess.check_output(args=args).decode('utf-8') log.debug('out: %r', out) return out
python
def tts_langs(): """Languages Google Text-to-Speech supports. Returns: dict: A dictionnary of the type `{ '<lang>': '<name>'}` Where `<lang>` is an IETF language tag such as `en` or `pt-br`, and `<name>` is the full English name of the language, such as `English` or `Portuguese...
python
def compareNamedTuple(tuple1: NamedTuple, tuple2: NamedTuple, *fields): """ Compare provided fields of 2 named tuples for equality and returns true :param tuple1: :param tuple2: :param fields: :return: """ tuple1 = tuple1._asdict() tuple2 = tuple2._asdict() comp = [] for fiel...
java
private static byte[] consumeRenewToken(ExtendedGSSContext c, byte[] wrappedToken) throws GSSException { if (!GSIConstants.MODE_SSL.equals(c.getOption(GSSConstants.GSS_MODE))) { throw new GSSException(GSSException.NO_CONTEXT); } byt...
java
public BooleanExpression in(T... right) { if (right.length == 1) { return eq(right[0]); } else { return Expressions.booleanOperation(Ops.IN, mixin, ConstantImpl.create(ImmutableList.copyOf(right))); } }
python
def generate_payload(exclude=None, **kwargs): """ Generate payload Usage: payload = generate_payload(**locals(), exclude=['foo']) :param exclude: :param kwargs: :return: dict """ if exclude is None: exclude = [] return {key: value for key, value in kwargs.items() if ...
java
public static <T> Chain<T> chain(final List<T> list) { return new U.Chain<T>(list); }
java
public Collection<String> getAllLoggerNames() { Set<String> loggerNames = new TreeSet<>(); for (Logger logger : getParentLoggers()) { loggerNames.add(logger.getName()); } for (Logger logger : getLoggers()) { loggerNames.add(logger.getName()); } if (!customLoggers.isEmpty()) { for (Entry<Lo...
python
def walk(dispatcher, node, definition=None): """ The default, standalone walk function following the standard argument ordering for the unparsing walkers. Arguments: dispatcher a Dispatcher instance, defined earlier in this module. This instance will dispatch out the correct calla...
java
private static URL safeURL(String urlString) throws ClassNotFoundException { try { return new URL(urlString); } catch (MalformedURLException exception) { throw new ClassNotFoundException(exception.getMessage()); } }
python
def dict_find_key(dd, value): """ Find first suitable key in dict. :param dd: :param value: :return: """ key = next(key for key, val in dd.items() if val == value) return key
python
def _call(self, x, out=None): """Calculate the spatial gradient of ``x``.""" if out is None: out = self.range.element() x_arr = x.asarray() ndim = self.domain.ndim dx = self.domain.cell_sides for axis in range(ndim): with writable_array(out[axis]...
python
def run(self): """ Process all log messages, until `stop()` is called. Intended to run in its own thread. """ while True: msg = self._queue.get() if msg is _SHUTDOWN: break if self._enabled: print msg
python
def run(steps, iter_vars=None, data_out=None, out_interval=1, out_base_tables=None, out_run_tables=None, compress=False, out_base_local=True, out_run_local=True): """ Run steps in series, optionally repeatedly over some sequence. The current iteration variable is set as a global injectable ...
java
public static <T> T newInstance(final Class<T> clas) { try { return clas.newInstance(); } catch (final Exception e) { throw new RuntimeException(e); } }
java
public QueueBuilder<T> threadFactory(ThreadFactory factory) { Preconditions.checkNotNull(factory, "factory cannot be null"); this.factory = factory; return this; }
java
protected FromHostPrimitiveResult < T > fromHostInternal( Class < T > javaClass, CobolContext cobolContext, byte[] hostData, int start) { int hostBytesLen = getBytesLen(); int pos = start; // Copies the mainframe data into a byte buffer large enough for the // t...
python
def make_parser(add_help=True, exclude_args=None): """Return an argparse.ArgumentParser object with losser's arguments. Other projects can call this to get an ArgumentParser with losser's command line interface to use as a parent parser for their own parser. For example:: parent_parser = losse...
python
def read_locked(*args, **kwargs): """Acquires & releases a read lock around call into decorated method. NOTE(harlowja): if no attribute name is provided then by default the attribute named '_lock' is looked for (this attribute is expected to be a :py:class:`.ReaderWriterLock`) in the instance object th...
java
protected SearchResult executeSearch(final ISearch _search) throws EFapsException { final SearchResult ret = new SearchResult(); try { LOG.debug("Starting search with: {}", _search.getQuery()); final StandardQueryParser queryParser = new StandardQueryParser(Index.getA...
java
public static void setTimeout(Stub stub, int timeout) { if (stub instanceof org.apache.axis.client.Stub) { ((org.apache.axis.client.Stub)stub).setTimeout(timeout); } }
python
def parse_socket_info(cls, info): """ Parse string that is formed like '[address]<:port>' and return corresponding :class:`.WIPV4ScketInfo` object :param info: string to parse :return: WIPV4ScketInfo """ info = info.split(':') if len(info) > 2: raise ValueError('Incorrect socket info specified') ad...
java
@BetaApi public final Operation insertInterconnectAttachment( ProjectRegionName region, InterconnectAttachment interconnectAttachmentResource) { InsertInterconnectAttachmentHttpRequest request = InsertInterconnectAttachmentHttpRequest.newBuilder() .setRegion(region == null ? null : regi...
java
public Result<List<Data>> readByType(AuthzTrans trans, String ns, String type) { return psByType.read(trans, R_TEXT, new Object[]{ns, type}); }
python
def generate_crash_handler_decorator(error_decorator=None): """Return the crash_handler to pass to pymacaron_core, with optional error decoration""" def crash_handler(f): """Return a decorator that reports failed api calls via the error_reporter, for use on every server endpoint""" @wr...
python
def list_domains(): ''' Return a list of virtual machine names on the minion CLI Example: .. code-block:: bash salt '*' virt.list_domains ''' with _get_xapi_session() as xapi: hosts = xapi.VM.get_all() ret = [] for _host in hosts: if xapi.VM.get_re...
java
@Override public List<CommerceAddress> findByG_C_C_DS(long groupId, long classNameId, long classPK, boolean defaultShipping, int start, int end, OrderByComparator<CommerceAddress> orderByComparator) { return findByG_C_C_DS(groupId, classNameId, classPK, defaultShipping, start, end, orderByComparator, true); ...
python
def _configure_saver(checkpoint_dir, checkpoint_interval): """Returns a tf.train.CheckpointSaverHook for autosaving checkpoints.""" saver = tf.train.Saver() return tf.train.CheckpointSaverHook( checkpoint_dir=checkpoint_dir, save_steps=checkpoint_interval, saver=saver)
java
public V remove (int key) { Record<V> removed = removeImpl(key, true); return (removed == null) ? null : removed.value; }
java
@Reference(name = KEY_FEATURE_SECURITY_COLLAB, service = FeatureAuthorizationTableService.class) protected void setFeatureCollabAuthzTable(ServiceReference<FeatureAuthorizationTableService> ref) { featureCollabAuthzTableRef.setReference(ref); }
java
public boolean isSpecified (String uri, String localName) { int index = getIndex (uri, localName); if (index < 0) throw new IllegalArgumentException ( "No such attribute: local=" + localName + ", namespace=" + uri); return specified [index]; }
python
def build_dictionary(self): """ Return a dictionary of characterIds to their defining tags. """ d = {} for t in self.all_tags_of_type(DefinitionTag, recurse_into_sprites = False): if t.characterId in d: #print 'redefinition of characterId %d:' % (t.cha...
python
def extract_prefix(self, prefix): """ It extracts an irc msg prefix chunk """ field = re.match(PREFIX_REG, prefix if prefix else '') return (prefix,) if not field else field.group(1, 2, 3)
java
public JComponent addScreenControl(Container parent, Converter fieldInfo) { JComponent component = this.createScreenComponent(fieldInfo); if (component instanceof ScreenComponent) if (((ScreenComponent)component).getConverter() != null) fieldInfo = (Converter)((ScreenComp...
java
private void setOption(String opt, String argument) { String[] option = { opt, argument }; options.append(option); }
python
def _iterslice(self, slice): """Yield records from a slice index.""" indices = range(*slice.indices(len(self._records))) if self.is_attached(): rows = self._enum_attached_rows(indices) if slice.step is not None and slice.step < 0: rows = reversed(list(rows...
python
def append(x: T, xs: Iterable[T]) -> Iterator[T]: """ Append a value to an iterable. Parameters ---------- x An element of type T. xs An iterable of elements of type T. Returns ------- Iterator An iterator that yields elements of *xs*, then yields *x*. Exa...
python
def auth(opts, whitelist=None): ''' Returns the auth modules :param dict opts: The Salt options dictionary :returns: LazyLoader ''' return LazyLoader( _module_dirs(opts, 'auth'), opts, tag='auth', whitelist=whitelist, pack={'__salt__': minion_mods(opts)},...
python
def _check_state(self, state): """ Checks if a list representing the state of the variables is valid. """ if not hasattr(state, '__iter__') or isinstance(state, six.string_types): raise ValueError('Start state must be a non-string iterable object.') state_vars = {s.va...
python
def bound_variables(xmrs): """Return the list of all bound variables in *xmrs*""" bvs = set( ep.intrinsic_variable for ep in xmrs.eps() if ep.is_quantifier() and ep.intrinsic_variable is not None ) return sorted(bvs, key=var_id)
python
def printex(ex, msg='[!?] Caught exception', prefix=None, key_list=[], locals_=None, iswarning=False, tb=TB, pad_stdout=True, N=0, use_stdout=False, reraise=False, msg_=None, keys=None, colored=None): """ Prints (and/or logs) an exception with relevant info Args: ...
python
def gtype(n): """ Return the a string with the data type of a value, for Graph data """ t = type(n).__name__ return str(t) if t != 'Literal' else 'Literal, {}'.format(n.language)
java
static Set<Path> findFiles(final String logDir, final ModelNode model, final boolean relativize) throws IOException { if (logDir == null) { return Collections.emptySet(); } // Get the list of valid file names final Collection<String> validFileNames = findValidFileNames(model)...
python
def _handler(func): "Decorate a command handler" def _wrapped(*a, **k): r = func(*a, **k) if r is None: r = 0 return r return staticmethod(_wrapped)
python
def _handle_sdp_target_state_updated(sdp_state: SDPState): """Respond to an SDP target state change event. This function sets the current state of SDP to the target state if that is possible. TODO(BMo) This cant be done as a blocking function as it is here! """ LOG.info('Handling SDP target st...
python
def end_scan(self): """Ends an ongoing BLE scan started by :meth:`begin_scan`. Returns: a :class:`ScanResults` object containing the scan results. """ # TODO check states before/after self._set_state(self._STATE_GAP_END) self.api.ble_cmd_gap_end_procedure() ...
java
@Override public void include(Readable in, String source) throws IOException { if (cursor != end) { release(); } if (includeStack == null) { includeStack = new ArrayDeque<>(); } includeStack.push(includeLevel); i...
java
protected void addAppendingAddOnToInputGroup(FacesContext context, ResponseWriter rw, UIComponent appendingAddOnFacet, boolean hasAppendingAddOn, SelectOneMenu menu) throws IOException { if (hasAppendingAddOn) { R.decorateFacetComponent(menu, appendingAddOnFacet, context, rw); } }
java
@Override public SequenceRecord loadSequenceFromMetaData(RecordMetaData recordMetaData) throws IOException { SequenceRecord next = sequenceRecordReader.loadSequenceFromMetaData(recordMetaData); next.setSequenceRecord(transformProcess.executeSequence(next.getSequenceRecord())); return next; ...
java
@Override public double similarity(int vertexIdx1, int vertexIdx2) { if (vertexIdx1 == vertexIdx2) return 1.0; INDArray vector = Transforms.unitVec(getVertexVector(vertexIdx1)); INDArray vector2 = Transforms.unitVec(getVertexVector(vertexIdx2)); return Nd4j.getBlasWrappe...
python
def p_regex_literal(self, p): """regex_literal : REGEX""" p[0] = self.asttypes.Regex(p[1]) p[0].setpos(p)
python
def set_decade_lims(axis=None,direction=None): r''' Set limits the the floor/ceil values in terms of decades. :options: **axis** ([``plt.gca()``] | ...) Specify the axis to which to apply the limits. **direction** ([``None``] | ``'x'`` | ``'y'``) Limit the application to a certain direction (default: b...
java
public List getEmbeddedObjectList(DBCollection dbCollection, EntityMetadata m, String documentName, BasicDBObject mongoQuery, String result, BasicDBObject orderBy, int maxResult, int firstResult, BasicDBObject keys, final KunderaMetadata kunderaMetadata) throws PropertyAccess...
java
@Override public void delete(Object entity, Object rowKey) { EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entity.getClass()); MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel( m.getPersistenceUnit()); ...
python
def get_for_update(self, connection_name='DEFAULT', **kwargs): """ http://docs.sqlalchemy.org/en/latest/orm/query.html?highlight=update#sqlalchemy.orm.query.Query.with_for_update # noqa """ if not kwargs: raise InvalidQueryError( "Can not execute a query wit...
java
public Single<Boolean> revokeToken(FullHttpRequest req) throws OAuthException { RevokeTokenRequest revokeRequest = new RevokeTokenRequest(req); revokeRequest.checkMandatoryParams(); String clientId = revokeRequest.getClientId(); // check valid client_id, status does not matter as token o...
python
def feed(self): "Feed a line from the contents of the GPS log to the daemon." line = self.testload.sentences[self.index % len(self.testload.sentences)] if "%Delay:" in line: # Delay specified number of seconds delay = line.split()[1] time.sleep(int(delay)) ...
java
public void marshall(KinesisFirehoseDestination kinesisFirehoseDestination, ProtocolMarshaller protocolMarshaller) { if (kinesisFirehoseDestination == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(k...
python
def generate_data(self, data_dir, tmp_dir, task_id=-1): """The function generating the data.""" filepath_fns = { problem.DatasetSplit.TRAIN: self.training_filepaths, problem.DatasetSplit.EVAL: self.dev_filepaths, problem.DatasetSplit.TEST: self.test_filepaths, } # We set shuffle...
java
public static <T> Reference<T> create(ReferenceType type, T referent) { return create(type, referent, null); }
python
def HelloWorld(handler, t): """ This is the traditional "Hello, World" function. The idiom is used throughout the API. We construct a Tropo object, and then flesh out that object by calling "action" functions (in this case, tropo.say). Then call tropo.Render, which translates the Tropo object into JSON format. ...
java
public static VatIdMapSharedConstants create() { if (vatIdMapConstants == null) { // NOPMD it's thread save! synchronized (VatIdMapConstants.class) { if (vatIdMapConstants == null) { vatIdMapConstants = GWT.create(VatIdMapConstants.class); } } } return vatIdMapConstants...
python
def make_subscriber(self, my_args=None): """ not implemented :return: """ LOGGER.debug("zeromq.Driver.make_subscriber") if my_args is None: raise exceptions.ArianeConfError('subscriber arguments') if not self.configuration_OK or self.connection_args is...
python
def cache(self, delete_lineage=False): """ Caches the result of the Sequence so far. This means that any functions applied on the pipeline before cache() are evaluated, and the result is stored in the Sequence. This is primarily used internally and is no more helpful than to_list() exter...
python
def name_to_hex(name, spec=u'css3'): """ Convert a color name to a normalized hexadecimal color value. The optional keyword argument ``spec`` determines which specification's list of color names will be used; valid values are ``html4``, ``css2``, ``css21`` and ``css3``, and the default is ``css...
python
def create_asset_model(self, ): """Return a treemodel with the levels: project, assettype, asset and reftrack type :returns: a treemodel :rtype: :class:`jukeboxcore.gui.treemodel.TreeModel` :raises: None """ rootdata = treemodel.ListItemData(['Name']) rootitem = ...
python
def load(cls, path:PathOrStr, cache_name:PathOrStr='tmp', processor:PreProcessor=None, **kwargs): "Load a `TextDataBunch` from `path/cache_name`. `kwargs` are passed to the dataloader creation." warn("""This method is deprecated and only kept to load data serialized in v1.0.43 or earlier. ...
python
def write_text(filename, tracklisting): """Handle writing tracklisting to text.""" print("Saving text file.") try: write_listing_to_textfile(filename + '.txt', tracklisting) except IOError: # if all else fails, just print listing print("Cannot write text file to path: {}".format(...
python
def make_organisms(self, genome_list, genome_dir): '''Organism factory method. Appends organisms to the organisms list. Args genome_list (list) genome_dir (string) ''' for genome in genome_list: genome_path = genome_dir + genome ...
python
def set_grid_data(self): """Populate the attrs that hold grid data.""" if self._grid_data_is_set: return self._set_mult_grid_attr() if not np.any(getattr(self, 'sfc_area', None)): try: sfc_area = _grid_sfc_area(self.lon, self.lat, self.lon_bounds, ...
java
public void chainPolicyHandlers() { IReadWriteStream<H> previousHandler = null; Iterator<PolicyWithConfiguration> iterator = iterator(); while (iterator.hasNext()) { final PolicyWithConfiguration pwc = iterator.next(); final IPolicy policy = pwc.getPolicy(); f...
java
public V get(int[] stampHolder) { Pair<V> pair = this.pair; stampHolder[0] = pair.stamp; return pair.reference; }
python
def get_audits(): """Get OS hardening PAM authentication audits. :returns: dictionary of audits """ audits = [] settings = utils.get_settings('os') if settings['auth']['pam_passwdqc_enable']: audits.append(PasswdqcPAM('/etc/passwdqc.conf')) if settings['auth']['retries']: ...
python
def get_board_mapping_parent_items(self, team_context, child_backlog_context_category_ref_name, workitem_ids): """GetBoardMappingParentItems. [Preview API] Returns the list of parent field filter model for the given list of workitem ids :param :class:`<TeamContext> <azure.devops.v5_0.work.models...
python
def error(*tokens: Token, **kwargs: Any) -> None: """ Print an error message """ tokens = [bold, red, "Error:"] + list(tokens) # type: ignore kwargs["fileobj"] = sys.stderr message(*tokens, **kwargs)
java
public void auditUpdateNotificationV3Event(RFC3881EventOutcomeCodes eventOutcome, String pixMgrIpAddress, String sendingFacility, String sendingApp, String receivingFacility, String receivingApp, String hl7MessageId, String[] patientIds, List<CodedValueType> purposesOfUse, List<CodedValu...
python
def update_node(node, flush=True, **kwargs): """ Update a node. If new attributes are present, they will be added to the node. The non-presence of attributes does not remove them. The flush argument indicates whether dbsession.flush should be called. THis is set to False when update_node is cal...
java
protected void localRelease() { super.localRelease(); _fatalError = false; _templatePage = null; _innerErrors = null; _reportErrors = false; _savedContext = null; }
python
def lru_append(kc, lru, kckey, maxsize): """Delete old data from ``kc``, then add the new ``kckey``. :param kc: a three-layer keycache :param lru: an :class:`OrderedDict` with a key for each triple that should fill out ``kc``'s three layers :param kckey: a triple that indexes into ``kc``, which will be...
java
public java.util.List<ConfigurationItem> getConfigurationItems() { if (configurationItems == null) { configurationItems = new com.amazonaws.internal.SdkInternalList<ConfigurationItem>(); } return configurationItems; }
python
def post_collection(self, session, data, api_type): """ Create a new Resource. :param session: SQLAlchemy session :param data: Request JSON Data :param params: Keyword arguments """ model = self._fetch_model(api_type) self._check_json_data(data) ...
python
def from_code(cls, code_object): """ Disassemble a Python code object and make a Code object from the bits. This is the expected way to make a Code instance. But you are welcome to call Code() directly if you wish. """ # It's an annoyance to keep having to add ".__code__"...
python
def utils(opts, whitelist=None, context=None, proxy=proxy): ''' Returns the utility modules ''' return LazyLoader( _module_dirs(opts, 'utils', ext_type_dirs='utils_dirs'), opts, tag='utils', whitelist=whitelist, pack={'__context__': context, '__proxy__': proxy or ...
java
@Pure public IntegerProperty yProperty() { if (this.y == null) { this.y = new SimpleIntegerProperty(this, MathFXAttributeNames.Y); } return this.y; }
python
def lookup_ids(self, keys): """Lookup the integer ID associated with each (namespace, key) in the keys list""" keys_len = len(keys) ids = {namespace_key: None for namespace_key in keys} start = 0 bulk_insert = self.bulk_insert query = 'SELECT namespace, key, id FR...
java
@Override public void writeXML(XMLOutput xmlOutput) throws IOException { xmlOutput.openTag(ELEMENT_NAME, new XMLAttributeList().addAttribute("class", className)); for (Iterator<String> i = featureIterator(); i.hasNext();) { String feature = i.next(); xmlOutput.openCloseTag(FE...
java
protected void deleteAlias(MonolingualTextValue alias) { String lang = alias.getLanguageCode(); AliasesWithUpdate currentAliases = newAliases.get(lang); if (currentAliases != null) { currentAliases.aliases.remove(alias); currentAliases.deleted.add(alias); curr...
java
public static Class<?> loadClass(String name, boolean isInitialized) throws UtilException { return loadClass(name, null, isInitialized); }
python
def create_pending_after_task(self): """ Creates pending task results in a dict on self.after_result with task string as key. It will also create a list on self.tasks that is used to make sure the serialization of the results creates a correctly ordered list. """ for task...
java
public void hideKeyboard() { InputMethodManager inputMethodManager = (InputMethodManager) getContext().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(mPhoneEdit.getWindowToken(), 0); }
java
public static String format(final String str) { final NumericShaper shaper = NumericShaper.getContextualShaper(NumericShaper.EASTERN_ARABIC); final char[] c = str.toCharArray(); shaper.shape(c, 0, c.length, NumericShaper.EASTERN_ARABIC); return new String(c); }
java
public void commit(ICommitChanges changes, boolean incrementVersions, Runnable r) { beginWrite(); try { checkForConcurrentModifications(changes, incrementVersions); saveChanges(changes); if (r != null) { r.run(); } } ...
python
def remove(self, connection): '''Remove a connection''' key = (connection.host, connection.port) with self._lock: found = self._connections.pop(key, None) try: self.close_connection(found) except Exception as exc: logger.warn('Failed to close %...
python
def ParseOptions(cls, options, analysis_plugin): """Parses and validates options. Args: options (argparse.Namespace): parser options. analysis_plugin (VirusTotalAnalysisPlugin): analysis plugin to configure. Raises: BadConfigObject: when the output module object is of the wrong type. ...
java
public static <T> com.google.common.util.concurrent.ListenableFuture<T> toGuavaListenableFuture(ListenableFuture<T> springListenableFuture) { return GuavaFutureUtils.createListenableFuture(SpringFutureUtils.createValueSourceFuture(springListenableFuture)); }
java
@Override public StartReplicationTaskAssessmentResult startReplicationTaskAssessment(StartReplicationTaskAssessmentRequest request) { request = beforeClientExecution(request); return executeStartReplicationTaskAssessment(request); }
java
@Override public Query doQuery(SpatialStrategy strategy) { BooleanQuery.Builder builder = new BooleanQuery.Builder(); builder.add(query(maxGeoDistance, strategy), FILTER); if (minGeoDistance != null) { builder.add(query(minGeoDistance, strategy), MUST_NOT); } retu...
java
@Override public Request<MoveAddressToVpcRequest> getDryRunRequest() { Request<MoveAddressToVpcRequest> request = new MoveAddressToVpcRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }