language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def diamondTabularFormatToDicts(filename, fieldNames=None): """ Read DIAMOND tabular (--outfmt 6) output and convert lines to dictionaries. @param filename: Either a C{str} file name or an open file pointer. @param fieldNames: A C{list} or C{tuple} of C{str} DIAMOND field names. Run 'diamond -h...
java
public String saveExecutionResult(String username, String password, Vector<?> args) { return confluenceServiceDelegator.saveExecutionResult(username, password, args); }
java
public void marshall(CommandFilter commandFilter, ProtocolMarshaller protocolMarshaller) { if (commandFilter == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(commandFilter.getKey(), KEY_BINDING); ...
java
public void setIcon(Icon icon) { Icon old = null; if (iconInfo == CommandButtonIconInfo.BLANK_ICON_INFO) { if (icon != null) { // New IconInfo fires event setIconInfo(new CommandButtonIconInfo(icon)); } } else { old = ic...
java
public void marshall(DeleteBackupRequest deleteBackupRequest, ProtocolMarshaller protocolMarshaller) { if (deleteBackupRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteBackupRequest.ge...
python
def get_contacts_of_client_per_page(self, client_id, per_page=1000, page=1): """ Get contacts of client per page :param client_id: the client id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list """ ...
python
def pos_int(i): """ Simple positive integer validation. """ try: if isinstance(i, string_types): i = int(i) if not isinstance(i, int) or i < 0: raise Exception() except: raise ValueError("Not a positive integer") return i
java
protected void printError(final Span references[], final Span predictions[], final T referenceSample, final T predictedSample, final String sentence) { final List<Span> falseNegatives = new ArrayList<Span>(); final List<Span> falsePositives = new ArrayList<Span>(); findErrors(references, predictions,...
java
public void setAjaxStartEvent(ISliderAjaxEvent ajaxStartEvent) { this.ajaxEvents.put(SliderAjaxEvent.ajaxStartEvent, ajaxStartEvent); setSlideEvent(new SliderAjaxJsScopeUiEvent(this, SliderAjaxEvent.ajaxStartEvent)); }
java
public static double getGradDotDirApprox(Function fn, IntDoubleVector x, IntDoubleVector d, double c) { double dot = 0; { // L(\theta + c * d) IntDoubleVector d1 = d.copy(); d1.scale(c); IntDoubleVector x1 = x.copy(); x1.add(d1); do...
python
def p_statement_while(p): 'statement : WHILE LPAREN expr RPAREN while_statement' p[0] = ast.While(p[3], p[5], lineno=p.lineno(1))
python
def _add_hookimpl(self, hookimpl): """Add an implementation to the callback chain. """ if hookimpl.hookwrapper: methods = self._wrappers else: methods = self._nonwrappers if hookimpl.trylast: methods.insert(0, hookimpl) elif hookimpl.t...
python
def plugin_class_validation(self, plugin_class): """Plugin validation Every workbench plugin must have a dependencies list (even if it's empty). Every workbench plugin must have an execute method. Args: plugin_class: The loaded plugun class. Returns: ...
python
def load(self, config): """Load the web list from the configuration file.""" web_list = [] if config is None: logger.debug("No configuration file available. Cannot load ports list.") elif not config.has_section(self._section): logger.debug("No [%s] section in the...
java
protected JvmTypeReference inferFunctionReturnType(XtendFunction source, JvmOperation target, JvmOperation overriddenOperation) { // The return type is explicitly given if (source.getReturnType() != null) { return ensureValidType(source.eResource(), source.getReturnType()); } // An super operation was detec...
python
def words_for_language(language_code): """ Return the math words for a language code. The language_code should be an ISO 639-2 language code. https://www.loc.gov/standards/iso639-2/php/code_list.php """ word_groups = word_groups_for_language(language_code) words = [] for group in word_g...
python
def as_issue(self): """ :calls: `GET /repos/:owner/:repo/issues/:number <http://developer.github.com/v3/issues>`_ :rtype: :class:`github.Issue.Issue` """ headers, data = self._requester.requestJsonAndCheck( "GET", self.issue_url ) return gi...
python
def set_args(self, args, unknown_args=None): """ Configure job, based on the arguments provided. """ if unknown_args is None: unknown_args = [] self.logger.setLevel(getattr(logging, args.log_level)) parent = hdfs.path.dirname(hdfs.path.abspath(args.output.rst...
python
def flush(self, fsync=False): """ Force all buffered modifications to be written to disk. Parameters ---------- fsync : bool (default False) call ``os.fsync()`` on the file handle to force writing to disk. Notes ----- Without ``fsync=True``, fl...
python
def addImg(self, img, maxShear=0.015, maxRot=100, minMatches=12, borderWidth=3): # borderWidth=100 """ Args: img (path or array): image containing the same object as in the reference image Kwargs: maxShear (float): In order to define a good fit, refe...
java
@Override public boolean checkAndDelete(byte[] row, byte[] family, byte[] qualifier, byte[] value, Delete delete) throws IOException { return checkAndDelete(row, family, qualifier, CompareFilter.CompareOp.EQUAL, value, delete); }
java
public boolean isValid( ChronoElement<Long> element, long value ) { return this.isValid(element, Long.valueOf(value)); }
java
public static <T> List<Class<?>> getPublicConcreteSubTypesOf(final Class<T> type) { return ClassGraphFacade.getPublicConcreteSubTypesOf(type); }
python
def json_or_jsonp(func): """Wrap response in JSON or JSONP style""" @wraps(func) def _(*args, **kwargs): mimetype = 'application/javascript' callback = request.args.get('callback', None) if callback is None: content = func(*args, **kwargs) else: conte...
python
def _prepair(self): '''Try to connect to the given dbus services. If successful it will return a callable dbus proxy and those arguments. ''' try: sessionbus = dbus.SessionBus() systembus = dbus.SystemBus() except: return (None, None) ...
java
public static Matcher<JsonElement> areItemsValid(final Validator validator) { return new TypeSafeDiagnosingMatcher<JsonElement>() { @Override protected boolean matchesSafely(JsonElement item, Description mismatchDescription) { //we do not care for the properties if parent...
python
def register_by_twine(self): """ register via the twine method :return: """ check_call_no_output([ '{}'.format(self.python), 'setup.py', 'bdist_wheel', ]) # at this point there should be only one file in the 'dist' folder ...
python
def decode_bytes(byt, enc='utf-8'): """Given a string or bytes input, return a string. Args: bytes - bytes or string enc - encoding to use for decoding the byte string. """ try: strg = byt.decode(enc) except UnicodeDecodeError as err: strg = "Unable to decode mess...
java
public void setDeploymentInfoCustomizers( Collection<? extends UndertowDeploymentInfoCustomizer> customizers) { Assert.notNull(customizers, "Customizers must not be null"); this.deploymentInfoCustomizers = new ArrayList<>(customizers); }
java
protected void push(String location, FragmentBuilder builder, Node node) { // Check if any in content should be processed for the current node processInContent(location, builder, -1); builder.pushNode(node); }
java
public static String formatBytes (byte[] data, int start, int count) { return formatBytes(data, start, count, true); }
python
def accumulate_impl(func, sequence): # pylint: disable=no-name-in-module """ Implementation for accumulate :param sequence: sequence to accumulate :param func: accumulate function """ if six.PY3: from itertools import accumulate return accumulate(sequence, func) else: ...
java
private static String loggerRequest(HttpUriRequest request){ String id = UUID.randomUUID().toString(); if(logger.isInfoEnabled()||logger.isDebugEnabled()){ if(request instanceof HttpEntityEnclosingRequestBase){ HttpEntityEnclosingRequestBase request_base = (HttpEntityEnclosingRequestBase)request; HttpEnt...
java
public ServiceFuture<RouteTableInner> updateTagsAsync(String resourceGroupName, String routeTableName, Map<String, String> tags, final ServiceCallback<RouteTableInner> serviceCallback) { return ServiceFuture.fromResponse(updateTagsWithServiceResponseAsync(resourceGroupName, routeTableName, tags), serviceCallbac...
java
protected void processClass (File source) { CtClass clazz; InputStream in = null; try { clazz = _pool.makeClass(in = new BufferedInputStream(new FileInputStream(source))); } catch (IOException ioe) { System.err.println("Failed to load " + source + ": " + ioe);...
python
def parse_packet(packet): """Parse a beacon advertisement packet.""" frame = parse_ltv_packet(packet) if frame is None: frame = parse_ibeacon_packet(packet) return frame
java
public HttpClientResponseBuilder doReturnJSON(String response, Charset charset) { return doReturn(response, charset).withHeader("Content-type", APPLICATION_JSON.toString()); }
python
def _convert_todo(self, p_todo): """ Converts a Todo instance (Topydo) to an icalendar Todo instance. """ def _get_uid(p_todo): """ Gets a unique ID from a todo item, stored by the ical tag. If the tag is not present, a random value is assigned to it and returned. ...
java
public V findChachedValueOf(K key) { // check selection for (V value : selection) { if (getKeyOf(value).equals(key)) { return value; } } // check data cache for (V value : getData()) { if (getKeyOf(value).equals(key)) { return value; } } return null; }
python
def export(context, keywords, module, update): """Operate on libraries and exported functions. Query the module name containing the function by default. Windows database must be prepared before using this. """ logging.info(_('Export Mode')) database = context.obj['sense'] none = True i...
java
public ArrayList returnErrors() { if (_containerErrors != null) return _containerErrors.returnErrors(); ArrayList e = _errors; _errors = null; return e; }
python
def topology_mdtraj(traj): '''Generate topology spec for the MolecularViewer from mdtraj. :param mdtraj.Trajectory traj: the trajectory :return: A chemview-compatible dictionary corresponding to the topology defined in mdtraj. ''' import mdtraj as md top = {} top['atom_types'] = [a.elemen...
python
def safe(self,x): """removes nans and infs from outputs.""" x[np.isinf(x)] = 1 x[np.isnan(x)] = 1 return x
python
def _save_archive(self): """Saves the JSON archive of processed pull requests. """ import json from utility import json_serial with open(self.archpath, 'w') as f: json.dump(self.archive, f, default=json_serial)
java
public ContainerDefinition withVolumesFrom(VolumeFrom... volumesFrom) { if (this.volumesFrom == null) { setVolumesFrom(new com.amazonaws.internal.SdkInternalList<VolumeFrom>(volumesFrom.length)); } for (VolumeFrom ele : volumesFrom) { this.volumesFrom.add(ele); } ...
python
def face_encodings(face_image, known_face_locations=None, num_jitters=1): """ Given an image, return the 128-dimension face encoding for each face in the image. :param face_image: The image that contains one or more faces :param known_face_locations: Optional - the bounding boxes of each face if you al...
python
def is_feature_enabled(self, feature_key, user_id, attributes=None): """ Returns true if the feature is enabled for the given user. Args: feature_key: The key of the feature for which we are determining if it is enabled or not for the given user. user_id: ID for user. attributes: Dict represe...
java
public void help() { p(""); p("Command Description"); p("======= ==========="); p("help() Display usage and help messages. "); p("defineClass(className) Define an extension using the Java class"); p(" nam...
java
public List<String> getExtensionPoints(String prefix,String suffix){ return extensionPointsCache.get(prefix+"@"+suffix); }
java
public Iterator<PlaceObject> enumeratePlaces () { final Iterator<PlaceManager> itr = _pmgrs.values().iterator(); return new Iterator<PlaceObject>() { public boolean hasNext () { return itr.hasNext(); } public PlaceObject next () { P...
java
public static boolean isOverlappingAfter(final Interval timeRange, final Interval timeRangeToCheck) { return ((timeRange.getStart() != null && timeRange.getStart().isBefore(timeRangeToCheck.getStart())) && (timeRange.getEnd() != null && timeRange.getEnd().isBefore(timeRangeToCheck.getEnd()))); }
java
public void marshall(GitConfig gitConfig, ProtocolMarshaller protocolMarshaller) { if (gitConfig == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(gitConfig.getRepositoryUrl(), REPOSITORYURL_BINDING)...
java
public void removeEntity(Entity entity){ boolean delayed = updating || familyManager.notifying(); entityManager.removeEntity(entity, delayed); }
java
public static void main(String[] argv) { SimpleSourcedTokenizer tokenizer = DEFAULT_SOURCED_TOKENIZER; int n = 0; for (int i=0; i<argv.length; i++) { System.out.println("argument "+i+": '"+argv[i]+"'"); SourcedToken[] tokens = tokenizer.sourcedTokenize(argv[i],Integer.toString(i))...
python
def receive_message(self, header, message): """Receive a message""" print("=== Receive ===") print(header) print(message) print("MsgID: {0}".format(header["message-id"])) assert header["message-id"] txn = self._transport.transaction_begin() print(" 1. T...
java
private void readWaypoint(final Element waypoint, final List<GraphObjectMap> resultList) { final GraphObjectMap item = readPoint(waypoint); if (item != null) { resultList.add(item); } }
python
def hex_hash160(s, hex_format=False): """ s is in hex or binary format """ if hex_format and is_hex(s): s = unhexlify(s) return hexlify(bin_hash160(s))
python
def get_all_package_releases(self, package_name: str) -> Iterable[Tuple[str, str]]: """ Returns a tuple of release data (version, manifest_ur) for every release of the given package name available on the current registry. """ validate_package_name(package_name) self._vali...
java
protected boolean completeAppend(boolean succeeded, long lastLogIndex, CompletableFuture<AppendResponse> future) { future.complete(logResponse(AppendResponse.builder() .withStatus(RaftResponse.Status.OK) .withTerm(raft.getTerm()) .withSucceeded(succeeded) .withLastLogIndex(lastLogInd...
python
def is_value_in(constants_group, value): """ Checks whether value can be found in the given constants group, which in turn, should be a Django-like choices tuple. """ for const_value, label in constants_group: if const_value == value: return True return False
python
def widen(self): """Increase the interval size.""" t, h = self.time, self.half_duration h *= self.scaling_coeff_x self.set_interval((t - h, t + h))
python
def random_str_uuid(string_length): """Returns a random string of length string_length""" if not isinstance(string_length, int) or not 1 <= string_length <= 32: msg = "string_length must be type int where 1 <= string_length <= 32" raise ValueError(msg) random = str(uuid.uuid4()).upper().repl...
python
def _check_not_empty(string): """ Checks that the string is not empty. If it is empty an exception is raised, stopping the validation. This is used for compulsory alphanumeric fields. :param string: the field value """ string = string.strip() if len(string) == 0: message = 'T...
java
private static Weekmodel getDefaultWeekmodel() { return Weekmodel.of(Weekday.SATURDAY, 1, Weekday.SATURDAY, Weekday.SUNDAY); }
python
def all_terms(self): """Iterate over all of the terms. The self.terms property has only root level terms. This iterator iterates over all terms""" for s_name, s in self.sections.items(): # Yield the section header if s.name != 'Root': yield s ...
python
def main(): '''main reoutine''' # validate command line arguments arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--vmssname', '-n', required=True, action='store', help='VMSS Name') arg_parser.add_argument('--rgname', '-g', required=True, ...
java
public ItBitOrder[] getItBitOrders(String status, String instrument) throws IOException { ItBitOrder[] orders = itBitAuthenticated.getOrders( signatureCreator, new Date().getTime(), exchange.getNonceFactory(), instrument, "1", "1000", ...
python
def get_cmd_tuple_list(self): """ Return a list of tuples containg the command line arguments """ # pattern to find DAGman macros pat = re.compile(r'\$\((.+)\)') argpat = re.compile(r'\d+') # first parse the options and replace macros with values options = self.job().get_opts() mac...
java
void setWorkbenchLayout(Layout layout) { validateNotNull(layout, "layout"); if (this.layout == layout) { return; } requestTabIndex = getCurrentRequestTabIndex(); Layout previousLayout = this.layout; this.layout = layout; componentMaximiser.unmaximiseComponent(); removeAll(); Lis...
java
public MoneyParseContext parse(CharSequence text, int startIndex) { checkNotNull(text, "Text must not be null"); if (startIndex < 0 || startIndex > text.length()) { throw new StringIndexOutOfBoundsException("Invalid start index: " + startIndex); } if (isParser() == false...
java
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeyException, XmlPullParserException { try { /* play.min.io for test and development. */ MinioClient minioClient = new MinioClient("https://play.min.io:9000", "Q3AM3UQ867SPQQA43P2F", ...
java
@Override public String readString() throws JMSException { backupState(); try { return MessageConvertTools.asString(internalReadObject()); } catch (JMSException e) { restoreState(); throw e; } catch (RuntimeException e) { restoreState(); throw e; ...
java
public ApiResponse<DeviceTypesEnvelope> getDeviceTypesByApplicationWithHttpInfo(String appId, Boolean productInfo, Integer count, Integer offset) throws ApiException { com.squareup.okhttp.Call call = getDeviceTypesByApplicationValidateBeforeCall(appId, productInfo, count, offset, null, null); Type local...
java
private Bitmap getBitmapOfView(final View view){ view.destroyDrawingCache(); view.buildDrawingCache(false); Bitmap orig = view.getDrawingCache(); Bitmap.Config config = null; if(orig == null) { return null; } config = orig.getConfig(); if(config == null) { config = Bitmap.Config.ARGB_8888; } ...
python
def hatchery(): """ Main entry point for the hatchery program """ args = docopt.docopt(__doc__) task_list = args['<task>'] if not task_list or 'help' in task_list or args['--help']: print(__doc__.format(version=_version.__version__, config_files=config.CONFIG_LOCATIONS)) return 0 l...
java
@Override boolean hasContent(LessExtendMap lessExtends ) { if( output.length() == 0 ) { return false; } if( !isConcatExtents ) { isConcatExtents = true; selectors = lessExtends.concatenateExtends( selectors, isReference ); } return selector...
python
def insertPreviousCommand(self): """ Inserts the previous command from history into the line. """ self._currentHistoryIndex -= 1 if 0 <= self._currentHistoryIndex < len(self._history): cmd = self._history[self._currentHistoryIndex] else: cm...
python
def encode_dense(input_sentences, nbest_size=0, alpha=1.0, model_file=None, model_proto=None, reverse=False, add_bos=False, add_eos=False, out_type=tf.int32, name=None): """Encodes sentences into pieces in dense tensor format. Args: input_sentences: A 1D strin...
python
def _normalize(self, string): ''' Returns a sanitized string. ''' string = string.replace(u'\xb7', '') string = string.replace(u'\u0331', '') string = string.replace(u'\u0323', '') string = string.strip(' \n\rI.') return string
python
def route_filter_rules(self): """Instance depends on the API version: * 2016-12-01: :class:`RouteFilterRulesOperations<azure.mgmt.network.v2016_12_01.operations.RouteFilterRulesOperations>` * 2017-03-01: :class:`RouteFilterRulesOperations<azure.mgmt.network.v2017_03_01.operations.RouteFil...
python
def start_auth(self, context, internal_req): """ See super class method satosa.backends.base.BackendModule#start_auth :type context: satosa.context.Context :type internal_req: satosa.internal.InternalData :rtype: satosa.response.Response """ target_entity_id = co...
python
def allocate(self): """Initializes libvirt resources.""" disk_path = self.provider_image self._hypervisor = libvirt.open( self.configuration.get('hypervisor', 'vbox:///session')) self._domain = domain_create(self._hypervisor, self.identifier, ...
java
private void validateWorkflow(WorkflowDef workflowDef, Map<String, Object> workflowInput, String externalStoragePath) { try { //Check if the input to the workflow is not null if (workflowInput == null && StringUtils.isBlank(externalStoragePath)) { LOGGER.error("The input ...
java
public Module build() { SagaLibModule module = new SagaLibModule(); module.setStateStorage(stateStorage); module.setTimeoutManager(timeoutMgr); module.setScanner(scanner); module.setProviderFactory(providerFactory); module.setExecutionOrder(preferredOrder); module...
python
def details_dict(obj, existing, ignore_missing, opt): """Output the changes, if any, for a dict""" existing = dict_unicodeize(existing) obj = dict_unicodeize(obj) for ex_k, ex_v in iteritems(existing): new_value = normalize_val(obj.get(ex_k)) og_value = normalize_val(ex_v) if ex_...
java
public static File touch(File file) throws IORuntimeException { if (null == file) { return null; } if (false == file.exists()) { mkParentDirs(file); try { file.createNewFile(); } catch (Exception e) { throw new IORuntimeException(e); } } return file; }
java
private Set<String> initExcludedPathList(Set<String> paths) { Set<String> toExclude = new HashSet<>(); if (null == paths) return toExclude; for (String path : paths) { path = PathNormalizer.asPath(path); toExclude.add(path); } return toExclude; }
java
public static boolean isBenchmarkable(final Method meth) { boolean returnVal = true; // Check if bench-anno is given. For testing purposes against // before/after annos final Bench benchAnno = meth.getAnnotation(Bench.class); // if method is annotated with SkipBench, the method is never // benchmarkable. ...
java
public URL copyWith(String serviceUUID, String characteristicUUID, String fieldName) { return new URL(this.protocol, this.adapterAddress, this.deviceAddress, this.deviceAttributes, serviceUUID, characteristicUUID, fieldName); }
java
public Observable<ServiceResponse<Integer>> getUntaggedImageCountWithServiceResponseAsync(UUID projectId, UUID iterationId) { if (projectId == null) { throw new IllegalArgumentException("Parameter projectId is required and cannot be null."); } if (this.client.apiKey() == null) { ...
python
def run_sparql_on(q, ontology): """ Run a SPARQL query (q) on a given Ontology (Enum EOntology) """ logging.info("Connecting to " + ontology.value + " SPARQL endpoint...") sparql = SPARQLWrapper(ontology.value) logging.info("Made wrapper: {}".format(sparql)) sparql.setQuery(q) sparql.set...
python
def __ensure_suffix_stem(t, suffix): """ Ensure that the target t has the given suffix, and return the file's stem. """ tpath = str(t) if not tpath.endswith(suffix): stem = tpath tpath += suffix return tpath, stem else: stem, ext = os.path.splitext(tpath) ...
java
public void persistAttributes() { String attrName = getScopedName( STORED_ATTRS_ATTR ); getSession().setAttribute( attrName, _scopedContainer.getSerializableAttrs() ); }
java
public void marshall(UpdateRoleAliasRequest updateRoleAliasRequest, ProtocolMarshaller protocolMarshaller) { if (updateRoleAliasRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateRoleAli...
java
protected void renderColumnBody( FacesContext facesContext, ResponseWriter writer, UIData uiData, UIComponent component, Styles styles, int columnStyleIndex) throws IOException { // Get the rowHeader attribute from the attribute map, because of MYF...
python
def getGeneralInfo(rh): """ Obtain general information about the host. Input: Request Handle with the following properties: function - 'GETHOST' subfunction - 'GENERAL' Output: Request Handle updated with the results. Return code - 0: ok Return code -...
java
public static <P> Setting of( String description, ListProperty<P> items, ObjectProperty<P> selection) { return new Setting<>( description, Field.ofSingleSelectionType(items, selection) .label(description) .render(new SimpleComboBoxControl<>()), selection); }
python
def community_post_subscription_show(self, post_id, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/subscriptions#show-post-subscription" api_path = "/api/v2/community/posts/{post_id}/subscriptions/{id}.json" api_path = api_path.format(post_id=post_id, id=id) retu...
java
Table SYSTEM_SESSIONS() { Table t = sysTables[SYSTEM_SESSIONS]; if (t == null) { t = createBlankTable(sysTableHsqlNames[SYSTEM_SESSIONS]); addColumn(t, "SESSION_ID", CARDINAL_NUMBER); addColumn(t, "CONNECTED", TIME_STAMP); addColumn(t, "USER_NAME", SQL_...
python
def libs(args): """ %prog libs libfile Get list of lib_ids to be run by pull(). The SQL commands: select library.lib_id, library.name from library join bac on library.bac_id=bac.id where bac.lib_name="Medicago"; select seq_name from sequence where seq_name like 'MBE%' and trash is ...