language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def getVMstats(self): """Return stats for Virtual Memory Subsystem. @return: Dictionary of stats. """ info_dict = {} try: fp = open(vmstatFile, 'r') data = fp.read() fp.close() except: raise IOError('Failed...
python
def _update_bordercolor(self, bordercolor): """Updates background color""" border_color = wx.SystemSettings_GetColour(wx.SYS_COLOUR_ACTIVEBORDER) border_color.SetRGB(bordercolor) self.linecolor_choice.SetColour(border_color)
java
public boolean couldContainAnnotationsOnClassDef(DataInput in, Set<String> byteCodeAnnotationsNames) throws IOException { /* According to Java VM Spec, each .class file contains * a single class or interface definition. The structure * definition is shown below: Cl...
python
def download(self, source, dest): """ Download an archive file. :param str source: URL pointing to an archive file. :param str dest: Local path location to download archive file to. """ # propagate all exceptions # URLError, OSError, etc proto, netloc, pa...
python
def _sqla_postgresql(self, uri, version=None, isolation_level="READ COMMITTED"): ''' expected uri form: postgresql+psycopg2://%s:%s@%s:%s/%s' % ( username, password, host, port, db) ''' isolation_level = isolation_level or "READ COMMITTED" ...
python
def clear_java_home(): """Clear JAVA_HOME environment or reset to BCBIO_JAVA_HOME. Avoids accidental java injection but respects custom BCBIO_JAVA_HOME command. """ if os.environ.get("BCBIO_JAVA_HOME"): test_cmd = os.path.join(os.environ["BCBIO_JAVA_HOME"], "bin", "java") if os.path...
java
public String getName(final Locale locale) { return messageResolver.getMessage(locale, String.format("locale.%s.name", hexId)); }
java
public boolean invokeProxyScript(ScriptWrapper script, HttpMessage msg, boolean request) { validateScriptType(script, TYPE_PROXY); Writer writer = getWriters(script); try { // Dont need to check if enabled as it can only be invoked manually ProxyScript s = this.getInterface(script, ProxyScript.class)...
java
public PondLife get(int timeoutMs) throws Exception { PondLife pl=null; // Defer to other threads before locking if (_available<_min) Thread.yield(); int new_id=-1; // Try to get pondlife without creating new one. synchr...
python
def modularity(matrix, clusters): """ Compute the modularity :param matrix: The adjacency matrix :param clusters: The clusters returned by get_clusters :returns: modularity value """ matrix = convert_to_adjacency_matrix(matrix) m = matrix.sum() if isspmatrix(matrix): matrix...
java
public Iterable<HistoryPageEntry<T>> getRenderList() { if(trimmed) { List<HistoryPageEntry<T>> pageEntries = toPageEntries(baseList); if(pageEntries.size() > THRESHOLD) { return updateFirstTransientBuildKey(pageEntries.subList(0,THRESHOLD)); } else { ...
python
async def close(self): """ Terminate the ICE agent, ending ICE processing and streams. """ if self.__isClosed: return self.__isClosed = True self.__setSignalingState('closed') # stop senders / receivers for transceiver in self.__transceivers: ...
python
def p_namedblock_empty(self, p): 'namedblock : BEGIN COLON ID END' p[0] = Block((), p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
python
def update_xml_element(self): """ Updates the xml element contents to matches the instance contents. :returns: Updated XML element. :rtype: lxml.etree._Element """ super(Description, self).update_xml_element() if hasattr(self, 'lang'): self.xml_elem...
python
def _encode(cls, data, charsets): """Encode the data using the character sets in charsets. :param data: Data to be encoded. :param charsets: Sequence of charsets that are used to encode the barcode. Must be the exact amount of symbols needed to encode the data. ...
java
public Integer getMaxAge() { if (childNode.getTextValueForPatternName("max-age") != null && !childNode.getTextValueForPatternName("max-age").equals("null")) { return Integer.valueOf(childNode.getTextValueForPatternName("max-age")); } return null; }
java
private void appendLinebreaks(Tag tag, boolean open) { String name = tag.getTagName(); int pos = TAG_LIST.indexOf(name); switch (pos) { case 0: // H1 setMarker("=", open); setIndentation(2, open); appendLinebreak(2); b...
java
@Override public EClass getIfcFilter() { if (ifcFilterEClass == null) { ifcFilterEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(271); } return ifcFilterEClass; }
java
private Locale getContentLocale(ListConfigurationBean bean) { CmsObject cms = A_CmsUI.getCmsObject(); if (bean.getFolders().isEmpty()) { return OpenCms.getLocaleManager().getDefaultLocale(cms, "/"); } else { return OpenCms.getLocaleManager().getDefaultLocale( ...
java
public boolean isNodeType(InternalQName qName) throws RepositoryException { checkValid(); return session.getWorkspace().getNodeTypesHolder().isNodeType(qName, nodeData().getPrimaryTypeName(), nodeData().getMixinTypeNames()); }
java
private final void parseDocument(Node currentNode) { try { mutex.acquire(); String nodeName = currentNode.getNodeName(); if ((currentNode.getNodeType() == Node.ELEMENT_NODE) && (nodeName.equals("type")) ) { String typeName = ((Element) currentNode)...
java
private WebReply unprotectedSpecialURI(WebRequest webRequest, String uriName, String methodName) { LoginConfiguration loginConfig = webRequest.getLoginConfig(); if (loginConfig == null) return null; String authenticationMethod = loginConfig.getAuthenticationMethod(); FormLog...
java
public static String getPrimitiveObjCType(TypeMirror type) { return TypeUtil.isVoid(type) ? "void" : type.getKind().isPrimitive() ? "j" + TypeUtil.getName(type) : "id"; }
java
@Override public Collection<Instance> getInstanceList() throws Exception { List<Instance> instances = new ArrayList<>(); List<String> appNames = getApplications(); if (appNames == null || appNames.size() == 0) { log.info("No apps configured, returning an empty instance list"); return instances; } log.i...
java
@XmlElementDecl(namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", name = "ACLPropagation", scope = ApplyACL.class) public JAXBElement<EnumACLPropagation> createApplyACLACLPropagation( EnumACLPropagation value) { return new JAXBElement<EnumACLPropagation>( _ApplyACLACLPropagation_QNAME, E...
python
def focusInEvent(self, event): """ When this widget loses focus, try to emit the record changed event signal. """ self._changedRecord = -1 super(XOrbRecordBox, self).focusInEvent(event)
java
public void register(K key, T connection) { connections.put(key, new Sync<>(key, connection)); }
java
public long[] getChannelIdArray() { long[] ret = new long[channelIds.size()]; for(int i = 0; i < channelIds.size(); i++) ret[i] = channelIds.get(i); return ret; }
java
public boolean isContractive(QualifiedName nid, Type type) { HashSet<QualifiedName> visited = new HashSet<>(); return isContractive(nid, type, visited); }
java
@Override public UnixSshPath subpath( int start, int end ) { String[] parts = new String[end - start]; for ( int i = start; i < end; i++ ) { parts[i] = getName( i ).toString(); } return new UnixSshPath( getFileSystem(), false, parts ); }
java
public static String defaultButtonHtml( CmsHtmlIconButtonStyleEnum style, String id, String name, String helpText, boolean enabled, String iconPath, String confirmationMessage, String onClick) { return defaultButtonHtml( style, ...
python
def p_load_code(p): """ statement : load_or_verify expr ID | load_or_verify expr CODE | load_or_verify expr CODE expr | load_or_verify expr CODE expr COMMA expr """ if p[2].type_ != TYPE.string: api.errmsg.syntax_error_expected_string(p.lineno(3)...
java
@Override public void writeFile(List lblSeqs, String filename) { String ret = writeString(lblSeqs); try{ BufferedWriter out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(filename), "UTF-8")); out.write(ret); out.close(); } catch (Exception e){ } }
java
public void setColor(float r, float g, float b, float a) { color.set(r, g, b, a); colorF = color.toFloatBits(); if (staticLight) dirty = true; }
python
def document(self, name, file_name, **kwargs): """Add Document data to Batch object. Args: name (str): The name for this Group. file_name (str): The name for the attached file for this Group. date_added (str, kwargs): The date timestamp the Indicator was created. ...
python
def _createIndexRti(self, index, nodeName): """ Auxiliary method that creates a PandasIndexRti. """ return PandasIndexRti(index=index, nodeName=nodeName, fileName=self.fileName, iconColor=self._iconColor)
python
def _merge_files(self, input_files, output_file): """Combine the input files to a big output file""" # we assume that all the input files have the same charset with open(output_file, mode='wb') as out: for input_file in input_files: out.write(open(input_file, mode='rb...
python
def merge(intervals): """ Merge two intervals into one. """ out = [] for i in sorted(intervals, key=lambda i: i.start): if out and i.start <= out[-1].end: out[-1].end = max(out[-1].end, i.end) else: out += i, return out
java
void removeToRelockList(final DeviceProxy dev) { // Check if admin device already exists. String adm; try { adm = dev.adm_name(); } catch (final DevFailed e) { // Give up return; } if (relockMap.containsKey(adm)) { final Loc...
java
public void materialise(Session session) { PersistentStore store; // table constructors if (isDataExpression) { store = session.sessionData.getSubqueryRowStore(table); dataExpression.insertValuesIntoSubqueryTable(session, store); return; } ...
java
protected void kill( String pid ) throws IOException, InterruptedException { String os = System.getProperty( "os.name" ); String command = ( os.startsWith( "Windows" ) ) ? "taskkill /F /PID " + pid : "kill " + pid; Runtime.getRuntime().exec( command ).waitFor(); }
java
public static String removeAll(final String text, final Pattern regex) { return replaceAll(text, regex, N.EMPTY_STRING); }
java
Instance createInstance(String name, Cls cls) throws KnowledgeSourceReadException { return getFromProtege(new InstanceSpec(name, cls), INSTANCE_CREATOR); }
java
@Pure public VisualizationType getVisualizationType() { if (this.vizualizationType == null) { final AttributeValue val = getAttributeCollection().getAttribute(ATTR_VISUALIZATION_TYPE); if (val != null) { try { this.vizualizationType = val.getJavaObject(); } catch (Exception e) { // } }...
java
public void add(String key, Collection<String> cves) throws VictimsException { key = hash(key); if (exists(key)) { delete(key); } String result = ""; if (cves != null) { result = StringUtils.join(cves, ","); } try { ...
python
def read_chunks(self, chunk_size, start, step, count) -> bytes: ''' Read the content. Read and concatenate the chunks of size chunk_size using offsets calculated from start, step and stop. Args: chunk_size (int): The chunk size. s...
python
def get_asns(self, privaddr=0): """Obtain associated AS Numbers for IPv4 Addreses. privaddr: 0 - Normal display of AS numbers, 1 - Do not show an associated AS Number bound box (cluster) on graph for a private IPv4 Address.""" ips = {} if privaddr: for...
python
def decrypt(self, ciphertext): """Given ``ciphertext`` returns a ``plaintext`` decrypted using the keys specified in ``__init__``. Raises ``CiphertextTypeError`` if the input ``ciphertext`` is not a string. Raises ``RecoverableDecryptionError`` if the input ``ciphertext`` has a non-negative mes...
python
def run_task(func): """ Decorator to collect and return generator results, returning a list if there are multiple results """ def _wrapped(*a, **k): gen = func(*a, **k) return _consume_task(gen) return _wrapped
python
def persist(self): """Stores the current configuration for pushing to W&B""" # In dryrun mode, without wandb run, we don't # save config on initial load, because the run directory # may not be created yet (because we don't know if we're # being used in a run context, or as an AP...
python
async def artwork_save(self): """Download artwork and save it to artwork.png.""" artwork = await self.atv.metadata.artwork() if artwork is not None: with open('artwork.png', 'wb') as file: file.write(artwork) else: print('No artwork is currently av...
python
def load_profile_from_files(filenames=None, profile=None): """Load a profile from a list of D-Wave Cloud Client configuration files. .. note:: This method is not standardly used to set up D-Wave Cloud Client configuration. It is recommended you use :meth:`.Client.from_config` or :meth:`.config....
java
public static appfwpolicylabel[] get_filtered(nitro_service service, String filter) throws Exception{ appfwpolicylabel obj = new appfwpolicylabel(); options option = new options(); option.set_filter(filter); appfwpolicylabel[] response = (appfwpolicylabel[]) obj.getfiltered(service, option); return response; ...
java
public static void convolveAndTranspose(Kernel kernel, int[] inPixels, int[] outPixels, int width, int height, boolean alpha, boolean premultiply, boolean unpremultiply, int edgeAction) { float[] matrix = kernel.getKernelData(null); int cols = kernel.getWidth(); int cols2 = cols / 2; fo...
python
def add_to_submenu(self, submenu_path, item): ''' add an item to a submenu using a menu path array ''' for m in self.items: if m.name == submenu_path[0]: m.add_to_submenu(submenu_path[1:], item) return raise(ValueError("No submenu (%s) ...
python
def _rule_value(self): """ Parses the production rule:: value : TERM (',' TERM)* Returns list of string terms. """ terms = [self._get_token()] # consume additional terms if available while self._lookahead_token() == ',': self._get_to...
java
public JsonMappingOption asFieldNaming(JsonFieldNaming fieldNaming) { if (fieldNaming == null) { throw new IllegalArgumentException("The argument 'fieldNaming' should not be null."); } this.fieldNaming = OptionalThing.of(fieldNaming); return this; }
python
def get_device_activity(self, type_p): """Gets the current activity type of given devices or device groups. in type_p of type :class:`DeviceType` return activity of type :class:`DeviceActivity` raises :class:`OleErrorInvalidarg` Invalid device type. """ ...
java
<ResultT> AggregateOperation<ResultT> aggregate( final List<? extends Bson> pipeline, final Class<ResultT> resultClass) { return new AggregateOperation<>(namespace, dataSynchronizer, pipeline, resultClass); }
python
def bitonic_sort(arr, reverse=False): """ bitonic sort is sorting algorithm to use multiple process, but this code not containing parallel process It can sort only array that sizes power of 2 It can sort array in both increasing order and decreasing order by giving argument true(increasing) and false(de...
java
public InventoryResultItem withContent(java.util.Map<String, String>... content) { if (this.content == null) { setContent(new com.amazonaws.internal.SdkInternalList<java.util.Map<String, String>>(content.length)); } for (java.util.Map<String, String> ele : content) { this...
java
public void init() { pocessorMap.clear(); //標準のフィールドプロセッサを登録する。 registerProcessor(XlsSheetName.class, new SheetNameProcessor()); registerProcessor(XlsCell.class, new CellProcessor()); registerProcessor(XlsLabelledCell.class, new LabelledCellProcessor()); ...
java
Future<?> flushAllTableQueues() throws InterruptedException { return m_es.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { loadTable(buildTable(), m_table); return true; } }); }
python
def get_curve_name(self, ecdh=False): """Return correct curve name for device operations.""" if ecdh: return formats.get_ecdh_curve_name(self.curve_name) else: return self.curve_name
python
def now(self): """ Function to return just the current timestep from this forecast """ # From the comments in issue 19: forecast.days[0] is dated for the # previous day shortly after midnight now = None # Set the time now to be in the same time zone as the first...
python
def plot_pointings(self, pointings=None): """Plot pointings on canavs""" if pointings is None: pointings = self.pointings i = 0 for pointing in pointings: items = [] i = i + 1 label = {} label['text'] = pointing['label']['text...
java
public Object parse(byte [] bytes, String charset) { if (bytes == null) { throw new IllegalArgumentException("bytes must not be null"); } if (charset == null) { throw new IllegalArgumentException("charset must not be null"); } Object content; con...
python
def build_or_install_bokehjs(): ''' Build a new BokehJS (and install it) or install a previously build BokehJS. If no options ``--build-js`` or ``--install-js`` are detected, the user is prompted for what to do. If ``--existing-js`` is detected, then this setup.py is being run from a packaged ...
java
public AwsSecurityFindingFilters withFirstObservedAt(DateFilter... firstObservedAt) { if (this.firstObservedAt == null) { setFirstObservedAt(new java.util.ArrayList<DateFilter>(firstObservedAt.length)); } for (DateFilter ele : firstObservedAt) { this.firstObservedAt.add(e...
java
public void copyResources( URI uri, ClassLoader classLoader, File target ) throws MojoExecutionException { URL url; String scheme = uri.getScheme(); if ( "classpath".equals( scheme ) ) { // get resource from class-path String path = uri.getPath()...
java
public void addTopicAcl(SIBUuid12 destName, TopicAcl acl) throws SIDiscriminatorSyntaxException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "addTopicAcl", new Object[] { destName, acl }); String discriminator = null; // Postpend # wildcard to the ful...
java
public static SingularValueDecomposition_F64<DMatrixRMaj> svd(boolean needU , boolean needV , boolean compact ) { return svd(100,100,needU,needV,compact); }
python
def balance(self, as_of=None, raw=False, leg_query=None, **kwargs): """Get the balance for this account, including child accounts Args: as_of (Date): Only include transactions on or before this date raw (bool): If true the returned balance should not have its sign ...
python
def units(self) -> typing.Iterator['BaseUnit']: """ Iterates over all units Returns: generator of Unit """ for group in self.groups: for unit in group.units: yield unit
python
def __send_retry_requests(self, last_send_failure_time): """Called via Timer from __send_ready to resend requests which might not have been sent due to transport failure. This can happen since the current transport implementation does not received acknowledgements for sent messages.""" ...
python
def request(self, method, url, **kwargs): """Constructs a :class:`requests.Request`, prepares it and sends it. Raises HTTPErrors by default. :param method: method for the new :class:`Request` object. :type method: :class:`str` :param url: URL for the new :class:`Request` object....
python
def rank(self): """convert a list of integers so that the lowest integer is 0, the next lowest is 1 ... note: modifies list in place""" # XXX FIX ME, should the lowest value be 1 or 0? symclasses = self.symclasses stableSort = map(None, symclasses, range(len(symclasses)))...
python
def _key_name(self): # type: () -> str """Return the key referring to this object The default value is the lower case version of the class name :rtype: str """ if self._key is not None: return self._key return self.__class__.__name__.lower()
python
def b58encode_check(v: bytes) -> str: '''Encode a string using Base58 with a 4 character checksum''' digest = sha256(sha256(v).digest()).digest() return b58encode(v + digest[:4])
java
protected boolean onBusItineraryRemoved(BusItinerary itinerary, int index) { if (this.autoUpdate.get()) { try { removeMapLayerAt(index); return true; } catch (Throwable exception) { // } } return false; }
java
private String getSetterGuidanceDoc() { StringBuilder docBuilder = new StringBuilder(); if (isJsonValue()) { docBuilder.append("<p>") .append(LINE_SEPARATOR) .append("This field's value must be valid JSON according to RFC 7159, including the openi...
python
async def list(self, setname=None): """ Lists the existing ipsets. If setname is given, only lists this ipset. The resulting command looks like one of the following: * ``ipset list`` * ``ipset list ellis_blacklist4`` """ args = ['list'] ...
java
@SuppressWarnings("unchecked") public <T extends IMetric> T registerMetric(String name, T metric, int timeBucketSizeInSecs) { if ((Boolean) _openOrPrepareWasCalled.deref()) { throw new RuntimeException("TopologyContext.registerMetric can only be called from within overridden " ...
java
private static Response createErrorResponse(S3Exception e) { S3Error errorResponse = new S3Error(e.getResource(), e.getErrorCode()); // Need to explicitly encode the string as XML because Jackson will not do it automatically. XmlMapper mapper = new XmlMapper(); try { return Response.status(e.getEr...
python
def _landsat_stats( band, address_prefix, metadata, overview_level=None, max_size=1024, percentiles=(2, 98), dst_crs=CRS({"init": "EPSG:4326"}), histogram_bins=10, histogram_range=None, ): """ Retrieve landsat dataset statistics. Attributes ---------- band : str ...
python
def _ppf(self, qloc, cache, **kwargs): """ Example: >>> dist = chaospy.J(chaospy.Uniform(), chaospy.Normal()) >>> print(numpy.around(dist.inv([[0.1, 0.2, 0.3], [0.3, 0.3, 0.4]]), 4)) [[ 0.1 0.2 0.3 ] [-0.5244 -0.5244 -0.2533]] >>> d0...
python
def abort(self, count=2, timeout=60): ''' Send an abort sequence using CAN bytes. ''' for counter in xrange(0, count): self.putc(CAN, timeout)
java
public Dict setIgnoreNull(String attr, Object value) { if (null != attr && null != value) { set(attr, value); } return this; }
java
public void setBytes(int index, byte[] source, int sourceIndex, int length) { checkPositionIndexes(sourceIndex, sourceIndex + length, source.length); copyMemory(source, (long) SizeOf.ARRAY_BYTE_BASE_OFFSET + sourceIndex, base, address + index, length); }
java
public boolean load() { if ((lastLoaded + cacheTTLMillis) <= System.currentTimeMillis()) { clearCache(); } if (!readCache()) { if (shouldReadDataFromFallback()) { return loadFallback(); } } return true; }
python
def search_script(self, script): """ Search a script's contents for import statements and check if they're currently prevent in the list of all installed pip modules. :param script: string :return: void """ if self.import_statement.search(script): ...
java
private static Class<?> callerBuilder(Object caller, StringBuilder text) { Class<?> c = Debugger.class; if (caller != null) { if (caller instanceof Class) { c = (Class<?>) caller; text.append(c.getName()).append(": "); } else if (caller instanceof String) { text.appen...
python
def get_db_instance_info(self, dbid): ''' Get DB instance info ''' if not self.connect_to_aws_rds(): return False try: instances = self.rdsc.describe_db_instances(dbid).get('DBInstances') except: return False else: myinstance = inst...
python
def wvcal_spectrum(sp, fxpeaks, poly_degree_wfit, wv_master, wv_ini_search=None, wv_end_search=None, wvmin_useful=None, wvmax_useful=None, geometry=None, debugplot=0): """Execute wavelength calibration of a spectrum using fixed line peaks. Parameters ...
java
public void setCacheKeyParameters(java.util.Collection<String> cacheKeyParameters) { if (cacheKeyParameters == null) { this.cacheKeyParameters = null; return; } this.cacheKeyParameters = new java.util.ArrayList<String>(cacheKeyParameters); }
python
def save_batches(server_context, assay_id, batches): # type: (ServerContext, int, List[Batch]) -> Union[List[Batch], None] """ Saves a modified batches. :param server_context: A LabKey server context. See utils.create_server_context. :param assay_id: The assay protocol id. :param batches: The Ba...
python
def DoesIDExist(tag_name): """ Determines if a fully-qualified site.service.tag eDNA tag exists in any of the connected services. :param tag_name: fully-qualified (site.service.tag) eDNA tag :return: true if the point exists, false if the point does not exist Example: >>> DoesID...
python
def delete_alias(i): """ Input: { path - path to the entry data_uid - data UID (data_alias) - data alias (repo_dict) - repo cfg if available to check sync (share) - if 'yes', try to rm via GIT } Output: { ...
python
def _update_function_transition_graph(self, src_node_key, dst_node_key, jumpkind='Ijk_Boring', ins_addr=None, stmt_idx=None, confirmed=None): """ Update transition graphs of functions in function manager based on information passed in. :param str jumpki...
python
def disassociate_api_key_stagekeys(apiKey, stagekeyslist, region=None, key=None, keyid=None, profile=None): ''' disassociate the given stagekeyslist to the given apiKey. CLI Example: .. code-block:: bash salt myminion boto_apigateway.disassociate_stagekeys_api_key \\ api_key '...