language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def create_menu(self): """ Create the MenuBar for the GUI current structure is: File : Change Working Directory, Import Interpretations from LSQ file, Import interpretations from a redo file, Save interpretations to a redo file, Save MagIC tables, Save Plots Edit : New In...
java
public static List<Alignment.AlignmentDifference> getDifferencesFromCigar(SAMRecord record, String refStr, int maxStoredSequence) { List<Alignment.AlignmentDifference> differences = new LinkedList<>(); int index = 0, indexRef = 0, indexMismatchBlock = 0, realStart; AlignmentBlock blk; // ...
python
def rounding(price, currency): """ rounding currency value based on its max decimal digits """ currency = validate_currency(currency) price = validate_price(price) if decimals(currency) == 0: return round(int(price), decimals(currency)) return round(price, decimals(currency))
python
def GenApiConfig(service_class_names, config_string_generator=None, hostname=None, application_path=None, **additional_kwargs): """Write an API configuration for endpoints annotated ProtoRPC services. Args: service_class_names: A list of fully qualified ProtoRPC service classes. config_str...
java
@Override public Fixture getFixture(String fixtureName, String... params) throws Throwable { Fixture fixture; if (params.length != 0) { // When params are used, we use the PlainOldSystemUnderDevelopment to instantiate the fixture // these params are passed to the constructor fix...
java
private static boolean polygonDisjointPolyline_(Polygon polygon_a, Polyline polyline_b, double tolerance, ProgressTracker progress_tracker) { // Quick rasterize test to see whether the the geometries are disjoint, // or if one is contained in the other. int relation = tryRasterizedContainsOrDisjoint_(polygo...
java
public static String resolve(User u, String avatarSize) { String avatar = resolveOrNull(u, avatarSize); return avatar != null ? avatar : Jenkins.getInstance().getRootUrl() + Functions.getResourcePath() + "/images/" + avatarSize + "/user.png"; }
java
public void setActiveButton(I_CmsToolbarButton button) { m_activeButton = button; setEditButtonsVisible((button == null) || m_editor.getSelection().equals(button)); }
java
boolean serveStaticResource(HttpServletRequest req, StaplerResponse rsp, InputStream in, long lastModified, long expiration, long contentLength, String fileName) throws IOException { try { {// send out Last-Modified, or check If-Modified-Since if(lastModified!=0) { ...
java
public void addIntermediary(AbstractPlanNode node) { // transfer this node's children to node Iterator<AbstractPlanNode> it = m_children.iterator(); while (it.hasNext()) { AbstractPlanNode child = it.next(); it.remove(); // remove this.child from...
java
public static boolean handle(File zip, String name, ZipEntryCallback action) { ZipFile zf = null; try { zf = new ZipFile(zip); ZipEntry ze = zf.getEntry(name); if (ze == null) { return false; // entry not found } InputStream in = new BufferedInputStream(zf.getInputStream(...
python
def flagmanager_cli(argv, alter_logger=True): """Command-line access to ``flagmanager`` functionality. The ``flagmanager`` task manages tables of flags associated with measurement sets. Its features are easy to implement that a standalone library function is essentially unnecessary. See the source code...
python
def import_context(target_zip): """ Overwrite old context.json, use context.json from target_zip :param target_zip: :return: """ context_path = tasks.get_context_path() with zipfile.ZipFile(target_zip) as unzipped_data: with open(context_path, 'w') as context: context.wri...
java
@Override public void postWrite(Site site) { if(processors != null){ for(Processor p: processors){ p.postWrite(site); } } }
java
public List<DefaultIssue> loadClosedIssues(String componentUuid) { if (closedIssueMaxAge == 0) { return emptyList(); } Date date = new Date(system2.now()); long closeDateAfter = date.toInstant() .minus(closedIssueMaxAge, ChronoUnit.DAYS) .truncatedTo(ChronoUnit.DAYS) .toEpochMil...
java
public static Double checkNull(Double value, double elseValue) { return checkNull(value, Double.valueOf(elseValue)); }
python
def _check_patch_type_mismatch(self, patched_item, existing_item): """Enforces that each patch has a corresponding, already-defined data type.""" def raise_mismatch_error(patched_item, existing_item, data_type_name): error_msg = ('Type mismatch. Patch {} corresponds to pre-existing ' ...
python
def time_slides_vacuum(time_slides, verbose = False): """ Given a dictionary mapping time slide IDs to instrument-->offset mappings, for example as returned by the as_dict() method of the TimeSlideTable class in pycbc_glue.ligolw.lsctables or by the load_time_slides() function in this module, construct and return ...
java
public static Object streamIn(InputStream in, ClassLoader classLoader, boolean compressed) throws IOException, ClassNotFoundException { if (compressed) in = new GZIPInputStream(in); return new DroolsObjectInputStream(in, classLoader).readObject(); }
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "Cylinder", substitutionHeadNamespace = "http://www.opengis.net/gml", substitutionHeadName = "_GriddedSurface") public JAXBElement<CylinderType> createCylinder(CylinderType value) { return new JAXBElement<CylinderType>(_Cylinder_QNAME, Cylinde...
python
def read_union(fo, writer_schema, reader_schema=None): """A union is encoded by first writing a long value indicating the zero-based position within the union of the schema of its value. The value is then encoded per the indicated schema within the union. """ # schema resolution index = read_lo...
java
protected int getNextNode() { if (null != m_exprObj) { m_lastFetched = m_exprObj.nextNode(); } else m_lastFetched = DTM.NULL; return m_lastFetched; }
python
def taper_timeseries(tsdata, tapermethod=None, return_lal=False): """ Taper either or both ends of a time series using wrapped LALSimulation functions Parameters ---------- tsdata : TimeSeries Series to be tapered, dtype must be either float32 or float64 tapermethod : string ...
python
def ret_dump(self, d_ret, **kwargs): """ JSON print results to console (or caller) """ b_print = True for k, v in kwargs.items(): if k == 'JSONprint': b_print = bool(v) if b_print: print( json.dumps( ...
java
public <T> T getPropertyValueAs(final String propertyName, final boolean required, final Class<T> type) { try { return convert(getPropertyValue(propertyName, required), type); } catch (ConversionException e) { if (required) { throw new ConfigurationException(String.format( "Fai...
java
@Override public List<CommerceShippingMethod> findByGroupId(long groupId) { return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
protected void setLifecycleConfigurations(PropertyResolver configResolver, String configurationsCommonPrefix, Class<?> interfaceClass){ Integer phase = getConfigProperty(configResolver, configurationsCommonPrefix, ".phase", Integer.class, interfaceClass); if (phase == null){ logger.warn("No configuration found f...
java
@Override public <T extends ApiGameUser> List<T> in(ApiRoom room, Class<?> clazz) { Room sfsRoom = CommandUtil.getSfsRoom(room, extension); validateRoom(sfsRoom, room); return CommandUtil.getApiGameUserList(sfsRoom.getUserList(), clazz); }
java
public char charAt( int idx ) { if ( idx < 0 ) throw new IndexOutOfBoundsException("idx{"+idx+"} < 0"); if ( idx >= count ) throw new IndexOutOfBoundsException("idx{"+idx+"} >= buffer.length"); return buff[idx]; }
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case AfplibPackage.MCARG__RG_LENGTH: return getRGLength(); case AfplibPackage.MCARG__TRIPLETS: return getTriplets(); } return super.eGet(featureID, resolve, coreType); }
python
def docopt_cmd(func): """ This decorator is used to simplify the try/except block and pass the result of the docopt parsing to the called action. """ def helper_fn(self, arg): '''helper function for docopt''' try: opt = docopt(helper_fn.__doc__, arg) except Docopt...
python
def yaml2tree(cls, yamltree): """Class method that creates a tree from YAML. | # Example yamltree data: | - !Node &root | name: "root node" | parent: null | data: | testpara: 111 | - !Node &child1 | name: "child node" | paren...
python
def filter_kwargs(keys, kwargs): """ :param keys: A iterable key names to select items :param kwargs: A dict or dict-like object reprensents keyword args >>> list(filter_kwargs(("a", "b"), dict(a=1, b=2, c=3, d=4))) [('a', 1), ('b', 2)] """ for k in keys: if k in kwargs: ...
python
def snmp_server_host_severity_level(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp") host = ET.SubElement(snmp_server, "host") ip_key = ET.SubElement(hos...
java
public Observable<ServiceResponse<Page<SharedAccessAuthorizationRuleResourceInner>>> listAuthorizationRulesWithServiceResponseAsync(final String resourceGroupName, final String namespaceName, final String notificationHubName) { return listAuthorizationRulesSinglePageAsync(resourceGroupName, namespaceName, notif...
java
public static Iterable<byte[]> iterateOnSplits(final byte[] a, final byte[] b, final int num) { return iterateOnSplits(a, b, false, num); }
java
public Observable<ServiceResponseWithHeaders<UploadBatchServiceLogsResult, ComputeNodeUploadBatchServiceLogsHeaders>> uploadBatchServiceLogsWithServiceResponseAsync(String poolId, String nodeId, UploadBatchServiceLogsConfiguration uploadBatchServiceLogsConfiguration, ComputeNodeUploadBatchServiceLogsOptions computeNode...
java
public void run() { this.runnerState = JobControl.RUNNING; while (true) { while (this.runnerState == JobControl.SUSPENDED) { try { Thread.sleep(5000); } catch (Exception e) { } } checkRunningJobs(); checkWaitingJobs(); startReadyJo...
java
public static VariableCreator creator(final String pathServiceSid, final String pathEnvironmentSid, final String key, final String value) { return new VariableCreator(pathServiceSid, ...
python
def deleteNetwork(self, id, headers=None, query_params=None, content_type="application/json"): """ Delete network It is method for DELETE /network/{id} """ uri = self.client.base_url + "/network/"+id return self.client.delete(uri, None, headers, query_params, content_type...
python
def bitcoin_sig_hash(message): """Bitcoin has a special format for hashing messages for signing. :param message: the encoded message to hash in preparation for verifying """ padded = b'\x18Bitcoin Signed Message:\n' +\ int_to_var_bytes(len(message)) +\ message return double_sha256(p...
python
def create_requests_request_name_debug_entries(self, batch, request_name, collection): """CreateRequestsRequestNameDebugEntries. [Preview API] Create debug entries for a symbol request as specified by its name. :param :class:`<DebugEntryCreateBatch> <azure.devops.v5_0.symbol.models.DebugEntryCre...
python
def _create_cfgnode(self, sim_successors, call_stack, func_addr, block_id=None, depth=None, exception_info=None): """ Create a context-sensitive CFGNode instance for a specific block. :param SimSuccessors sim_successors: The SimSuccessors object. :param CallStack call_stack_suff...
java
public static String toHex(Color color) { if(color != null) { return "#" + Integer.toHexString(color.getRed()) + Integer.toHexString(color.getGreen()) + Integer.toHexString(color.getBlue()); } return null; }
python
def DeleteGRRUser(self, username): """Deletes the user and all related metadata with the given username.""" try: del self.approvals_by_username[username] except KeyError: pass # No approvals to delete for this user. for approvals in itervalues(self.approvals_by_username): for approva...
java
void remove_child(int idx) { assert(idx >=0); assert(idx < get_child_count()); // this also asserts child count > 0 assert get_child(idx) != null : "No child at index " + idx; _children[idx].detachFromContainer(); int children_to_move = _child_count - idx - 1; if (ch...
python
def get_embeddings(self, rand=None, dtype='float32'): """ Retrieves the embeddings for the vocabulary. :param rand: Random initialization function for out-of-vocabulary words. Defaults to `np.random.uniform(-0.1, 0.1, size=shape)`. :param dtype: Type of the matrix. :return: embe...
java
private AbstractRule processFormula(RulesTextProvider textProvider) { log.debug("processFormula"); Formula rule = new Formula(); int start = textProvider.getPos(); LoadCommonRuleData(rule,textProvider); textProvider.addTOCElement(null, rule.getDescription(), start, textProvider....
python
def generate_messages_info(msgs): """Add proper formated variable names, initializers and type names to use in templates""" for msg in msgs: msg.swift_name = camel_case_from_underscores(msg.name) msg.formatted_description = "" if msg.description: msg.description = " ".join(...
java
public List<ContentKeyAuthorizationPolicyRestriction> getRestrictions() { List<ContentKeyAuthorizationPolicyRestriction> result = new ArrayList<ContentKeyAuthorizationPolicyRestriction>(); List<ContentKeyAuthorizationPolicyRestrictionType> restrictionsTypes = getContent().getRestrictions(); if ...
java
public List<org.openprovenance.prov.model.Type> getType() { if (type == null) { type=AttributeList.populateKnownAttributes(this,all, org.openprovenance.prov.model.Type.class); } return this.type; }
python
def p_formula_atom(self, p): """formula : ATOM | TRUE | FALSE""" if p[1]==Symbols.TRUE.value: p[0] = PLTrue() elif p[1]==Symbols.FALSE.value: p[0] = PLFalse() else: p[0] = PLAtomic(Symbol(p[1]))
python
def copy(self): """ Convenience method to get a copy of the structure, with options to add site properties. Returns: A copy of the Structure, with optionally new site_properties and optionally sanitized. """ return GrainBoundary(self.lattice, self...
python
def matchremove_verb_endings(word): """Remove the verb endings""" """verb endings sorted by charlen then alph""" verb_endings =['issiiens', 'isseient', 'issiiez', 'issons', 'issent', 'issant', 'isseie', 'isseit', 'issons', 'isseiz', 'assent', 'issons', 'isseiz', 'issent', 'iiens', 'eient'...
python
def cli(yamlfile, directory, out, classname, format): """ Generate graphviz representations of the biolink model """ DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out)
python
def flatten(repertoire, big_endian=False): """Flatten a repertoire, removing empty dimensions. By default, the flattened repertoire is returned in little-endian order. Args: repertoire (np.ndarray or None): A repertoire. Keyword Args: big_endian (boolean): If ``True``, flatten the rep...
python
def get_package_release_from_pypi(pkg_name, version, pypi_json_api_url, allowed_classifiers): """ No classifier-based selection of Python packages is currently implemented: for now we don't fetch any .whl or .egg Eventually, we should select the best release available, based on the classifier & PEP 425: htt...
python
def process(self, chunk): """ computes the hash of all of the trigrams in the chunk using a window of length 5 """ self._digest = None if isinstance(chunk, text_type): chunk = chunk.encode('utf-8') # chunk is a byte string for char in chunk: ...
python
def _connect(self): "Wrap the socket with SSL support" sock = super(SSLConnection, self)._connect() if hasattr(ssl, "create_default_context"): context = ssl.create_default_context() context.check_hostname = False context.verify_mode = self.cert_reqs ...
java
@Override public String getId() { StringBuilder strId = new StringBuilder(); strId.append(id); if (nextProcessor != null) { strId.append(",").append(nextProcessor.getId()); } return strId.toString(); }
java
private static int getPairIndex(int ch) { int probe = pairedCharPower; int index = 0; if (ch >= pairedChars[pairedCharExtra]) { index = pairedCharExtra; } while (probe > (1 << 0)) { probe >>= 1; if (ch >= pairedChars[index + probe]) { ...
java
public void setParamTabExWorkplaceSearchResult(String style) { if (style == null) { style = OpenCms.getWorkplaceManager().getDefaultUserSettings().getWorkplaceSearchViewStyle().getMode(); } m_userSettings.setWorkplaceSearchViewStyle(CmsSearchResultStyle.valueOf(style)); }
python
def split_options(opts, validate=True, warn=False, normalize=True): """Takes the options portion of a MongoDB URI, validates each option and returns the options in a dictionary. :Parameters: - `opt`: A string representing MongoDB URI options. - `validate`: If ``True`` (the default), validat...
python
def get_children(self): """return the current child parts of this assessment part""" if self.has_magic_children(): if self._child_parts is None: self.generate_children() return self._child_parts raise IllegalState()
java
public final void sendSentinel(long txnId, int partitionId) { final long initiatorHSId = m_cartographer.getHSIdForSinglePartitionMaster(partitionId); sendSentinel(txnId, initiatorHSId, -1, -1, true); }
python
def get_json_or_yaml(file_path, content): """ Generate JSON or YAML depending on the file extension. """ if os.path.splitext(file_path)[1] == ".json": return json.dumps(content, sort_keys=False, indent=4, separators=(',', ': ')) else: return inginious.common.custom_yaml.dump(content)
python
def encrpyt_file(self, filename): ''' Encrypt File Args: filename: Pass the filename to encrypt. Returns: No return. ''' if not os.path.exists(filename): print "Invalid filename %s. Does not exist" % filename return ...
python
def _pretty_const_type_val(typecode, val): """ given a typecode and a value, returns the appropriate pretty version of that value (not the dereferenced data) """ if typecode == CONST_Utf8: typestr = "Utf8" # formerly Asciz, which was considered Java bug if not isinstance(val, str):...
java
public static String buildClusterMasterCommand(String clusterName, String nfsParentDir, String sinkLogRootDir, String awsConfDir, String appWorkDir, String masterS3ConfUri, String masterS3ConfFiles, String masterS3JarsUri, String masterS3JarsFiles, String masterJarsDir, String masterJvmMemory, O...
python
def _initiate_resumable_upload(self, stream, metadata, num_retries): """Initiate a resumable upload. :type stream: IO[bytes] :param stream: A bytes IO object open for reading. :type metadata: dict :param metadata: The metadata associated with the upload. :type num_retr...
java
public void validateRange(Config config, T value, Comparable<T> min, Comparable<T> max) { boolean isValid = min.compareTo(value) <= 0 && 0 <= max.compareTo(value); if (!isValid) { throw new MorphlineCompilationException( String.format("Invalid choice: '%s' (choose from {%s..%s})", ...
java
private void transferRow(TransferResultSet r, PreparedStatement p, int len, int[] types) throws DataAccessPointException, SQLException { for (int i = 1; i <= len; i++) { int t = types[i]; Object o ...
java
public boolean getParamBoolean(String paramName) { Object paramValue = getParam(paramName); if (paramValue == null) { return false; } return Boolean.parseBoolean(paramValue.toString()); }
java
public void setTotalColorForRow(int row, Color color){ int map = (colors[0].length-1) - row; colors[colors.length-1][map]=color; }
java
public void start() { lockRemover.start(); // Remove all locks records directly from DB. boolean deleteLocks = "true".equalsIgnoreCase(PrivilegedSystemHelper.getProperty(LOCKS_FORCE_REMOVE, "false")); if (deleteLocks) { doClean(); } // remove all locks at the st...
java
protected boolean canConsumeThisString(String string, boolean consume) { if (string == null) { return false; } for (int i = 0; i < string.length(); i++) { if (!input.next(i).is(string.charAt(i))) { return false; } } if (consume)...
python
def users(self): """Get current users and add in any search results. :returns: a list of dicts with keys - id - title :rtype: list """ existing_users = self.existing_users() existing_user_ids = [x['id'] for x in existing_users] # Only add searc...
java
public boolean closeOutbound() throws SSLException { if (sslEngine == null || sslEngine.isOutboundDone()) { return false; } sslEngine.closeOutbound(); createOutNetBuffer(0); SSLEngineResult result; for (;;) { result = sslEngine.wrap(emptyBuffer.b...
java
public void setTimeUnit(com.google.api.ads.admanager.axis.v201808.TimeUnit timeUnit) { this.timeUnit = timeUnit; }
java
public static void noNullElements(Object[] array) { Validate.notNull(array); for (int i = 0; i < array.length; i++) { if (array[i] == null) { throw new IllegalArgumentException("The validated array contains null element at index: " + i); } } }
python
def check_effective(func): """decorator, tests if an Assessment or Section is effective, raises error if not Side benefit: raised NotFound on AssessmentSections and AssessmentTakens """ def wrapper(*args, **kwargs): if ('assessment_section_id' in kwargs or args and 'Section' in...
python
def macro_attachment_create(self, macro_id, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/macros#create-macro-attachment" api_path = "/api/v2/macros/{macro_id}/attachments.json" api_path = api_path.format(macro_id=macro_id) return self.call(api_path, method="POST", d...
java
private static byte[] toByteArray(final ByteBuffer buffer) { if (buffer.hasArray() && buffer.arrayOffset() == 0 && buffer.position() == 0 && buffer.array().length == buffer.limit()) { return buffer.array(); } else { final byte[] retVal = new byte[buffer.remaining()]; ...
java
public ValidationConfigurationDescriptor addNamespace(String name, String value) { model.attribute(name, value); return this; }
java
public String getLink() { String strType = this.getField(ClassInfo.CLASS_TYPE).getString(); String strLink = this.getField(ClassInfo.CLASS_NAME).getString(); if (this.getField(ClassInfo.CLASS_PACKAGE).getLength() > 0) strLink = DBConstants.ROOT_PACKAGE + this.getField(ClassInfo.C...
java
public int ZoomForPixelSize( int pixelSize ) { for( int i = 0; i < 30; i++ ) { if (pixelSize > Resolution(i)) { if (i != 0) { return i - 1; } else { return 0; // We don't want to scale up } } ...
python
def all_api_methods(cls): """ Return a list of all the TradingAlgorithm API methods. """ return [ fn for fn in itervalues(vars(cls)) if getattr(fn, 'is_api_method', False) ]
java
private void appendToFile(RandomAccessFile output, InputStream input) throws IOException { byte[] buffer = new byte[1024 * 1024]; int bytesRead = 0; do { bytesRead = input.read(buffer); if (bytesRead < 0) break; output.write(buffer,...
java
@Override public WsByteBuffer[] marshallLine() { WsByteBuffer[] firstLine = new WsByteBuffer[1]; firstLine[0] = allocateBuffer(getOutgoingBufferSize()); firstLine = putBytes(getVersionValue().getByteArray(), firstLine); firstLine = putByte(SPACE, firstLine); if (null == this...
java
public UpdateAppRequest withEnvironmentVariables(java.util.Map<String, String> environmentVariables) { setEnvironmentVariables(environmentVariables); return this; }
java
public Matrix3x2d scaleAround(double sx, double sy, double ox, double oy) { return scaleAround(sx, sy, ox, oy, this); }
java
@Override public final void update(double extrp, double speed, double y) { final int lowest = totalHeight; int py; if (maxY == 0) { py = (int) y; } else { final double currentY = UtilMath.clamp(y, minY, maxY); py = (int)...
java
public static void replaceNodeValue(final Document doc, final String xPath, final String newValue) { final Text textNode = doc.createTextNode(newValue); try { final Node node = (Node) s_path.evaluate(xPath, doc, XPathConstants.NODE); if (LOG....
python
def get_attributes(self): """ Returns the unordered list of attributes :return: list of strings """ attr = ['chr', 'start', 'stop'] if self.strandPos is not None: attr.append('strand') if self.otherPos: for i, o in enumerate(self.otherPos): ...
java
public static char getCorrespondingSymbol(String name) { Character symbol = (Character) map.get(name); if (symbol == null) { return (char)0; } return symbol.charValue(); }
java
public Stream<ProtectedBranch> getProtectedBranchesStream(Object projectIdOrPath) throws GitLabApiException { return (getProtectedBranches(projectIdOrPath, this.getDefaultPerPage()).stream()); }
python
def main(): """ Main function of this example. """ parser = argparse.ArgumentParser() parser.add_argument( '--digest', default="md5", help="Digest to use", choices=sorted( getattr(hashlib, 'algorithms', None) or hashlib.algorithms_available)) parser.add_argument( ...
java
@GET @Produces(MediaType.APPLICATION_JSON) @Path("/{gavc}" + ServerAPI.SET_DO_NOT_USE) public Response getDoNotUse(@PathParam("gavc") final String gavc){ if(LOG.isInfoEnabled()) { LOG.info(String.format("Got a get doNotUse artifact request [%s]", gavc)); } final DbArtifa...
python
def add(ctx, short_name, uri, interval, buffer): """Add a subscription with a given short_name for a given uri This command can be used to create subscriptions to receive new pieces of vehicle data on the stream channel on a periodic basis. By default, subscriptions are buffered and have a 5 second interval: \b ...
java
public static TrimmedTileSet trimTileSet (TileSet source, OutputStream destImage) throws IOException { return trimTileSet(source, destImage, FastImageIO.FILE_SUFFIX); }