language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def ActivateCard(self, card): """Activate a card.""" if not hasattr(card, 'connection'): card.connection = card.createConnection() if None != self.parent.apdutracerpanel: card.connection.addObserver(self.parent.apdutracerpanel) card.connection.connect(...
python
def indices(self, index=None, params=None): """ The indices command provides a cross-section of each index. `<https://www.elastic.co/guide/en/elasticsearch/reference/current/cat-indices.html>`_ :arg index: A comma-separated list of index names to limit the returned informati...
java
public void close() { if (dbEnv != null) { // closing dbs iidToIdDB.close(); idToIidDB.close(); if (useGeolocation) { iidToGeolocationDB.close(); } if (useMetaData) { iidToMetadataDB.close(); } closeInternal(); dbEnv.close(); // closing env } else { System.out.pri...
python
def get_default_metrics(config): """ Get the default metrics for a configuration. :param config: The configuration :type config: :class:`wily.config.WilyConfig` :return: Return the list of default metrics in this index :rtype: ``list`` of ``str`` """ archivers = list_archivers(config)...
java
public GraphHopperStorage build() { Directory dir = mmap ? new MMapDirectory(location) : new RAMDirectory(location, store); GraphExtension graphExtension = encodingManager.needsTurnCostsSupport() ? new TurnCostExtension() : new TurnCostExt...
java
@Nonnull public static <T> UnaryOperator<T> unaryOperatorFrom(Consumer<UnaryOperatorBuilder<T>> buildingFunction) { UnaryOperatorBuilder builder = new UnaryOperatorBuilder(); buildingFunction.accept(builder); return builder.build(); }
python
def build_prefixes(namespaces=None): """Internal function takes a list of prefix, namespace uri tuples and generates a SPARQL PREFIX string. Args: namespaces(list): List of tuples, defaults to BIBFRAME and Schema.org Returns: string """ if namespaces i...
java
@Override public ListAvailableZonesResult listAvailableZones(ListAvailableZonesRequest request) { request = beforeClientExecution(request); return executeListAvailableZones(request); }
python
def cache_node_list(nodes, provider, opts): ''' If configured to do so, update the cloud cachedir with the current list of nodes. Also fires configured events pertaining to the node list. .. versionadded:: 2014.7.0 ''' if 'update_cachedir' not in opts or not opts['update_cachedir']: ret...
python
def create_file_for(self, script): """ Create a temporary, executable bash file. It also does render given script (string) with the model and the provided environment variables and optional also an item when using the B{with} field. Args: script (str): eithe...
java
public static <T> void writeObject(final T entity, final Object destination, final String comment) { try { JAXBContext jaxbContext; if (entity instanceof JAXBElement) { jaxbContext = JAXBContext.newInstance(((JAXBElement) entity).getValue().getClass()); } else...
python
def save(self, file): """ Save the image to *file*. If *file* looks like an open file descriptor then it is used, otherwise it is treated as a filename and a fresh file is opened. In general, you can only call this method once; after it has been called the first...
python
def which(program): ''' Emulate unix 'which' command. If program is a path to an executable file (i.e. it contains any directory components, like './myscript'), return program. Otherwise, if an executable file matching program is found in one of the directories in the PATH environment variable, re...
python
def set_base_path(self, value): """Munge in the base path into the configuration values :param str value: The path value """ if config.PATHS not in self.config.application: self.config.application[config.PATHS] = dict() if config.BASE not in self.config.application...
python
def headerSortAscending( self ): """ Sorts the column at the current header index by ascending order. """ self.setSortingEnabled(True) self.sortByColumn(self._headerIndex, QtCore.Qt.AscendingOrder)
python
def diff(s1, s2): ''' --word-diff=porcelain clone''' delta = difflib.Differ().compare(s1.split(), s2.split()) difflist = [] fullline = '' for line in delta: if line[0] == '?': continue elif line[0] == ' ': fullline += line.strip() + ' ' else: ...
python
def right_replace(string, old, new, count=1): """ Right replaces ``count`` occurrences of ``old`` with ``new`` in ``string``. For example:: right_replace('one_two_two', 'two', 'three') -> 'one_two_three' """ if not string: return string return new.join(string.rsplit(old, count))
python
def doc(self): """ Return the root Doc element (if there is one) """ guess = self while guess is not None and guess.tag != 'Doc': guess = guess.parent # If no parent, this will be None return guess
java
private static boolean checkParameters(Method method, Object... data) { Parameter[] parameters = method.getParameters(); if (ArrayUtils.isEmpty(data) && parameters.length != 0) return false; if (parameters.length != data.length) return false; for (int i = 0; i < parameters.length; i++) { Class<?> p...
python
def get_instruction(self, idx, off=None): """ Get a particular instruction by using (default) the index of the address if specified :param idx: index of the instruction (the position in the list of the instruction) :type idx: int :param off: address of the instruction :t...
python
async def inline_query(self, bot, query, *, offset=None, geo_point=None): """ Makes the given inline query to the specified bot i.e. ``@vote My New Poll`` would be as follows: >>> client = ... >>> client.inline_query('vote', 'My New Poll') Args: bot (`entity...
java
public static void setStyle(XWPFRun run, Map<String, Object> styles) { if (Checker.isNotEmpty(styles)) { styles.forEach((key, value) -> { String methodName = "set" + key.substring(0, 1).toUpperCase() + key.substring(1); try { ReflectUtils.invokeMet...
python
def get(self, sid): """ Constructs a SyncStreamContext :param sid: Stream SID or unique name. :returns: twilio.rest.sync.v1.service.sync_stream.SyncStreamContext :rtype: twilio.rest.sync.v1.service.sync_stream.SyncStreamContext """ return SyncStreamContext(self....
python
def _variable_elimination(self, variables, operation, evidence=None, elimination_order=None, joint=True): """ Implementation of a generalized variable elimination. Parameters ---------- variables: list, array-like variables that are not to be eliminated. oper...
java
private void parseMetaZones(JsonObject root) { JsonObject node = resolve(root, "supplemental", "metaZones", "metazoneInfo", "timezone"); for (MetaZone zone : _parseMetaZones(node, Collections.emptyList())) { metazones.put(zone.zone, zone); } }
python
def get_fields(self): """Return an iterator for accessing the fields of this type.""" def visitor(field, children): assert field != conf.lib.clang_getNullCursor() # Create reference to TU so it isn't GC'd before Cursor. field._tu = self._tu fields.append...
python
def forceutc(t: Union[str, datetime.datetime, datetime.date, np.datetime64]) -> Union[datetime.datetime, datetime.date]: """ Add UTC to datetime-naive and convert to UTC for datetime aware input: python datetime (naive, utc, non-utc) or Numpy datetime64 #FIXME add Pandas and AstroPy time classes outpu...
java
public static boolean isModelSupportOutput(CamelCatalog camelCatalog, String modelName) { // use the camel catalog String json = camelCatalog.modelJSonSchema(modelName); if (json == null) { throw new IllegalArgumentException("Could not find catalog entry for model name: " + modelName...
java
public int getPathId(String pathName, int profileId) { PreparedStatement queryStatement = null; ResultSet results = null; // first get the pathId for the pathName/profileId int pathId = -1; try (Connection sqlConnection = sqlService.getConnection()) { queryStatement =...
python
def run_analysis(self, catalogue, config, completeness_table=None, smoothing_kernel=None): ''' Runs an analysis of smoothed seismicity in the manner originally implemented by Frankel (1995) :param catalogue: Instance of the openquake.hmtk.seismicity.cata...
python
def get_targets(conn=None): """ get_brain_targets function from Brain.Targets table. :return: <generator> yields dict objects """ targets = RBT results = targets.run(conn) for item in results: yield item
java
public PublicKey get(String name) throws IOException { if (name.equalsIgnoreCase(KEY)) { return(key); } else { throw new IOException("Attribute name not recognized by " + "CertAttrSet: CertificateX509Key."); } }
python
def competition_leaderboard_view(self, competition): """ view a leaderboard based on a competition name Parameters ========== competition: the competition name to view leadboard for """ result = self.process_response( self.competition_view_leaderb...
python
def is_appendable(self, entry): """Return True if entry can be appended to self""" try: if ( self.name == entry.name and self.dtype == entry.dtype and self.dim == entry.dim ): return True except A...
python
def lazy_map(data_processor, data_generator, n_cpus=1, stepsize=None): """A variant of multiprocessing.Pool.map that supports lazy evaluation As with the regular multiprocessing.Pool.map, the processes are spawned off asynchronously while the results are returned in order. In contrast to multiprocessin...
java
public void printTopStack() throws IOException { System.out.printf("%n Stack trace of top %d threads:%n", view.threadLimit); ThreadInfo[] infos = view.topThreadInfo.getTopThreadInfo(); for (ThreadInfo info : infos) { if (info == null) { continue; } printSingleThread(info); } System.out.flush(); ...
java
public static Batch batchWithCount( Batch batch ) { if (batch == null || batch.isEmpty() || batch.rowCount() >= 0 || batch.width() < 1) return batch; // Otherwise, the batch doesn't know it's row count, so we have to copy it ... return batch.width() == 1 ? new SingleWidthBatch(batch) : new Multi...
python
def get_request_from_view_args(self, view, args, kwargs): """Get request object from a handler function or method. Used internally by ``use_args`` and ``use_kwargs``. """ if len(args) > 1 and isinstance(args[1], sanic.request.Request): req = args[1] else: ...
python
async def send_venue(self, chat_id: typing.Union[base.Integer, base.String], latitude: base.Float, longitude: base.Float, title: base.String, address: base.String, foursquare_id: typing.Union[base.String, None] = None, f...
java
File syncLog(long stamp, final long startTxId, final URL url, String name, File tmpFile) throws IOException { final File[] localPaths = new File[] { tmpFile }; // TODO add security if needed. LOG.info("Synchronizing log " + name + " from " + url); boolean success = false; try { Transfer...
python
def des(clas,keyblob,valblob): "deserialize. translate publish message, basically" raise NotImplementedError("don't use tuples, it breaks __eq__. this function probably isn't used in real life") raw_keyvals=msgpack.loads(keyblob) (namespace,version),keyvals=raw_keyvals[:2],raw_keyvals[2:] if na...
java
public VocabCache<T> buildJointVocabulary(boolean resetCounters, boolean buildHuffmanTree) { long lastTime = System.currentTimeMillis(); long lastSequences = 0; long lastElements = 0; long startTime = lastTime; AtomicLong parsedCount = new AtomicLong(0); if (resetCounters...
java
public boolean processMVBasedQueryFix(StmtTableScan mvTableScan, Set<SchemaColumn> scanColumns, JoinNode joinTree, List<ParsedColInfo> displayColumns, List<ParsedColInfo> groupByColumns) { // Check valid cases first //@TODO if ( ! (mvTableScan instanceof StmtTargetTableScan)) { ...
java
public I_CmsIndexWriter getIndexWriter(I_CmsReport report, boolean create) throws CmsIndexException { // note - create will be: // true if the index is to be fully rebuild, // false if the index is to be incrementally updated if (m_indexWriter != null) { if (!create) { ...
java
public static CompletableFuture<Void> loop(Supplier<Boolean> condition, Supplier<CompletableFuture<Void>> loopBody, Executor executor) { CompletableFuture<Void> result = new CompletableFuture<>(); Loop<Void> loop = new Loop<>(condition, loopBody, null, result, executor); executor.execute(loop); ...
java
public List<V> values() { final Collection<Entry<V>> values = map.values(); // Note below that e.value avoids updating the access time final List<V> res = values.stream().map(e -> e.value).collect(Collectors.toList()); return Collections.unmodifiableList(res); }
java
public Project project(String name, Project parentProject, DateTime beginDate, Schedule schedule) { return project(name, parentProject, beginDate, schedule, null); }
python
def extract_lambda_package(self, package_name, path): """ Extracts the lambda package into a given path. Assumes the package exists in lambda packages. """ lambda_package = lambda_packages[package_name][self.runtime] # Trash the local version to help with package space saving ...
python
def step(self, action): """Repeat action, sum reward, and max over last observations.""" total_reward = 0.0 done = None for i in range(self._skip): obs, reward, done, info = self.env.step(action) if i == self._skip - 2: self._obs_buffer[0] = obs if i == self._skip - 1: ...
python
def movav(y, Dx, dx): """ Moving average rectangular window filter: calculate average of signal y by using sliding rectangular window of size Dx using binsize dx Parameters ---------- y : numpy.ndarray Signal Dx : float Window length of filter. dx : float ...
java
public static void logServer(int logLevel, String message, Throwable throwable) { String logMessage = message; if (null == logMessage) { logMessage = ""; } if (null != throwable) { logMessage += "\n" + getMessage(throwable); } LogRequest logRequest = new LogRequest(); logRequest.setLevel(logLevel); ...
python
def do_start_service(self, service): """ Start a service Usage: > start_service <service> """ if not self.has_cluster(): return None if self.service_action(service=service, action="start"): print("%s is being started" % (service)) ...
java
public static Object returnStaticField(Class clazz, String fieldName) throws MjdbcException { Object result = null; Field field = null; try { field = clazz.getField(fieldName); result = field.get(null); } catch (NoSuchFieldException ex) { thro...
python
def run(self): """ Runs the CWD's scent file. """ if not self.scent or len(self.scent.runners) == 0: print("Did not find 'scent.py', running nose:") return super(ScentSniffer, self).run() else: print("Using scent:") arguments = [sys...
python
def logpdf(self, p): """ Logarithm of the probability density function evaluated at ``p``. """ x2 = self.p2x(p) ** 2 return -0.5 * numpy.sum(x2) - self.log_gnorm
python
def tenant_quota_usages(request, tenant_id=None, targets=None): """Get our quotas and construct our usage object. :param tenant_id: Target tenant ID. If no tenant_id is provided, a the request.user.project_id is assumed to be used. :param targets: A tuple of quota names to be retrieved. If ...
python
def ZernikeSequence(x,y,maxRadial=5,epsilon=1e-10): """ Return Zernike values at a given set of x,y coords up to some maximum radial order """ if maxRadial>5: raise ValueError('Code for higher radial orders not implemented') # Derive radius and exp(i*theta) temp = x + 1j*y r1 =...
python
def register_connection(name, hosts=None, consistency=None, lazy_connect=False, retry_connect=False, cluster_options=None, default=False, session=None): """ Add a connection to the connection registry. ``hosts`` and ``session`` are mutually exclusive, and ``co...
java
public String binaryToString(Object objData) { initGlobals(); if (objData == null) return Constants.BLANK; String string = null; synchronized (gNumberFormat) { if (m_ibScale != 2) { gNumberFormat.setMinimumFractionDigits(m_...
python
def expand_composites (properties): """ Expand all composite properties in the set so that all components are explicitly expressed. """ if __debug__: from .property import Property assert is_iterable_typed(properties, Property) explicit_features = set(p.feature for p in propertie...
python
def beforeRender(self, ctx): """ Before rendering, retrieve the hostname from the request being responded to and generate an URL which will serve as the root for all JavaScript modules to be loaded. """ request = IRequest(ctx) root = self.webSite.rootURL(request) ...
java
private static String toLowerUnderscoreFromCamel(final String value) { if (value.isEmpty()) { return value; } final String s = toLowerFirstChar(value); // include some extra space for separators final StringBuilder out = new StringBuilder(s.length() + 4);...
python
def before_insert(mapper, conn, target): """event.listen method for Sqlalchemy to set the seqience_id for this object and create an ObjectNumber value for the id_""" # from identity import ObjectNumber # assert not target.fk_vid or not ObjectNumber.parse(target.fk_vid).revision ...
python
def time_slice(self, t_from, t_to=None): """Return an new graph containing nodes and interactions present in [t_from, t_to]. Parameters ---------- t_from : snapshot id, mandatory t_to : snapshot id, optional (default=None) If None t_to will be se...
java
static int getRecommendedMinimumErrorCorrectionLevel(int n) throws WriterException { if (n <= 0) { throw new IllegalArgumentException("n must be > 0"); } if (n <= 40) { return 2; } if (n <= 160) { return 3; } if (n <= 320) { return 4; } if (n <= 863) { r...
java
public void startAgent (AgentObject agent) { agent.setLocal(AgentData.class, new AgentData()); Bureau bureau = _bureaus.get(agent.bureauId); if (bureau != null && bureau.ready()) { _omgr.registerObject(agent); log.info("Bureau ready, sending createAgent", "agent", a...
python
def choose(formatter, value, name, option, format): """Adds simple logic to format strings. Spec: `{:c[hoose](choice1|choice2|...):word1|word2|...[|default]}` Example:: >>> smart.format(u'{num:choose(1|2|3):one|two|three|other}, num=1) u'one' >>> smart.format(u'{num:choose(1|2|3):one...
python
def multiget(self, pairs, **params): """Fetches many keys in parallel via threads. :param pairs: list of bucket_type/bucket/key tuple triples :type pairs: list :param params: additional request flags, e.g. r, pr :type params: dict :rtype: list of :class:`RiakObjects <ria...
python
def rollback(self, path, pretend=False): """ Rollback the last migration operation. :param path: The path :type path: str :param pretend: Whether we execute the migrations as dry-run :type pretend: bool :rtype: int """ self._notes = [] ...
python
def merge_strings_files(old_strings_file, new_strings_file): """ Merges the old strings file with the new one. Args: old_strings_file (str): The path to the old strings file (previously produced, and possibly altered) new_strings_file (str): The path to the new strings file (newly produced). ...
java
private static void validateCategories(String... categories) { for (String category : categories) { if (!category.matches(FCM_TOPIC_PATTERN)) { throw new IllegalArgumentException(String.format("%s does not match %s", category, FCM_TOPIC_PATTERN)); } } }
java
public static INDArray[] dup(INDArray[] history) { INDArray[] dupHistory = new INDArray[history.length]; for (int i = 0; i < history.length; i++) { dupHistory[i] = history[i].dup(); } return dupHistory; }
python
def yview(self, *args): """Update inplace widgets position when doing vertical scroll""" self.after_idle(self.__updateWnds) ttk.Treeview.yview(self, *args)
python
def set_layer(self, name: str, matrix: np.ndarray, chunks: Tuple[int, int] = (64, 64), chunk_cache: int = 512, dtype: str = "float32", compression_opts: int = 2) -> None: """ **DEPRECATED** - Use `ds.layer.Name = matrix` or `ds.layer[`Name`] = matrix` instead """ deprecated("'set_layer' is deprecated. Use 'ds.l...
java
public static String escapeHtml(String s) { // (The code of this method is a bit redundant in order to optimize speed) if (s == null) { return null; } int sLength = s.length(); boolean found = false; int p; loop1: for (p = 0; p < sLength; p++) ...
java
public boolean isSelfLabel() { Set<Node> nodes = getNodes(); return nodes.size() == 1 && nodes.iterator().next().getSelfLabel() == this; }
java
public void configure(@Observes(precedence = -200) ArquillianDescriptor arquillianDescriptor) { restAssuredConfigurationInstanceProducer.set( RestAssuredConfiguration.fromMap(arquillianDescriptor .extension("restassured") .getExtensionProperties())); }
python
def _login(login_func, *args): """A helper function for logging in. It's purpose is to avoid duplicate code in the login functions. """ response = login_func(*args) _fail_if_contains_errors(response) user_json = response.json() return User(user_json)
python
def get(self, name_or_klass): """ Get a extension by name (or class). :param name_or_klass: The name or the class of the extension to get :type name_or_klass: str or type :rtype: spyder.api.mode.EditorExtension """ if not isinstance(name_or_klass, str): ...
java
public static SQLTransform lookup(TypeMirror typeMirror) { TypeName typeName; typeName = typeName(typeMirror); return lookup(typeName); }
java
@SuppressWarnings("unchecked") public <S> S getAttachment(String name) { return (S) attachments.get(name); }
java
public @Nonnull Iterable<Integer> ints() { final JsonArray parent=this; return () -> { final Iterator<JsonElement> iterator = parent.iterator(); return new Iterator<Integer>() { @Override public boolean hasNext() { return itera...
python
def _load_from_file(self, filename): """Load from a vocab file.""" if not tf.gfile.Exists(filename): raise ValueError("File %s not found" % filename) with tf.gfile.Open(filename) as f: self._load_from_file_object(f)
python
def from_stat(cls, obj, filename=None): """ Create an `.SFTPAttributes` object from an existing ``stat`` object (an object returned by `os.stat`). :param object obj: an object returned by `os.stat` (or equivalent). :param str filename: the filename associated with this file. ...
python
def transformer_mlperf_tpu(): """HParams for Transformer model on TPU for MLPerf on TPU 2x2.""" hparams = transformer_base_v3() hparams.mlperf_mode = True hparams.symbol_modality_num_shards = 1 hparams.max_length = 256 # ignored when using "_packed" problems hparams.batch_size = 2048 # per-chip batch size...
python
def generate_sources_zip(milestone_id=None, output=None): """ Generate a sources archive for given milestone id. """ if not is_input_valid(milestone_id, output): logging.error("invalid input") return 1 create_work_dir(output) download_sources_artifacts(milestone_id, output) ...
python
def validate_func_factory(validator_class: Any) -> ValidateFunc: """Provide default function for Schema validation. :param validator_class: JSONSchema suitable validator class. """ def validate_func(schema: AnyMapping, pure_data: AnyMapping) -> AnyMapping: """Validate schema with given data. ...
java
public static String toHex(byte[] data, int length) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i != length; i++) { int v = data[i] & 0xff; buffer.append(DIGITS.charAt(v >> 4)); buffer.append(DIGITS.charAt(v & 0xf)); } return buffer....
python
def check(cls, dap, network=False, yamls=True, raises=False, logger=logger): '''Checks if the dap is valid, reports problems Parameters: network -- whether to run checks that requires network connection output -- where to write() problems, might be None raises -- whe...
python
def AddDateTimeRange( self, time_value, start_time_string=None, end_time_string=None): """Adds a date time filter range. The time strings are formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be either 3 or 6 digits. ...
python
def set(self, name: str, value: str) -> None: """ 重写请求中的 header, 不推荐使用 """ name = name.casefold() self._headers[name] = value
python
def reindex_request(analysis, idxs=None): """Reindex the Analysis Request the analysis belongs to, as well as the ancestors recursively """ if not IRequestAnalysis.providedBy(analysis) or \ IDuplicateAnalysis.providedBy(analysis): # Analysis not directly bound to an Analysis Request....
java
private static Node getDeclarationRValue(Node n) { checkNotNull(n); checkArgument(NodeUtil.isNameDeclaration(n)); n = n.getFirstFirstChild(); if (n == null) { return null; } while (n.isAssign()) { n = n.getLastChild(); } return n; }
python
def render(self, is_unicode=False, **kwargs): """Render the graph, and return the svg string""" self.setup(**kwargs) svg = self.svg.render( is_unicode=is_unicode, pretty_print=self.pretty_print ) self.teardown() return svg
python
def qn_to_qubo(expr): """Convert Sympy's expr to QUBO. Args: expr: Sympy's quadratic expression with variable `q0`, `q1`, ... Returns: [[float]]: Returns QUBO matrix. """ try: import sympy except ImportError: raise ImportError("This function requires sympy. P...
python
def compute_numtab(self): """ Recomputes the sets for the static ranges of the trigger time. This method should only be called by the user if the string_tab member is modified. """ self.numerical_tab = [] for field_str, span in zip(self.string_tab, FIELD_RANGES)...
python
def calc_timestep_statistic(self, statistic, time): """ Calculate statistics from the primary attribute of the StObject. Args: statistic: statistic being calculated time: Timestep being investigated Returns: Value of the statistic """ ...
python
def run_state_estimation(data, clusters, dist='Poiss', reps=1, **kwargs): """ Runs state estimation for multiple initializations, returning the result with the highest log-likelihood. All the arguments are passed to the underlying state estimation functions (poisson_estimate_state, nb_estimate_state, zip_estima...
python
def thaw_parameter(self, name): """ Thaw a parameter by name Args: name: The name of the parameter """ i = self.get_parameter_names(include_frozen=True).index(name) self.unfrozen_mask[i] = True
java
public static Matcher anything() { return new Matcher() { @Override public boolean matches(Node node, NodeMetadata metadata) { return true; } }; }