language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def info(self, server_id): """return dicionary object with info about server Args: server_id - server identity """ result = self._storage[server_id].info() result['id'] = server_id return result
python
def execute(self, eopatch): """ Add requested feature to this existing EOPatch. """ data_arr = eopatch[FeatureType.MASK]['IS_DATA'] _, height, width, _ = data_arr.shape request = self._get_wms_request(eopatch.bbox, width, height) request_data, = np.asarray(reque...
python
def copy(self): """Return a shallow copy of the sorted dictionary.""" return self.__class__(self._key, self._load, self._iteritems())
java
public Document cmisDocument( CmisObject cmisObject ) { org.apache.chemistry.opencmis.client.api.Document doc = (org.apache.chemistry.opencmis.client.api.Document)cmisObject; DocumentWriter writer = newDocument(ObjectId.toString(ObjectId.Type.OBJECT, doc.getId())); ObjectType objectType = cmisO...
python
def square(m, eff_max,c,m0,sigma,m1=21): """ eff_max: Maximum of the efficiency function (peak efficiency) c: shape of the drop-off in the efficiency at bright end m0: transition to tappering at faint magnitudes sigma: width of the transition in efficeincy m1: magnitude at which peak efficeincy...
java
public ControllerRoute withBasicAuthentication(String username, String password) { Objects.requireNonNull(username, Required.USERNAME.toString()); Objects.requireNonNull(password, Required.PASSWORD.toString()); this.username = username; this.password = password; ...
python
def delete_cookie(self, key, path='/', domain=None): """Delete a cookie (by setting it to a blank value). The path and domain values must match that of the original cookie. """ self.set_cookie(key, value='', max_age=0, path=path, domain=domain, expires=datetime.u...
java
@Override public Schema convertSchema(Schema inputSchema, WorkUnitState workUnit) { return AVRO_FLATTENER.flatten(inputSchema, false); }
java
private void launchMyRichClient() { if (startupContext == null) { displaySplashScreen(rootApplicationContext); } final Application application; try { application = rootApplicationContext.getBean(Application.class); } catch (NoSuchBeanDefinitionE...
java
@Override public ProtocolDef protocol(String type) { return new ProtocolDefImpl( getDescriptorName(), getRootNode(), container, container.getOrCreate("protocol@type=" + type)); }
python
def remove_indicator(self, nid, prune=False): """ Removes a Indicator or IndicatorItem node from the IOC. By default, if nodes are removed, any children nodes are inherited by the removed node. It has the ability to delete all children Indicator and IndicatorItem nodes undernea...
python
def writeRunSetInfoToLog(self, runSet): """ This method writes the information about a run set into the txt_file. """ runSetInfo = "\n\n" if runSet.name: runSetInfo += runSet.name + "\n" runSetInfo += "Run set {0} of {1} with options '{2}' and propertyfile '{...
java
private EmptyStatementTree parseEmptyStatement() { SourcePosition start = getTreeStartLocation(); eat(TokenType.SEMI_COLON); return new EmptyStatementTree(getTreeLocation(start)); }
java
public static long count_filtered(nitro_service service, String sitepath, String filter) throws Exception{ wisite_translationinternalip_binding obj = new wisite_translationinternalip_binding(); obj.set_sitepath(sitepath); options option = new options(); option.set_count(true); option.set_filter(filter); wis...
java
public String findPrefix(String uri){ if(uri==null) uri = ""; String prefix = getPrefix(uri); if(prefix==null){ String defaultURI = getURI(""); if(defaultURI==null) defaultURI = ""; if(Util.equals(uri, defaultURI)) p...
java
@Deprecated public Redemptions getCouponRedemptionsByInvoice(final Integer invoiceNumber, final QueryParams params) { return getCouponRedemptionsByInvoice(invoiceNumber.toString(), params); }
java
@Override public DataResponse<Team> getTeam(ObjectId componentId, String teamId) { Component component = componentRepository.findOne(componentId); CollectorItem item = component.getCollectorItems() .get(CollectorType.AgileTool).get(0); ...
java
public int getHTTPStatus() throws InterruptedException, BOSHException { if (toThrow != null) { throw(toThrow); } lock.lock(); try { if (!sent) { awaitResponse(); } } finally { lock.unlock(); } return ...
python
def run_output(self): """Output finalized data""" for f in logdissect.output.__formats__: ouroutput = self.output_modules[f] ouroutput.write_output(self.data_set['finalized_data'], args=self.args) del(ouroutput) # Output to terminal if sil...
python
def _integrateOrbit_dxdv(vxvv,dxdv,pot,t,method,rectIn,rectOut): """ NAME: _integrateOrbit_dxdv PURPOSE: integrate an orbit and area of phase space in a Phi(R) potential in the (R,phi)-plane INPUT: vxvv - array with the initial conditions stacked like [R,vR,vT,...
python
def __gen_struct_anno_files(self, top_level_layer): """ A struct annotation file contains node (struct) attributes (of non-token nodes). It is e.g. used to annotate the type of a syntactic category (NP, VP etc.). See also: __gen_hierarchy_file() """ paula_id = '{...
python
def _ExtractYahooSearchQuery(self, url): """Extracts a search query from a Yahoo search URL. Examples: https://search.yahoo.com/search?p=query https://search.yahoo.com/search;?p=query Args: url (str): URL. Returns: str: search query or None if no query was found. """ i...
python
def init_duts(self, args): # pylint: disable=too-many-locals,too-many-branches """ Initializes duts of different types based on configuration provided by AllocationContext. Able to do the initialization of duts in parallel, if --parallel_flash was provided. :param args: Argument Namesp...
java
@SuppressWarnings("unchecked") private byte[] generateColumnFamilyKeyFromPkObj(CFMappingDef<?> cfMapDef, Object pkObj) { List<byte[]> segmentList = new ArrayList<byte[]>(cfMapDef.getKeyDef().getIdPropertyMap().size()); if (cfMapDef.getKeyDef().isComplexKey()) { Map<String, PropertyDescriptor> prop...
python
def _write_cache_to_file(self): """Write the contents of the cache to a file on disk.""" with(open(self._cache_file_name, 'w')) as fp: fp.write(simplejson.dumps(self._cache))
java
public void calcOffset(Container compAnchor, Point offset) { offset.x = 0; offset.y = 0; Container parent = this; while (parent != null) { offset.x -= parent.getLocation().x; offset.y -= parent.getLocation().y; parent = parent.getParent(); ...
java
public ApiResponse<ApiSuccessResponse> switchToListenInWithHttpInfo(String id, MonitoringScopeData monitoringScopeData) throws ApiException { com.squareup.okhttp.Call call = switchToListenInValidateBeforeCall(id, monitoringScopeData, null, null); Type localVarReturnType = new TypeToken<ApiSuccessRespons...
java
@Override public void connectController(String host, int port) { try { if (host == null && port == -1) { try { this.controllerHost = this.defaultControllerHost; this.controllerPort = this.defaultControllerPort; client....
python
def createExternalTable(self, tableName, path=None, source=None, schema=None, **options): """Creates an external table based on the dataset in a data source. It returns the DataFrame associated with the external table. The data source is specified by the ``source`` and a set of ``options``. ...
java
public static Object getId(Object object) { Objects.nonNull(object); try { Field idField = getIdField(object.getClass()); if (idField == null) throw new IllegalArgumentException(object.getClass().getName() + " has no id field to get"); Object id = idField.get(object); return id; } catch (SecurityExcep...
python
def loads_json(p_str, custom=None, meta=False, verbose=0): """ Given a json string it creates a dictionary of sfsi objects :param ffp: str, Full file path to json file :param custom: dict, used to load custom objects, {model type: custom object} :param meta: bool, if true then also return all ecp m...
java
public <T extends BaseWrapper<T>> CollectionWrapper<T> createCollection(final Object collection, final Class<?> entityClass, boolean isRevisionCollection) { return createCollection((Collection) collection, entityClass, isRevisionCollection); }
java
public CodeSigner[] getCodeSigners() { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new VirtualFilePermission(getPathName(), "read")); } final VFS.Mount mount = VFS.getMount(this); return mount.getFileSystem().getCodeSig...
python
def column(self, key): """Iterator over a given column, skipping steps that don't have that key """ for row in self.rows: if key in row: yield row[key]
python
def _get_download_url(self): """Get the download URL for the current blob. If the ``media_link`` has been loaded, it will be used, otherwise the URL will be constructed from the current blob's path (and possibly generation) to avoid a round trip. :rtype: str :returns: T...
java
@Pure public static <S> S getSreSpecificData(SRESpecificDataContainer container, Class<S> type) { assert container != null; return container.$getSreSpecificData(type); }
python
def convert_libraries_in_path(config_path, lib_path, target_path=None): """ This function resaves all libraries found at the spcified path :param lib_path: the path to look for libraries :return: """ for lib in os.listdir(lib_path): if os.path.isdir(os.path.join(lib_path, lib)) and not '...
java
@Override public DescribeFleetPortSettingsResult describeFleetPortSettings(DescribeFleetPortSettingsRequest request) { request = beforeClientExecution(request); return executeDescribeFleetPortSettings(request); }
python
def validate_email(email, check_mx=False, verify=False, debug=False, smtp_timeout=10): """Indicate whether the given string is a valid email address according to the 'addr-spec' portion of RFC 2822 (see section 3.4.1). Parts of the spec that are marked obsolete are *not* included in this test, and cert...
java
private Token scanNumber(int c) throws IOException { int startLine = mSource.getLineNumber(); int startPos = mSource.getStartPosition(); mWord.setLength(0); int errorPos = -1; // 0 is decimal int, // 1 is hex int, // 2 is decimal long, // 3 is...
java
public static CanCache of(MethodDescription.InDefinedShape methodDescription) { if (methodDescription.isTypeInitializer()) { return CanCacheIllegal.INSTANCE; } else if (methodDescription.isConstructor()) { return new ForConstructor(methodDescription); } else { ...
java
private static boolean isLinearRing(LineString lineString) { if (lineString.coordinates().size() < 4) { throw new GeoJsonException("LinearRings need to be made up of 4 or more coordinates."); } if (!(lineString.coordinates().get(0).equals( lineString.coordinates().get(lineString.coordinates().si...
python
def p_expression_comparison(self, p): """ expression : name comparison_number number | name comparison_string string | name comparison_equality boolean_value | name comparison_equality none | name comparison_in_list const_list_v...
python
def get_tokens_list(self, registry_address: PaymentNetworkID): """Returns a list of tokens the node knows about""" tokens_list = views.get_token_identifiers( chain_state=views.state_from_raiden(self.raiden), payment_network_id=registry_address, ) return tokens_lis...
python
def push(self, tx): """ Args: tx: hex of signed transaction Returns: pushed transaction """ self._service.push_tx(tx) return bitcoin.txhash(tx)
java
@Override public DescribeBundleTasksResult describeBundleTasks(DescribeBundleTasksRequest request) { request = beforeClientExecution(request); return executeDescribeBundleTasks(request); }
python
def get_id_type_map(id_list: Iterable[str]) -> Dict[str, List[str]]: """ Given a list of ids return their types :param id_list: list of ids :return: dictionary where the id is the key and the value is a list of types """ type_map = {} filter_out_types = [ 'cliqueLeader', 'Cl...
python
def is_installed(self, package): """Returns True if the given package (given in pip's package syntax or a tuple of ('name', 'ver')) is installed in the virtual environment.""" if isinstance(package, tuple): package = '=='.join(package) if package.endswith('.git'): ...
python
def CreateGRRTempFile(filename=None, lifetime=0, mode="w+b", suffix=""): """Open file with GRR prefix in directory to allow easy deletion. Missing parent dirs will be created. If an existing directory is specified its permissions won't be modified to avoid breaking system functionality. Permissions on the dest...
java
public String getSubject() { if (triple.getSubject() instanceof IRI) { return ((IRI) triple.getSubject()).getIRIString(); } return triple.getSubject().ntriplesString(); }
java
public RequestHeader withUri(URI uri) { return new RequestHeader(method, uri, protocol, acceptedResponseProtocols, principal, headers, lowercaseHeaders); }
python
def _getattr(self, attri, fname=None, numtype='cycNum'): ''' Private method for getting an attribute, called from get.''' if str(fname.__class__)=="<type 'list'>": isList=True else: isList=False data=[] if fname==None: fname=self.files ...
java
private static ExtensionAuthentication getAuthenticationExtension() { if (extensionAuth == null) { extensionAuth = Control.getSingleton().getExtensionLoader().getExtension(ExtensionAuthentication.class); } return extensionAuth; }
python
def delete_commit(self, commit): """ Deletes a commit. Params: * commit: A tuple, string, or Commit object representing the commit. """ req = proto.DeleteCommitRequest(commit=commit_from(commit)) self.stub.DeleteCommit(req, metadata=self.metadata)
python
def get_pubmed_record(pmid): """Get PubMed record from PubMed ID.""" handle = Entrez.esummary(db="pubmed", id=pmid) record = Entrez.read(handle) return record
python
async def make_transition_register(self, request: 'Request'): """ Use all underlying stacks to generate the next transition register. """ register = {} for stack in self._stacks: register = await stack.patch_register(register, request) return register
java
public String generateUniqueId(String prefix, String text) { // Verify that the passed prefix contains only alpha characters since the generated id must be a valid HTML id. if (StringUtils.isEmpty(prefix) || !StringUtils.isAlpha(prefix)) { throw new IllegalArgumentException( ...
java
public Matrix4d translationRotateScale(double tx, double ty, double tz, double qx, double qy, double qz, double qw, double sx, double sy, double sz) { double dqx = qx + qx, dqy = qy + qy, dqz = qz + qz; double q00 = ...
python
def filter_inconsequential_mods(stmts_in, whitelist=None, **kwargs): """Filter out Modifications that modify inconsequential sites Inconsequential here means that the site is not mentioned / tested in any other statement. In some cases specific sites should be preserved, for instance, to be used as rea...
python
def get_matching_service_template_file(service_name, template_files): """ Return the template file that goes with the given service name, or return None if there's no match. Subservices return the parent service's file. """ # If this is a subservice, use the parent service's template service_na...
java
public void promote(String resourceGroupName, String clusterName, String scriptExecutionId) { promoteWithServiceResponseAsync(resourceGroupName, clusterName, scriptExecutionId).toBlocking().single().body(); }
java
static public UpdateSpecifier computeUpdateSpecifier( Document sourceDoc ,JSONObject targetDoc ) throws Exception { DigestComputerSha1 digestComputer = new DigestComputerSha1(); DocumentDigest dd = digestComputer.computeDocumentDigest(sourceDoc); return computeUpdateSpecifier( sourceDoc ,dd...
java
public String createModcaString4FromString(EDataType eDataType, String initialValue) { return (String)super.createFromString(eDataType, initialValue); }
python
def sign_extend(self, new_length): """ Unary operation: SignExtend :param new_length: New length after sign-extension :return: A new StridedInterval """ msb = self.extract(self.bits - 1, self.bits - 1).eval(2) if msb == [ 0 ]: # All positive numbers ...
java
public static <U, I> void saveDataModel(final DataModelIF<U, I> dm, final String outfile, final boolean overwrite, final String delimiter) throws FileNotFoundException, UnsupportedEncodingException { if (new File(outfile).exists() && !overwrite) { System.out.println("Ignoring " + outfile...
java
@Override protected String convert(final LoggingEvent event) { // // code should be unreachable. // final StringBuffer sbuf = new StringBuffer(); format(sbuf, event); return sbuf.toString(); }
java
public static void showView(View parentView, int id) { if (parentView != null) { View view = parentView.findViewById(id); if (view != null) { view.setVisibility(View.VISIBLE); } else { Log.e("Caffeine", "View does not exist. Could not show it."); ...
java
private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError { PoolingByteArrayOutputStream bytes = new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength()); byte[] buffer = null; try { InputStream in = entity.getContent(); if (in == null) { throw new ServerError(); ...
python
def _parameterize_string(raw): """Substitute placeholders in a string using CloudFormation references Args: raw (`str`): String to be processed. Byte strings are not supported; decode them before passing them to this function. Returns: `str` | :class:`troposphere.GenericHelperFn`: ...
python
def _palette(self): """ p """ # Loop through available palettes self.palette_idx += 1 try: self.loop.screen.register_palette(self.palettes[self.palette_names[self.palette_idx]]) except IndexError: self.loop.screen.register_palette(self.palettes[self.palett...
python
def _ParseEntry(self, key, val): """Adds an entry for a configuration setting. Args: key: The name of the setting. val: The value of the setting. """ if key in self._repeated: setting = self.section.setdefault(key, []) setting.extend(val) else: self.section.setdefault(...
python
def esearch(database, query, userhistory=True, webenv=False, query_key=False, retstart=False, retmax=False, api_key=False, email=False, **kwargs) -> Optional[EsearchResult]: """Search for a query using the Entrez ESearch API. Parameters ---------- database : str Entez database to se...
java
@Override public TableName[] listTableNamesByNamespace(String name) throws IOException { if (provideWarningsForNamespaces()) { LOG.warn("listTableNamesByNamespace is a no-op"); return new TableName[0]; } else { throw new UnsupportedOperationException("listTableNamesByNamespace"); // TODO ...
python
def read_version(version_file): "Read the `(version-string, version-info)` from `version_file`." vars = {} with open(version_file) as f: exec(f.read(), {}, vars) return (vars['__version__'], vars['__version_info__'])
python
def is_json_compat(value): """ Check that the value is either a JSON decodable string or a dict that can be encoded into a JSON. Raises ValueError when validation fails. """ try: value = json.loads(value) except ValueError as e: raise ValueError('JSON decoding error: ' + st...
java
@Produces @LoggedIn public String extractUsername() { final KeycloakPrincipal principal = (KeycloakPrincipal) httpServletRequest.getUserPrincipal(); if (principal != null) { logger.debug("Running with Keycloak context"); KeycloakSecurityContext kcSecurityContext = princi...
java
public List<Pair> parameterToPair(String name, Object value) { List<Pair> params = new ArrayList<Pair>(); // preconditions if (name == null || name.isEmpty() || value == null || value instanceof Collection) return params; params.add(new Pair(name, parameterToString(value))); re...
java
public NodeSet<OWLClass> getFillers(OWLClassExpression ce, List<OWLObjectPropertyExpression> propertyList) { Set<Node<OWLClass>> result = new HashSet<Node<OWLClass>>(); entailmentCheckCount = 0; computeExistentialFillers(ce, propertyList, getDataFactory().getOWLThing(), result, new HashSet<OWLCl...
java
public GenericField[] getFields() { Collection<GenericField> values = fieldMap.values(); if(values == null || values.isEmpty()) return null; GenericField[] fieldMirrors = new GenericField[values.size()]; values.toArray(fieldMirrors); return fieldMirrors; }
python
def make(class_name, base, schema): """ Create a new schema aware type. """ return type(class_name, (base,), dict(SCHEMA=schema))
java
public static appqoecustomresp[] get_filtered(nitro_service service, String filter) throws Exception{ appqoecustomresp obj = new appqoecustomresp(); options option = new options(); option.set_filter(filter); appqoecustomresp[] response = (appqoecustomresp[]) obj.getfiltered(service, option); return response; ...
python
def get(self, *, no_ack=False): """ Synchronously get a message from the queue. This method is a :ref:`coroutine <coroutine>`. :keyword bool no_ack: if true, the broker does not require acknowledgement of receipt of the message. :return: an :class:`~asynqp.message.IncomingMess...
java
public static VersionValues find(byte[] name, int offset, int length) { return myMatcher.match(name, offset, length, true); }
java
public Future<DeleteItemResult> deleteItemAsync(final DeleteItemRequest deleteItemRequest) throws AmazonServiceException, AmazonClientException { return executorService.submit(new Callable<DeleteItemResult>() { public DeleteItemResult call() throws Exception { return del...
python
def get_next_asset_content(self): """Gets the next AssetContent in this list. return: (osid.repository.AssetContent) - the next AssetContent in this list. The has_next() method should be used to test that a next AssetContent is available before calling th...
java
public static clusterinstance_clusternode_binding[] get_filtered(nitro_service service, Long clid, String filter) throws Exception{ clusterinstance_clusternode_binding obj = new clusterinstance_clusternode_binding(); obj.set_clid(clid); options option = new options(); option.set_filter(filter); clusterinstanc...
python
def load_friends(self): """Fetches the MAL user friends page and sets the current user's friends attributes. :rtype: :class:`.User` :return: Current user object. """ user_friends = self.session.session.get(u'http://myanimelist.net/profile/' + utilities.urlencode(self.username) + u'/friends').text ...
java
private int computeNearestCoarseIndex(double[] vector) { int centroidIndex = -1; double minDistance = Double.MAX_VALUE; for (int i = 0; i < numCoarseCentroids; i++) { double distance = 0; for (int j = 0; j < vectorLength; j++) { distance += (coarseQuantizer[i][j] - vector[j]) * (coarseQuantizer[i]...
java
public static String resolveProperty( Properties props, String value ) { return PropertyResolver.resolve( props, value ); }
python
def folderitems(self): """TODO: Refactor to non-classic mode """ items = super(ServicesView, self).folderitems() self.categories.sort() return items
java
public static Xml exports(SizeConfig config) { Check.notNull(config); final Xml node = new Xml(NODE_SIZE); node.writeInteger(ATT_WIDTH, config.getWidth()); node.writeInteger(ATT_HEIGHT, config.getHeight()); return node; }
java
@Override public <N extends Number> Expression<N> min(Expression<N> arg0) { // TODO Auto-generated method stub return null; }
python
def boot(name=None, kwargs=None, call=None): ''' Boot a Linode. name The name of the Linode to boot. Can be used instead of ``linode_id``. linode_id The ID of the Linode to boot. If provided, will be used as an alternative to ``name`` and reduces the number of API calls to ...
java
@CanIgnoreReturnValue public Ordered containsExactly(@NullableDecl Object k0, @NullableDecl Object v0, Object... rest) { return delegate().containsExactly(k0, v0, rest); }
java
@Override public DescribeDominantLanguageDetectionJobResult describeDominantLanguageDetectionJob(DescribeDominantLanguageDetectionJobRequest request) { request = beforeClientExecution(request); return executeDescribeDominantLanguageDetectionJob(request); }
java
public final List<T> findByQuery(String query, Object... params) { return this.findSortedByQuery(query, null, params); }
java
public void mouseExited(MouseEvent evt) { JLabel button = (JLabel)evt.getSource(); button.setBorder(oldBorder); }
java
public void setCellMerge(final Table table, final String pos, final int rowMerge, final int columnMerge) throws FastOdsException, IOException { final Position position = this.positionUtil.getPosition(pos); final int row = position.getRow(); final int col = position.getColumn(); this.setCellMerge(table, ...
python
def _load(self, data): """ Internal method that deserializes a ``pybrightcove.playlist.Playlist`` object. """ self.raw_data = data self.id = data['id'] self.reference_id = data['referenceId'] self.name = data['name'] self.short_description = data['...
python
def dst(self, dt): """datetime -> DST offset in minutes east of UTC.""" tt = _localtime(_mktime((dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, -1))) if tt.tm_isdst > 0: return _dstdiff return _zero