language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def run_qpoints(self, q_points, with_eigenvectors=False, with_group_velocities=False, with_dynamical_matrices=False, nac_q_direction=None): """Phonon calculations on q-points. Parameters --------...
java
protected ActionResponse handleLoginUnauthorizedException(ActionRuntime runtime, LoginUnauthorizedException appEx) { assertLoginManagerPresent(); if (appEx instanceof LoginFailureException) { saveErrors(getErrorsLoginFailureKey()); // needs to show message for user } final Ht...
python
def Clear(self): """Clears all data from the emulator instance. Returns: True if the data was successfully cleared, False otherwise. """ headers = {'Content-length': '0'} response, _ = self._http.request('%s/reset' % self._host, method='POST', headers=head...
python
def addFixedEffect(self, F=None, A=None, Ftest=None): """ add fixed effect term to the model Args: F: sample design matrix for the fixed effect [N,K] A: trait design matrix for the fixed effect (e.g. sp.ones((1,P)) common effect; sp.eye(P) any effect) [L,P] ...
java
public EditText getEditText(int index) { if(config.commandLogging){ Log.d(config.commandLoggingTag, "getEditText("+index+")"); } return getter.getView(EditText.class, index); }
python
def render_template(template_name, info, out_path=None): """Render a template using the variables in info. You can optionally render to a file by passing out_path. Args: template_name (str): The name of the template to load. This must be a file in config/templates inside this package ...
python
def underlying_symbol(self): """ [str] 合约标的代码,目前除股指期货(IH, IF, IC)之外的期货合约,这一字段全部为’null’(期货专用) """ try: return self.__dict__["underlying_symbol"] except (KeyError, ValueError): raise AttributeError( "Instrument(order_book_id={}) has no attrib...
java
private void showErrorIconHax(Drawable icon) { if (icon == null) return; // only for JB 4.2 and 4.2.1 if (android.os.Build.VERSION.SDK_INT != Build.VERSION_CODES.JELLY_BEAN && android.os.Build.VERSION.SDK_INT != Build.VERSION_CODES.JELLY_BEAN_MR1) return;...
python
def start_server(): """Starts up the imolecule server, complete with argparse handling.""" parser = argparse.ArgumentParser(description="Opens a browser-based " "client that interfaces with the " "chemical format converter.") parser.a...
python
def p_jointype(self,t): """jointype : kw_join | kw_inner kw_join | outerjoin kw_outer kw_join | outerjoin kw_join """ if len(t) <= 2 or t[1] == 'inner': t[0] = JoinTypeX(None, False, None) else: t[0] = JoinTypeX(t[1], True, None)
python
def get_vault_hierarchy_session(self): """Gets the session traversing vault hierarchies. return: (osid.authorization.VaultHierarchySession) - a ``VaultHierarchySession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_vault_hierarc...
java
private void moveNextResults(boolean clearPreviousResults) { if (clearPreviousResults) { allResults.clear(); } allResults.addAll(nextResults); nextResults.clear(); }
python
def read_gold_standard_blocks_file(data_dir, fileroot, split_blocks=True): """ Read the gold standard blocks file corresponding to identifier ``fileroot`` in the gold standard blocks directory below the root ``data_dir``. Args: data_dir (str) fileroot (str) split_blocks (bool): ...
python
def patch(save=True, tensorboardX=tensorboardX_loaded): """Monkeypatches tensorboard or tensorboardX so that all events are logged to tfevents files and wandb. We save the tfevents files and graphs to wandb by default. Arguments: save, default: True - Passing False will skip sending events. ...
python
def delete_namespaced_service(self, name, namespace, **kwargs): # noqa: E501 """delete_namespaced_service # noqa: E501 delete a Service # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> t...
python
def attach(self, host=None, source=None, sourcetype=None): """Opens a stream (a writable socket) for writing events to the index. :param host: The host value for events written to the stream. :type host: ``string`` :param source: The source value for events written to the stream. ...
python
def save_driver_logs(driver, prefix): """ Save the selenium driver logs. The location of the driver log files can be configured by the environment variable `SELENIUM_DRIVER_LOG_DIR`. If not set, this defaults to the current working directory. Args: driver (selenium.webdriver): The Sel...
java
private Map<String, Set<String>> getParameters(HttpServletRequest request) { Map<String, String[]> params = request.getParameterMap(); Map<String, Set<String>> queryParameters = new HashMap<>(params.size()); for (Map.Entry<String, String[]> entry : params.entrySet()) { queryParamete...
java
@OneToMany(targetEntity = org.openprovenance.prov.sql.Role.class, cascade = { CascadeType.ALL }) @JoinColumn(name = "ROLE__WASSTARTEDBY_PK") public List<org.openprovenance.prov.model.Role> getRole() { if (role == null) { role=AttributeList.populateKnownAttributes(this,all, org.op...
java
private String[] getTimePatterns(ProjectProperties properties) { String[] result; char timesep = properties.getTimeSeparator(); ProjectTimeFormat format = properties.getTimeFormat(); if (format == null || format == ProjectTimeFormat.TWELVE_HOUR) { result = new String[] ...
python
def apply_ants_transform_to_image(transform, image, reference, interpolation='linear'): """ Apply transform to an image ANTsR function: `applyAntsrTransformToImage` Arguments --------- image : ANTsImage image to which the transform will be applied reference : ANTsImage ref...
python
def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._created is not None: return False if self._updated is not None: return False if self._status is not None: return F...
python
def present(name, auth=None, **kwargs): ''' Ensure a network exists and is up-to-date name Name of the network provider A dict of network provider options. shared Set the network as shared. external Whether this network is externally accessible. admin_sta...
java
@Override public CreateKeyResult createKey(CreateKeyRequest request) { request = beforeClientExecution(request); return executeCreateKey(request); }
java
public Metadata getMetadata(String typeName, String scope) { URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, typeName); BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, "GET"); BoxJSONResponse response = (BoxJSONResponse) request.send(); ...
python
def get_surface_state(self, data=None): """Return the Euclidean distance between codebook and data. :param data: Optional parameter to specify data, otherwise the data used previously to train the SOM is used. :type data: 2D numpy.array of float32. :returns: The th...
java
public MailContent text(String s) { html.a(escapeXml(s)); text.a(s); return this; }
java
void writeRightCurlyBracket(Writer out, int indent) throws IOException { writeEol(out); writeWithIndent(out, indent, "}\n"); }
java
private Route matchRestful(String uri, ControllerPath controllerPathObject, HttpMethod method, AppController controller) { String theUri = uri.endsWith("/") ? uri.substring(0, uri.length() - 1) : uri; String controllerPath = (controllerPathObject.getControllerPackage() != null ? "/" + controllerPathObj...
java
protected void setExecutor(ServiceReference<ExecutorService> ref) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) Tr.debug(tc, "setExecutor", ref); execSvcRef.setReference(ref); }
python
def _set_customized(self, v, load=False): """ Setter method for customized, mapped from YANG variable /rbridge_id/hardware_profile/kap/customized (container) If this variable is read-only (config: false) in the source YANG file, then _set_customized is considered as a private method. Backends lookin...
java
public VirtualNetworkRuleInner update(String resourceGroupName, String accountName, String virtualNetworkRuleName) { return updateWithServiceResponseAsync(resourceGroupName, accountName, virtualNetworkRuleName).toBlocking().single().body(); }
python
def act(self, action): """ Take one action for one step """ # FIXME: Hack to change in return type action = int(action) assert isinstance(action, int) assert action < self.actions_num, "%r (%s) invalid"%(action, type(action)) # Reset buttons for k...
java
public static boolean copyFile(final File src, final File dest) throws FileNotFoundException, IOException { return copyFile(src, dest, -1, true); }
java
public Map<String, List<String>> getChatMetadata(String sessionID) throws XMPPException, NotConnectedException, InterruptedException { ChatMetadata request = new ChatMetadata(); request.setType(IQ.Type.get); request.setTo(workgroupJID); request.setSessionID(sessionID); ChatMetad...
java
public List<SimulatorEvent> init(long when) { LOG.debug("TaskTracker starting up, current simulation time=" + when); return Collections.<SimulatorEvent>singletonList(new HeartbeatEvent(this, when)); }
python
def evaluate(self, model): """Use the defined parameters to predict single gene essentiality.""" with model: if self.medium is not None: self.medium.apply(model) if self.objective is not None: model.objective = self.objective model.add_...
java
public void writeEncodeFor(String value, String encodeType) throws IOException, PageException { // FUTURE keyword:encodefore add to interface write(ESAPIUtil.esapiEncode(this, encodeType, value)); }
java
public Observable<LinkedWorkspaceInner> getAsync(String resourceGroupName, String automationAccountName) { return getWithServiceResponseAsync(resourceGroupName, automationAccountName).map(new Func1<ServiceResponse<LinkedWorkspaceInner>, LinkedWorkspaceInner>() { @Override public LinkedWo...
java
public String optString(Enum<?> key, String defaultValue) { return optString(key.name(), defaultValue); }
python
def edge_tuple(self, vertex0_id, vertex1_id): """To avoid duplicate edges where the vertex ids are reversed, we maintain that the vertex ids are ordered so that the corresponding pathway names are alphabetical. Parameters ----------- vertex0_id : int one vertex...
java
private boolean isDeprecated( JavaMethod method ) { if ( method == null ) return false; for ( Annotation annotation : method.getAnnotations() ) { if ( "java.lang.Deprecated".equals( annotation.getType().getFullyQualifiedName() ) ) { return...
python
def default_empty(shape, dtype): """Numpy's empty array can have random values in it. To prevent that, we define here a default emtpy array. This default empty is a numpy.zeros array, except that objects are set to None, and all ints to ID_NOT_SET. """ default = numpy.zeros(shape, dtype=dtype) s...
python
def eval_string_type(self, text, is_string=False): """Evaluate string type.""" stype = set() wstype = set() for m in RE_ITER_STRING_TYPES.finditer(text): value = m.group(0) if value == '*': wstype.add('u') wstype.add('f') ...
python
def _handle_substatements(self, stmt: Statement, sctx: SchemaContext) -> None: """Dispatch actions for substatements of `stmt`.""" for s in stmt.substatements: if s.prefix: key = ( sctx.schema_data.modules[sctx.text_mid].prefix_map[s.prefix][0] ...
java
public ListSessionsResponse listSessions(ListSessionsRequest request) { checkNotNull(request, "The parameter request should NOT be null."); InternalRequest internalRequest = createRequest(HttpMethodName.GET, request, LIVE_SESSION); if (request.getStatus() != null) { checkStringNotEm...
java
public static List<ListNumber> dft(ListNumber x, ListNumber y) { if (x.size() != y.size()) { throw new IllegalArgumentException("Real and imaginary part must be of the same length"); } double cosarg,sinarg; double[] resX = new double[x.size()]; double[...
java
public String getFirstPriorityTag(List<String> restrictions) { for (String str : restrictions) { if (hasTag(str)) return getTag(str); } return ""; }
java
public Observable<ServiceResponseWithHeaders<Void, JobScheduleEnableHeaders>> enableWithServiceResponseAsync(String jobScheduleId) { if (this.client.batchUrl() == null) { throw new IllegalArgumentException("Parameter this.client.batchUrl() is required and cannot be null."); } if (job...
java
private void updateComponents() { updatingComponents = true; Font font = getFont(); fontList.setSelectedValue(font.getName(), true); sizeList.setSelectedValue(font.getSize(), true); boldCheckBox.setSelected(font.isBold()); italicCheckBox.setSelected(font.isItalic()); ...
python
def period_comma(): """Period and comma case. Match if not preceded by ".<letter>" and only if followed by space. Won't cut in the middle/after dotted abbreviations; won't cut numbers. Note: Won't match if a dotted abbreviation ends a sentence. Note: Won't match the end of a sente...
java
static void checkCompact(final int serVer, final int flags) { final int compactFlagMask = COMPACT_FLAG_MASK | ORDERED_FLAG_MASK; if ((serVer != 2) && ((flags & EMPTY_FLAG_MASK) == 0) && ((flags & compactFlagMask) != compactFlagMask)) { throw new SketchesArgumentException( ...
java
private void refresh() { if (!refreshCheckStart()) { return; } final TileStates tileStates = mTilesOverlay.getTileStates(); do { mTilesOverlay.drawTiles(null, mProjection, mProjection.getZoomLevel(), mViewPort); boolean ready = true; if (mI...
java
public boolean shouldInvalidate (Object id, int sourceOfInvalidation, int causeOfInvalidation) { boolean retVal = true; if (preInvalidationListenerCount > 0) { // In external implementation, catch any exceptions and process try { retVal = currentPreInvalidationListener.shouldInv...
python
def strip_tags(s): """Resolve HTML entities and remove tags from a string.""" def handle_match(m): name = m.group(1) if name in html_entities: return unichr(html_entities[name]) if name[:2] in ("#x", "#X"): try: return unichr(int(name[2:], 16)) ...
python
def is_readable(path): """ Returns if given path is readable. :param path: Path to check access. :type path: unicode :return: Is path writable. :rtype: bool """ if os.access(path, os.R_OK): LOGGER.debug("> '{0}' path is readable.".format(path)) return True else: ...
python
def requires_authentication(func): """ Function decorator that throws an exception if the user is not authenticated, and executes the function normally if the user is authenticated. """ def _auth(self, *args, **kwargs): if not self._authenticated: ...
python
def fields(self): '''Return a tuple of ordered fields for this :class:`ColumnTS`.''' key = self.id + ':fields' encoding = self.client.encoding return tuple(sorted((f.decode(encoding) for f in self.client.smembers(key))))
java
public Observable<ServiceResponseWithHeaders<ImmutabilityPolicyInner, BlobContainersGetImmutabilityPolicyHeaders>> getImmutabilityPolicyWithServiceResponseAsync(String resourceGroupName, String accountName, String containerName) { if (resourceGroupName == null) { throw new IllegalArgumentException("...
python
def features(self, expand=False): """ Return the list of tuples of feature paths and feature values. Args: expand (bool): if `True`, expand all feature paths Example: >>> avm = AVM([('A.B', TypeIdentifier('1')), ... ('A.C', TypeIdentifier('...
java
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public static boolean hasAppWidgetFeature(PackageManager manager) { return manager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS); }
python
def is_me(self): # pragma: no cover, seems not to be used anywhere """Check if parameter name if same than name of this object TODO: is it useful? :return: true if parameter name if same than this name :rtype: bool """ logger.info("And arbiter is launched with the host...
java
public void marshall(ApplicationCodeConfiguration applicationCodeConfiguration, ProtocolMarshaller protocolMarshaller) { if (applicationCodeConfiguration == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.mars...
python
def filter_direct(stmts_in, **kwargs): """Filter to statements that are direct interactions Parameters ---------- stmts_in : list[indra.statements.Statement] A list of statements to filter. save : Optional[str] The name of a pickle file to save the results (stmts_out) into. Ret...
java
public static void encode(float value, byte[] dst, int dstOffset) { int bits = Float.floatToIntBits(value); bits ^= (bits < 0) ? 0xffffffff : 0x80000000; dst[dstOffset ] = (byte)(bits >> 24); dst[dstOffset + 1] = (byte)(bits >> 16); dst[dstOffset + 2] = (byte)(bits >> 8);...
java
public static base_response add(nitro_service client, scpolicy resource) throws Exception { scpolicy addresource = new scpolicy(); addresource.name = resource.name; addresource.url = resource.url; addresource.rule = resource.rule; addresource.delay = resource.delay; addresource.maxconn = resource.maxconn; ...
java
protected void configureColor(ColorConfigurable configurable, String objectName) { Assert.notNull(configurable, "configurable"); Assert.notNull(objectName, "objectName"); Color color = loadColor(objectName + ".foreground"); if (color != null) configurable.setForeground(color); color = loadColor(objectNam...
python
def _reassign_vd_dirrecord_extents(vd, current_extent): # type: (headervd.PrimaryOrSupplementaryVD, int) -> Tuple[int, List[inode.Inode]] ''' An internal helper method for reassign_extents that assigns extents to directory records for the passed in Volume Descriptor. The current extent is passed in...
python
async def update( self, *, node_id: str, version: int, spec: Mapping[str, Any] ) -> Mapping[str, Any]: """ Update the spec of a node. Args: node_id: The ID or name of the node version: version number of the node being updated spec: fields to be up...
python
def _get_rule_changes(rules, _rules): ''' given a list of desired rules (rules) and existing rules (_rules) return a list of rules to delete (to_delete) and to create (to_create) ''' to_delete = [] to_create = [] # for each rule in state file # 1. validate rule # 2. determine if rule...
python
def update(self, message): """ Updates the states in the primary AlarmDecoder object based on the LRR message provided. :param message: LRR message object :type message: :py:class:`~alarmdecoder.messages.LRRMessage` """ # Firmware version < 2.2a.8.6 if me...
java
public String readAll() throws IOException { StringBuilder sb = new StringBuilder(); String line; while ((line = readLine()) != null) { sb.append(line); } return sb.toString(); }
python
def build_trips(pfeed, routes, service_by_window): """ Given a ProtoFeed and its corresponding routes (DataFrame), service-by-window (dictionary), return a DataFrame representing ``trips.txt``. Trip IDs encode route, direction, and service window information to make it easy to compute stop times...
python
def get(self, name): """Get the vrrp configurations for a single node interface Args: name (string): The name of the interface for which vrrp configurations will be retrieved. Returns: A dictionary containing the vrrp configurations on the interface. ...
java
static GJLocaleSymbols forLocale(Locale locale) { if (locale == null) { locale = Locale.getDefault(); } GJLocaleSymbols symbols = cCache.get(locale); if (symbols == null) { symbols = new GJLocaleSymbols(locale); GJLocaleSymbols oldSymbols = cCache.putI...
java
public void publishSubmissions(List<ISubmission> submissions) throws Exception{ ParadataPublisher publisher = new ParadataPublisher(node); for (ISubmission submission: submissions){ publisher.publish(submission); } }
python
def find_contours(array, level, fully_connected='low', positive_orientation='low'): """Find iso-valued contours in a 2D array for a given level value. Uses the "marching squares" method to compute a the iso-valued contours of the input 2D array for a particular level value. Array values a...
python
def quote(s, unsafe='/'): """Pass in a dictionary that has unsafe characters as the keys, and the percent encoded value as the value.""" res = s.replace('%', '%25') for c in unsafe: res = res.replace(c, '%' + (hex(ord(c)).upper())[2:]) return res
python
def parse_xmlsec_output(output): """ Parse the output from xmlsec to try to find out if the command was successfull or not. :param output: The output from Popen :return: A boolean; True if the command was a success otherwise False """ for line in output.splitlines(): if line == 'OK': ...
java
public List<?> getList(PMContext ctx) throws PMException { final EntityFilter filter = (ctx != null && this.equals(ctx.getEntity())) ? ctx.getEntityContainer().getFilter() : null; return getList(ctx, filter, null, null, null); }
python
def experiments_predictions_create(self, model_id, name, api_url, arguments={}, properties=None): """Create a new model run at the given SCO-API. Parameters ---------- model_id : string Unique model identifier name : string User-defined name for experimen...
python
def database(self): """ Returns the database associated with this tree widget. :return <orb.Database> || None """ if self._database: return self._database if self._recordSet is not None: return self._recordSet.database() ...
java
public List<CmsJspResourceWrapper> readFilesInFolder(String resourcePath) throws CmsException { return CmsJspElFunctions.convertResourceList(m_cms, m_cms.getFilesInFolder(resourcePath)); }
java
public static base_response add(nitro_service client, linkset resource) throws Exception { linkset addresource = new linkset(); addresource.id = resource.id; return addresource.add_resource(client); }
python
def process_msg(self, marker): """ Reads and processes ERROR/INFO streams Stream formats: - ERROR: http://msdn.microsoft.com/en-us/library/dd304156.aspx - INFO: http://msdn.microsoft.com/en-us/library/dd303398.aspx :param marker: TDS_ERROR_TOKEN or TDS_INFO_TOKEN """ ...
python
def load(self, patterns, dirs, ignore=None): """ Load objects from the filesystem into the ``paths`` dictionary. """ for path in self.find_files(patterns=patterns, dirs=dirs, ignore=ignore): data = self.read_file(path=path) if data: self.paths[pat...
java
public void changeRoomName(String roomName) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { MUCLightSetConfigsIQ mucLightSetConfigIQ = new MUCLightSetConfigsIQ(room, roomName, null); connection.createStanzaCollectorAndSend(mucLightSetConfigIQ).ne...
java
public static IXMLDeclarationProcessor unwrap(final IXMLDeclarationProcessor processor) { if (processor == null) { return null; } if (processor instanceof AbstractProcessorWrapper) { return (IXMLDeclarationProcessor)((AbstractProcessorWrapper) processor).unwrap(); ...
python
async def shutdown(self, connmark = -1): ''' Can call without delegate ''' if connmark is None: connmark = self.connmark self.scheduler.emergesend(ConnectionControlEvent(self, ConnectionControlEvent.SHUTDOWN, True, connmark))
python
def save_load(jid, load, minions=None): ''' Save the load to the specified jid ''' serv = _get_serv(ret=None) serv.set(jid, salt.utils.json.dumps(load)) _append_list(serv, 'jids', jid)
java
public ISeq<Genotype<G>> getGenotypes() { return _population.stream() .map(Phenotype::getGenotype) .collect(ISeq.toISeq()); }
python
def query(self, sql, *args, **kwargs): """Executes an SQL SELECT query and returns rows generator. :param sql: query to execute :param args: parameters iterable :param kwargs: parameters iterable :return: rows generator :rtype: generator """ with self.loc...
python
def _DefaultValueConstructorForField(field): """Returns a function which returns a default value for a field. Args: field: FieldDescriptor object for this field. The returned function has one argument: message: Message instance containing this field, or a weakref proxy of same. That function in...
python
def cleanup(self): """ Clean up before quitting """ self.pre_exit_trigger = True self.logger.info("Shutting down %s, please wait a moment.", self.name) for t in threading.enumerate(): if isinstance(t, TimerClass): t.cancel() self....
java
public static ClassLoader getAndSetLoader(ClassLoader newCL) { ThreadContextAccessor tca = ThreadContextAccessor.getThreadContextAccessor(); //This could be a ClassLoader or the special type UNCHANGED. Object maybeOldCL = tca.pushContextClassLoaderForUnprivileged(newCL); if (maybeOldCL i...
java
public ApiResponse<List<SystemJumpsResponse>> getUniverseSystemJumpsWithHttpInfo(String datasource, String ifNoneMatch) throws ApiException { com.squareup.okhttp.Call call = getUniverseSystemJumpsValidateBeforeCall(datasource, ifNoneMatch, null); Type localVarReturnType = new TypeToken<List<...
java
@Override public EEnum getIfcSystemFurnitureElementTypeEnum() { if (ifcSystemFurnitureElementTypeEnumEEnum == null) { ifcSystemFurnitureElementTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(1081); } return ifcSystemFurnitureElementTypeEnum...
python
def __create_template_vars_index(self): """This method will create the dictionnary to be passed in the template in order to generate index.html""" template_vars = {} template_vars["index"] = True template_vars["name"] = self.name template_vars["title"] = self.title ...
python
def get_config(): """Get INI parser with version.ini data.""" # TODO(hanuszczak): See comment in `setup.py` for `grr-response-proto`. ini_path = os.path.join(THIS_DIRECTORY, "version.ini") if not os.path.exists(ini_path): ini_path = os.path.join(THIS_DIRECTORY, "../../version.ini") if not os.path.exists...
java
static String getDefaultNameFromClass(Class<?> cls) { String fromCache = defaultNameCache.get(cls); if (fromCache != null) { return fromCache; } // generate the default // default HystrixCommandKey to use if the method is not overridden String name = cls.getSi...