language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def heap_item(clock, record, shard): """Create a tuple of (ordering, (record, shard)) for use in a RecordBuffer.""" # Primary ordering is by event creation time. # However, creation time is *approximate* and has whole-second resolution. # This means two events in the same shard within one second can't b...
python
def factor_loadings( r, factors=None, scale=False, pickle_from=None, pickle_to=None ): """Security factor exposures generated through OLS regression. Incorporates a handful of well-known factors models. Parameters ---------- r : Series or DataFrame The left-hand-side variable...
python
def timezone(client, location, timestamp=None, language=None): """Get time zone for a location on the earth, as well as that location's time offset from UTC. :param location: The latitude/longitude value representing the location to look up. :type location: string, dict, list, or tuple :pa...
python
def pauli_from_char(ch, n=0): """Make Pauli matrix from an character. Args: ch (str): "X" or "Y" or "Z" or "I". n (int, optional): Make Pauli matrix as n-th qubits. Returns: If ch is "X" => X, "Y" => Y, "Z" => Z, "I" => I Raises: ValueError: When ch is not "X", "Y", "Z...
python
def argmax(self): """Index of the maximum, ignorning nans.""" if "argmax" not in self.attrs.keys(): def f(dataset, s): arr = dataset[s] try: amin = np.nanargmax(arr) except ValueError: amin = 0 ...
java
public List<String> process() throws IOException, OpenXML4JException, ParserConfigurationException, SAXException { ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(this.xlsxPackage); XSSFReader xssfReader = new XSSFReader(this.xlsxPackage); StylesTable styles = xssfReader.getStylesTable(); XS...
python
def download_as_pem( base_url=d1_common.const.URL_DATAONE_ROOT, timeout_sec=d1_common.const.DEFAULT_HTTP_TIMEOUT, ): """Download public certificate from a TLS/SSL web server as PEM encoded string. Also see download_as_der(). Args: base_url : str A full URL to a DataONE service en...
python
def _expand_variables(self, config, hostname): """ Return a dict of config options with expanded substitutions for a given hostname. Please refer to man ``ssh_config`` for the parameters that are replaced. :param dict config: the config for the hostname :param s...
python
def _get_level_values(self, level, unique=False): """ Return vector of label values for requested level, equal to the length of the index **this is an internal method** Parameters ---------- level : int level unique : bool, default False if T...
python
def get_last_calc_id(username=None): """ :param username: if given, restrict to it :returns: the last calculation in the database or the datastore """ if config.dbserver.multi_user: job = dbcmd('get_job', -1, username) # can be None return getattr(job, 'id', 0) else: # single u...
java
private static void extract(String s, int start, ExtractFloatResult result) { // Now looking for ' ', ',', '.' or '-' from the start. int currentIndex = start; boolean foundSeparator = false; result.mEndWithNegOrDot = false; boolean secondDot = false; boolean isExponentia...
python
def model(self, autoGenerate=False): """ Returns the default Table class that is associated with this \ schema instance. :param autoGenerate | <bool> :return <subclass of Table> """ if self.__model is None and autoGenerate: s...
python
def list_nodes(): """ Return a list of all nodes """ token = session.get('token') node = nago.core.get_node(token) if not node.get('access') == 'master': return jsonify(status='error', error="You need master access to view this page") nodes = nago.core.get_nodes().values() return render...
java
public synchronized void open(FieldTable table) throws DBException { if (m_VKeyList == null) this.initKeyAreas(table); this.saveCurrentKeys(table, null, true); }
java
public static Object removeVariable(PageContext pc, String var) throws PageException { // print.ln("var:"+var); StringList list = parse(pc, new ParserString(var), false); if (list == null) throw new InterpreterException("invalid variable declaration [" + var + "]"); if (list.size() == 1) { return pc.undefined...
java
private synchronized boolean addProvisionedSlave(DockerSlaveTemplate template) throws Exception { final DockerContainerLifecycle dockerCreateContainer = template.getDockerContainerLifecycle(); String dockerImageName = dockerCreateContainer.getImage(); int templateCapacity = template.getMaxCapaci...
java
public void setIPos(Integer newIPos) { Integer oldIPos = iPos; iPos = newIPos; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AfplibPackage.LND__IPOS, oldIPos, iPos)); }
python
def get_qseq_dir(fc_dir): """Retrieve the qseq directory within Solexa flowcell output. """ machine_bc = os.path.join(fc_dir, "Data", "Intensities", "BaseCalls") if os.path.exists(machine_bc): return machine_bc # otherwise assume we are in the qseq directory # XXX What other cases can we...
java
public void getCharacterBackStory(String API, String name, Callback<CharacterBackStory> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ParamType.API, API), new ParamChecker(ParamType.CHAR, name)); gw2API.getCharacterBackStory(name, API).enqueue(callback); }
java
public static ColorPackage init() { if (isInited) return (ColorPackage)EPackage.Registry.INSTANCE.getEPackage(ColorPackage.eNS_URI); // Obtain or create and register package ColorPackageImpl theColorPackage = (ColorPackageImpl)(EPackage.Registry.INSTANCE.get(eNS_URI) instanceof ColorPackageImpl ? EPackage.Regist...
java
public void setPublishEngine(CmsPublishEngine publishEngine) { if (m_frozen) { throw new CmsRuntimeException(Messages.get().container(Messages.ERR_CONFIG_FROZEN_0)); } m_publishEngine = publishEngine; }
java
protected void send(OutputStream out, Charset charset) throws IOException { // 报文分为三个部分 // 报文头 byte[] head = request.getHeadByte(charset); // 交易参数 byte[] param = request.encodeParam(charset); // 交易文件流 InputStream inputFile = request.getInputFile(); long fi...
java
public IScopeHandler getHandler() { log.trace("getHandler from {}", name); if (handler != null) { return handler; } else if (hasParent()) { return getParent().getHandler(); } else { return null; } }
python
def longestorf(args): """ %prog longestorf fastafile Find longest ORF for each sequence in fastafile. """ p = OptionParser(longestorf.__doc__) p.add_option("--ids", action="store_true", help="Generate table with ORF info [default: %default]") opts, args = p.parse_args(args)...
java
@Override public Boolean convert(final String value) { return Boolean.valueOf(value) || "1".equals(value) || "on".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value); }
python
def pop_local_cache(self, port_uuid, mac, net_uuid, lvid, vdp_vlan, segmentation_id): """Populate the local cache after restart. """ LOG.info("Populating the OVS VDP cache with port %(port_uuid)s, " "mac %(mac)s net %(net_uuid)s lvid %(lvid)s vdpvlan " ...
python
def get_selected_keys(self, selection): """Return a list of keys for the given selection.""" return [k for k, b in self._lookup.items() if b & selection]
python
def disasters(value=disasters_array, params_of_mean=params_of_mean): """Annual occurences of coal mining disasters.""" val = params_of_mean[1] + params_of_mean[0] * arange(111) return poisson_like(value, val)
java
public com.google.privacy.dlp.v2.PrivacyMetric.DeltaPresenceEstimationConfigOrBuilder getDeltaPresenceEstimationConfigOrBuilder() { if (typeCase_ == 6) { return (com.google.privacy.dlp.v2.PrivacyMetric.DeltaPresenceEstimationConfig) type_; } return com.google.privacy.dlp.v2.PrivacyMetric.DeltaPr...
java
public String getTopic() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getTopic"); if (topics == null) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getTopic", null)...
java
public Traverson followLink(final String rel, final Predicate<Link> predicate) { return followLink(rel, predicate, emptyMap()); }
java
public static Deferred<HashMap<String, String>> resolveIdsAsync(final TSDB tsdb, final List<byte[]> tags) throws NoSuchUniqueId { final short name_width = tsdb.tag_names.width(); final short value_width = tsdb.tag_values.width(); final short tag_bytes = (short...
python
def requeue(self): """Re-queues any expired job (one which does not get an expire before the job_expiry_interval) back into their respective queue. This function has to be run at specified intervals to ensure the expired jobs are re-queued back. """ timestamp = str(genera...
java
public static <T> Array2dJsonDeserializer<T> newInstance( JsonDeserializer<T> deserializer, Array2dCreator<T> arrayCreator ) { return new Array2dJsonDeserializer<T>( deserializer, arrayCreator ); }
java
protected String makeRequest(boolean includePassword) { StringBuffer buf = new StringBuffer(); buf.append(VERSION).append(CRLF); buf.append(COMMAND).append(String.valueOf(command)).append(CRLF); buf.append(USERNAME).append(this.username).append(CRLF); String pwd = getPassphrase(); ...
python
def context(self): """Get the context.""" stats = status_codes_by_date_stats() attacks_data = [{ 'type': 'line', 'zIndex': 9, 'name': _('Attacks'), 'data': [(v[0], v[1]['attacks']) for v in stats] }] codes_dat...
python
def calculate_bin_centers(edges): """Calculate the centers of wavelengths bins given their edges. Parameters ---------- edges : array-like or `~astropy.units.quantity.Quantity` Sequence of bin edges. Must be 1D and have at least two values. If not a Quantity, assumed to be in Angstrom. ...
java
@Nonnull public static FileSet createFileSet(@Nonnull File baseDir, @Nonnull String includes, @CheckForNull String excludes) { FileSet fs = new FileSet(); fs.setDir(baseDir); fs.setProject(new Project()); StringTokenizer tokens; tokens = new StringTokenizer(includes,","); ...
python
def weight_by_edge_odds_ratios(self, edges_expected_weight, flag_as_significant): """Applied during the permutation test. Update the edges in the network to be weighted by their odds ratios. The odds ratio measures how unexpec...
python
def send(self, url, **kwargs): """ Serializes and signs ``data`` and passes the payload off to ``send_remote`` If ``server`` was passed into the constructor, this will serialize the data and pipe it to the server using ``send_remote()``. """ if self.config.server_url: ...
python
def SNRaverage(snr, method='average', excludeBackground=True, checkBackground=True, backgroundLevel=None): ''' average a signal-to-noise map :param method: ['average','X75', 'RMS', 'median'] - X75: this SNR will be exceeded by 75% of the signal :type method: str ...
java
public RefreshSessionResponse refreshSession(String sessionId) { RefreshSessionRequest request = new RefreshSessionRequest(); request.setSessionId(sessionId); return refreshSession(request); }
java
@Controller public void askWhetherToRepeat(WebSocketSession session, Event event) { if (event.getText().contains("yes")) { reply(session, event, "Great! I will remind you tomorrow before the meeting."); } else { reply(session, event, "Okay, don't forget to attend the meeting ...
java
public void deleteProject(String name) throws Exception { m_cms.deleteProject(m_cms.readProject(name).getUuid()); }
python
def do_request_async(self, url, method='GET', headers=None, payload=None, deadline=None, callback=None): """Issue one HTTP request. It performs async retries using tasklets. Args: url: the url to fetch. method: the method in which to fetch. headers: the http header...
java
final protected Object common_get(Object key) { ValidateUtility.objectNotNull(key, "key"); Object value = cache.getValue(key, cache.shouldPull(this.sharingPolicy, key)); return value; }
java
@SuppressWarnings("unchecked") public Map<Object, Object> getClassPropertiesMapByClass (Class<?> pvClass) { return (Map<Object, Object>) classPropertiesMap.get(pvClass); }
python
def answer(self, text: str = None, show_alert: bool = None, url: str = None, cache_time: int = 0): """Bound method *answer* of :obj:`CallbackQuery <pyrogram.CallbackQuery>`. Use this method as a shortcut for: .. code-block:: python client.answer_callback_query( cal...
java
public void assertValid(String valueAsString) throws IllegalArgumentException { final T value = valueConverter.convert(valueAsString); for (Validator<T> validator : validators) { validator.assertValid(value); } }
java
protected CmsResource fillResource(CmsObject cms, Element element, CmsUUID resourceId) throws CmsException { String xpath = element.getPath(); int pos = xpath.lastIndexOf("/" + XmlNode.Containers.name() + "/"); if (pos > 0) { xpath = xpath.substring(pos + 1); } CmsRe...
java
public static TypeName resolveVariableTypeName(VariableElement variableElement, Messager messager) { // Resolve type if (variableElement.asType().getKind() == TypeKind.ERROR) { messager.printMessage(Kind.ERROR, "Couldn't resolve type " + variableElement.asType() ...
java
public String create(GuacamoleConfiguration config) throws GuacamoleException { // Get the next available connection identifier. String newConnectionId = Integer.toString(getNextConnectionID()); // Generate a name for the configuration. String name = QCParser.getName(config); ...
java
@Override public boolean isAcceptableChange( Changes changes, Tree node, MethodSymbol symbol, VisitorState state) { int numberOfChanges = changes.changedPairs().size(); return changes.totalOriginalCost() - changes.totalAssignmentCost() >= threshold * numberOfChanges; }
java
public T set(T newValue) { final T obj = this.object; this.object = newValue; return obj; }
python
def input(self, data): """ 小数据片段拼接成完整数据包 如果内容足够则yield数据包 """ self.buf += data while len(self.buf) > HEADER_SIZE: data_len = struct.unpack('i', self.buf[0:HEADER_SIZE])[0] if len(self.buf) >= data_len + HEADER_SIZE: content = self.buf[HE...
python
def _server_end_response_callback(self, respoonse: Response): '''Response callback handler.''' request = self._item_session.request response = self._item_session.response _logger.info(__( _('Fetched ‘{url}’: {status_code} {reason}. ' 'Length: {content_length} [...
python
def decode_base64_dict(data): ''' Decode a base64 encoded array into a NumPy array. Args: data (dict) : encoded array data to decode Data should have the format encoded by :func:`encode_base64_dict`. Returns: np.ndarray ''' b64 = base64.b64decode(data['__ndarray__']) arra...
python
def write_with_mac(self, data, block): """Write one data block with additional integrity check. If prior to calling this method the tag was not authenticated, a :exc:`RuntimeError` exception is raised. Command execution errors raise :exc:`~nfc.tag.TagCommandError`. """ ...
java
public synchronized boolean changeNodePriority(int streamID, int newPriority) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "changeNodePriority entry: streamID to change: " + streamID + " new Priority: " + newPriority); } Node nodeToChange = root...
python
def insert_into_graph(self, graph): """Insert this edge into a BEL graph. :param pybel.BELGraph graph: A BEL graph """ u = self.source.as_bel() v = self.target.as_bel() if self.evidence: return graph.add_qualified_edge(u, v, **json.loads(self.data))...
python
def unload_key(self, key): """Remove key from memory, leaving file in place. This forces :py:meth:`~bucketcache.buckets.DeferredWriteBucket.sync`. """ self.sync() return super(DeferredWriteBucket, self).unload_key(key)
java
public static String encodeUrlIso(String stringToEncode) { try { return URLEncoder.encode(stringToEncode, "ISO-8859-1"); } catch (UnsupportedEncodingException e1) { throw new RuntimeException(e1); } }
java
private void checkDefaults() { Utils.require(m_shards != null || m_shardsRange != null, "shards or range parameter is not set"); Utils.require(m_shards == null || m_shardsRange == null, "shards and range parameters cannot be both set"); Utils.require(m_continueAt == null || m_contin...
java
private void getArtistData() { mRetrievedTracks.clear(); mAdapter.notifyDataSetChanged(); mTracksSubscription = mCheerleaderClient.getArtistTracks() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) ...
java
public void waitForRestart() { if (standbyThread != null) { try { // if this is the standby avatarnode, then wait for the Standby to exit standbyThread.join(); } catch (InterruptedException ie) { //eat it up } standbyThread = null; LOG.info("waitForRestart: Stan...
java
public static void killAllProcesses() { Set<String> pids = processMap.keySet(); for (String pid : pids) { killProcess(pid); } LOG.info("Successfully killed all processes"); }
java
public static List<Import> getImportList(final List<String> importCells) { final List<Import> importList = new ArrayList<Import>(); if ( importCells == null ) return importList; for( String importCell: importCells ){ final StringTokenizer tokens = new StringTokenizer( importCell, ",...
python
def on_message(self, _, basic_deliver, properties, body): """Invoked by pika when a message is delivered from RabbitMQ. The channel is passed for your convenience. The basic_deliver object that is passed in carries the exchange, routing key, delivery tag and a redelivered flag for the m...
python
def auto(self): """Returns the highest whole-number unit.""" if self._value >= 1099511627776: return self.TiB, 'TiB' if self._value >= 1073741824: return self.GiB, 'GiB' if self._value >= 1048576: return self.MiB, 'MiB' if self._value >= 1024: ...
java
public static void main(String[] pArgs) throws IOException { ThumbsDBImageReader reader = new ThumbsDBImageReader(); reader.setInput(ImageIO.createImageInputStream(new File(pArgs[0]))); // reader.setLoadEagerly(true); if (pArgs.length > 1) { long start = System.currentTimeMil...
python
def has_friends(self, flt=FriendFilter.ALL): """Indicated whether the user has friends, who meet the given criteria (filter). :param int flt: Filter value from FriendFilter. Filters can be combined with `|`. :rtype: bool """ return self._iface.get_has_friend(self.user_id, flt)
python
def get_certificate(self, publisher_name, extension_name, version=None, **kwargs): """GetCertificate. [Preview API] :param str publisher_name: :param str extension_name: :param str version: :rtype: object """ route_values = {} if publisher_name is ...
java
private Object postRequest(HttpMethod httpMethod, String restUrl, Map<String, String> params) throws IOException, WebServiceException { HttpURLConnection conn = null; BufferedWriter wr = null; try { // Make the URL urlString = new StringBuilder(this.host).append(restUrl); LOGGER.debug("Doing HTT...
java
private static double snorm(double[] x, int itol) { int n = x.length; if (itol <= 3) { double ans = 0.0; for (int i = 0; i < n; i++) { ans += x[i] * x[i]; } return Math.sqrt(ans); } else { int isamax = 0; fo...
java
public TopicProducer<String> createTopicTextMessageProducer(final String topic) { Preconditions.checkState(connectionFactory != null, "connection factory was never injected!"); return new TopicProducer<String>(connectionFactory, jmsConfig, topic, new TextMessageProducerCallback()); }
python
def add_cxnSp(self, id_, name, type_member, x, y, cx, cy, flipH, flipV): """ Append a new ``<p:cxnSp>`` shape to the group/shapetree having the properties specified in call. """ prst = MSO_CONNECTOR_TYPE.to_xml(type_member) cxnSp = CT_Connector.new_cxnSp( id_,...
python
def magicquil(f): """ Decorator to enable a more convenient syntax for writing quil programs. With this decorator there is no need to keep track of a Program object and regular Python if/else branches can be used for classical control flow. Example usage: @magicquil def fast_reset(q1):...
java
public static nspbr_stats get(nitro_service service, String name) throws Exception{ nspbr_stats obj = new nspbr_stats(); obj.set_name(name); nspbr_stats response = (nspbr_stats) obj.stat_resource(service); return response; }
java
private static long adler32(byte[] data) { final Adler32 checksum = new Adler32(); checksum.update(data); return checksum.getValue(); }
python
def _encapsulate_item_for_combinfunc(item): """ This function has been extracted in order to make Github issue #28 easier to investigate. It replaces the following two lines of code, which occur twice in method genmatrix, just before the invocation of combinfunc. if not hasattr(item, '...
python
def _unweave(target, advices, pointcut, ctx, depth, depth_predicate): """Unweave deeply advices in target.""" # if weaving has to be done if pointcut is None or pointcut(target): # do something only if target is intercepted if is_intercepted(target): _remove_advices(target=targe...
python
def insert_arguments_into_gremlin_query(compilation_result, arguments): """Insert the arguments into the compiled Gremlin query to form a complete query. The GraphQL compiler attempts to use single-quoted string literals ('abc') in Gremlin output. Double-quoted strings allow inline interpolation with the $...
python
def _handle_update_msg(self, update_msg): """Extracts and processes new paths or withdrawals in given `update_msg`. Parameter: - `update_msg`: update message to process. - `valid_rts`: current valid/interesting rts to the application according to configurati...
python
def get_schema_type(cls, schema): """ Get schema type for the argument :param schema: Schema to analyze :return: COMPILED_TYPE constant :rtype: str|None """ schema_type = type(schema) # Marker if issubclass(schema_type, markers.Marker): retur...
java
public java.util.List<String> getImportTaskIds() { if (importTaskIds == null) { importTaskIds = new com.amazonaws.internal.SdkInternalList<String>(); } return importTaskIds; }
python
def get_updates(offset=None, limit=None, timeout=None, allowed_updates=None, **kwargs): """ Use this method to receive incoming updates using long polling. .. note:: 1. This method will not work if an outgoing webhook is set up. 2. In order to avoid getting duplicate update...
java
@Override public boolean isEnabled() throws WidgetException { try { return getWebElement().isEnabled(); } catch (Exception e) { throw new WidgetException( "Error while determing whether element is enabled", getByLocator(), e); } }
java
public boolean subtract(String key, ModuleDepInfo subInfo) { boolean modified = false; ModuleDepInfo info = get(key); if (info != null) { modified = info.subtract(subInfo); } return modified; }
java
public void setPipelineActivities(java.util.Collection<PipelineActivity> pipelineActivities) { if (pipelineActivities == null) { this.pipelineActivities = null; return; } this.pipelineActivities = new java.util.ArrayList<PipelineActivity>(pipelineActivities); }
python
def _get(self, *args, **kwargs): """ Make a GET request. """ return self._request(requests.get, *args, **kwargs)
java
Path getPathForCorrespondingNode( String workspaceName, NodeKey key, Path relativePath ) throws NoSuchWorkspaceException, AccessDeniedException, ItemNotFoundException, RepositoryException { assert key != null; try { ...
java
public static <T1, T2, T3, T4, R> Function4<T1, T2, T3, T4, R> memoizeQuadFunction(final Function4<T1, T2, T3, T4, R> fn) { Function1<Tuple4<T1, T2, T3, T4>, R> memoise2 = memoizeFunction((final Tuple4<T1, T2, T3, T4> quad) -> fn.apply(quad._1(), quad._2(), quad._3(), quad._4())); return (t1, t2, t3, t4) ...
python
def _make_units(*units): """ Units map helper. Each argument is treated as a unit descriptor--a tuple where the first element specifies a numerical value, and the second element consists of a sequence of names for that value. Returns a dictionary where each name is mapped to the numerical valu...
python
def searches(self): """*The search-block (if any) associated with this document* **Usage:** .. code-block:: python # DOCUMENT SEARCHES docSearchBlock = doc.searches """ return self._get_object( regex=re.compile( r...
python
def _pressed(self, evt): """ Clicked somewhere in the calendar. """ x, y, widget = evt.x, evt.y, evt.widget item = widget.identify_row(y) column = widget.identify_column(x) if not column or not (item in self._items): # clicked in the weekdays row or j...
python
def CountFlowOutputPluginLogEntries(self, client_id, flow_id, output_plugin_id, with_type=None, cursor=None): """Returns numbe...
java
private void stopResourceAdapter() { if (resourceAdapter != null) try { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(this, tc, "stop", resourceAdapter); ArrayList<ThreadContext> threadContext = startTask(raThreadContext...
java
public String redirectUrl(String token) { return play.shaded.oauth.oauth.signpost.OAuth.addQueryParameters( provider.getAuthorizationWebsiteUrl(), play.shaded.oauth.oauth.signpost.OAuth.OAUTH_TOKEN, token ); }
java
public void trimToSize() { this.modCount++; final int oldCapacity = this.data.length; if (this.size < oldCapacity) { this.data = Arrays.copyOf(this.data, this.size); } }
java
public static void write(FeatureList features, String filename) throws IOException { logger.info("Writing: {}", filename); BufferedWriter bw = new BufferedWriter(new FileWriter(filename)); ListIterator<FeatureI> iter = features.listIterator(); while (iter.hasNext()) { Feature feature = (Feature) iter.next(...