language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def sun_rise_set_transit_ephem(times, latitude, longitude, next_or_previous='next', altitude=0, pressure=101325, temperature=12, horizon='0:00'): """ Calculate the next sunrise and sunset ...
python
def libc(cls): """ Alpine linux uses a non glibc version of the standard library, it uses the stripped down musl instead. The core agent can be built against it, but which one is running must be detected. Shelling out to `ldd` appears to be the most reliable way to do this. ...
java
@Override public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception { if (profileSessionCreated) { long start = timeNow(); nextFilter.sessionCreated(session); long end = timeNow(); sessionCreatedTimerWorker.addNewDuratio...
python
def sum_queryset(qs: QuerySet, key: str= 'amount', default=Decimal(0)) -> Decimal: """ Returns aggregate sum of queryset 'amount' field. :param qs: QuerySet :param key: Field to sum (default: 'amount') :param default: Default value if no results :return: Sum of 'amount' field values (coalesced 0...
java
protected void initDataSource() { if (dataSource == null) { if (dataSourceJndiName != null) { try { dataSource = (DataSource) new InitialContext().lookup(dataSourceJndiName); } catch (Exception e) { throw new ProcessEngineException("couldn't lookup datasource from " + dataS...
python
def toProtocolElement(self): """ Returns the GA4GH protocol representation of this ReadGroupSet. """ readGroupSet = protocol.ReadGroupSet() readGroupSet.id = self.getId() readGroupSet.read_groups.extend( [readGroup.toProtocolElement() for readGrou...
java
public void removeIgnoreCase(String key) { int i = indexOfKeyIgnoreCase(key); if (i != NotFound) remove(i); }
python
def request_booking_details(self, poll_url, **params): """ Request for booking details URL Format: {API_HOST}/apiservices/pricing/v1.0/{session key}/booking ?apiKey={apiKey} """ return self.make_request("%s/booking" % poll_url, ...
python
def confd_state_loaded_data_models_data_model_namespace(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") loaded_data_models = ET.SubElement(confd_state, "l...
java
public static List<String> loadOptions(String optionFileName) { List<String> args = new ArrayList<String>(); File optionFile = new File(optionFileName); StringWriter stringWriter = new StringWriter(); try { InputStream inputStream = new FileInputStream(optionFile); IOUtils.copy(inputSt...
java
private void appendAffix(StringBuffer buffer, String affixPattern, String expAffix, boolean localized) { if (affixPattern == null) { appendAffix(buffer, expAffix, localized); } else { int i; for (int pos=0; pos<affixPattern.length(); pos=i...
python
def _cookie_parse_impl(b): """Lowlevel cookie parsing facility that operates on bytes.""" i = 0 n = len(b) while i < n: match = _cookie_re.search(b + b";", i) if not match: break key = match.group("key").strip() value = match.group("val") or b"" i = ...
java
public void setHealthCheckRegistry(Object healthCheckRegistry) { checkIfSealed(); if (healthCheckRegistry != null) { healthCheckRegistry = getObjectOrPerformJndiLookup(healthCheckRegistry); if (!(healthCheckRegistry instanceof HealthCheckRegistry)) { throw new IllegalArgum...
java
public static boolean hasForUpdate(Object parameter) { if (parameter != null && parameter instanceof Example) { Example example = (Example) parameter; return example.isForUpdate(); } return false; }
java
public void greet(String name) { logger.info("Will try to greet " + name + " ..."); HelloRequest request = HelloRequest.newBuilder().setName(name).build(); HelloReply response; SpanBuilder spanBuilder = tracer.spanBuilder("client").setRecordEvents(true).setSampler(Samplers.alwaysSample()); ...
java
protected void handleListCache() { reportable.output("Listing resources in the cache"); List<CachedResource> resources = cacheLookupService.getResources(); if (resources.isEmpty()) { reportable.output("No resources in the cache."); } for (CachedResource resource : r...
java
public PaymillList<Client> list( Integer count, Integer offset ) { return this.list( null, null, count, offset ); }
python
def _set_up_inheritance_and_subclass_sets(self, schema_data): """Load all inheritance data from the OrientDB schema. Used as part of __init__.""" # For each class name, construct its inheritance set: # itself + the set of class names from which it inherits. for class_definition in schema...
java
void doParse(String filePath, Reader fileContents) { this.filePath = filePath; parseSucceeded = true; BufferedReader lineBuffer = new BufferedReader(fileContents); // Parse all lines. String line = null; lineNum = 0; boolean inMultilineComment = false; boolean inJsDocComment = false; ...
java
private static int getMessageCountExcludeSelf(Messenger<String> messenger, String id) { Set<String> messageSet = newHashSet(messenger.receiveMessages()); messageSet.remove(id); return messageSet.size(); }
java
@Override public Collection<String> getAppliesToMinimumVersions() { Collection<String> versions = new HashSet<String>(); try { List<AppliesToFilterInfo> entries = generateAppliesToFilterInfoList(false); if (entries != null) { for (AppliesToFilterInfo appliesTo...
python
def OnHelpMove(self, event): """Help window move event handler stores position in config""" position = event.GetPosition() config["help_window_position"] = repr((position.x, position.y)) event.Skip()
java
public void removeDependentVariables(Variable ... depVars) { ArrayList<Variable> newDepVars = new ArrayList<Variable>(); for (Variable v : this.dependentVariables) { boolean toRemove = false; for (Variable v1 : depVars) { if (v.equals(v1)) { toRemove = true; break; } } if (!t...
java
protected Object getAllValues(BackedSession sess) { if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) { LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[GET_ALL_VALUES]); } Connection conn = g...
python
def parse_commandline(argv): """ Returns the arguments parsed from *argv* as a namespace. """ ap = ArgumentParser( prog='wdiffhtml', description=DESCRIPTION, epilog=EPILOG, ) ap.add_argument( '--version', action='version', version='wdiffhtml v{}'.format(version), help="shows version and...
python
def author_impact_factor(self, year=2014, refresh=True): """Get author_impact_factor for the . Parameters ---------- year : int (optional, default=2014) The year based for which the impact factor is to be calculated. refresh : bool (optional, default=True) ...
python
def from_transport(cls, t): """ Create an SFTP client channel from an open L{Transport}. @param t: an open L{Transport} which is already authenticated @type t: L{Transport} @return: a new L{SFTPClient} object, referring to an sftp session (channel) across the transpo...
java
public static ValueMatcher makeValueMatcherGeneric(DimensionSelector selector, @Nullable String value) { IdLookup idLookup = selector.idLookup(); if (idLookup != null) { return makeDictionaryEncodedValueMatcherGeneric(selector, idLookup.lookupId(value), value == null); } else if (selector.getValueCa...
java
private void generateInnerAccessPaths(BranchNode parentNode) { JoinNode innerChildNode = parentNode.getRightNode(); assert(innerChildNode != null); // In case of inner join WHERE and JOIN expressions can be merged if (parentNode.getJoinType() == JoinType.INNER) { parentNode.m...
java
public int add(final Message msg, boolean resize) { if(msg == null) return 0; if(index >= messages.length) { if(!resize) return 0; resize(); } messages[index++]=msg; return 1; }
java
public static void addInitParameters(Holder holder, Properties subSection) { //TODO rename initparam to property Properties properties = PropertiesSupport.getSubsection(subSection, "initparam"); // System.out.println("PROPS:" + properties); for (Object key : properties.keySet()) { // System.out.println(key + "...
java
public UrlChain moreUrl(Object... urlParts) { final String argTitle = "urlParts"; assertArgumentNotNull(argTitle, urlParts); checkWrongUrlChainUse(argTitle, urlParts); this.urlParts = urlParts; return this; }
python
def showPluginMenu(self, panel, point=None): """ Creates the interface menu for this view widget. If no point is \ supplied, then the current cursor position will be used. :param panel | <XViewPanel> point | <QPoint> || None """ if not s...
python
def load_all(self): ''' Helper function for actual Insights client use ''' # check for custom conf file before loading conf self._load_command_line(conf_only=True) self._load_config_file() self._load_env() self._load_command_line() self._imply_opti...
java
protected Association getAssociation(final ServerManager serverManager, final ParameterList parameterList) { try { val authReq = AuthRequest.createAuthRequest(parameterList, serverManager.getRealmVerifier()); val parameterMap = authReq.getParameterMap(); if (parameterMap != n...
java
List<MemberState> getReserveMemberStates(Comparator<MemberState> comparator) { List<MemberState> reserveMembers = new ArrayList<>(getReserveMemberStates()); Collections.sort(reserveMembers, comparator); return reserveMembers; }
python
def _GetHeader(self): """Returns header.""" header = [] for value in self.values: try: header.append(value.Header()) except SkipValue: continue return header
java
public static String sha256(String string) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest messageDigest; messageDigest = MessageDigest.getInstance("SHA-256"); byte[] hash = messageDigest.digest(string.getBytes("UTF-8")); return String.valueOf(Hex.encode...
python
def exclude(self, col: str, val): """ Delete rows based on value :param col: column name :type col: str :param val: value to delete :type val: any :example: ``ds.exclude("Col 1", "value")`` """ try: self.df = self.df[self.df[col] != v...
python
def get_article_by_search(text): """从搜索文章获得的文本 提取章列表信息 Parameters ---------- text : str or unicode 搜索文章获得的文本 Returns ------- list[dict] { 'article': { 'title': '', # 文章标题 'url': '',...
java
public static void assertNotEqual(Object a, Object b, String message) { if (Objects.equals(a, b)) { fail(message); } }
java
public void configure(Object obj, Element cfg, int startIdx) throws Exception { String id = getAttribute(cfg, "id"); if (id != null) { _idMap.put(id, obj); } Element[] children = getChildren(cfg); for (int i = startIdx; i < children.length; i++) { Element node = children[i]; //CHECKSTYLE:OFF ...
java
public StringColumn append(String value) { try { lookupTable.append(value); } catch (NoKeysAvailableException ex) { lookupTable = lookupTable.promoteYourself(); try { lookupTable.append(value); } catch (NoKeysAvailableException e) { ...
python
def as_dict(self): """ Return a dictionary containing the current values of the object. Returns: (dict): The object represented as a dictionary """ out = {} for prop in self: propval = getattr(self, prop) if hasattr(propval, 'for_json...
java
public static <A extends Number & Comparable<?>> NumberExpression<Double> degrees(Expression<A> num) { return Expressions.numberOperation(Double.class, Ops.MathOps.DEG, num); }
java
public static LocalResource createLocalResource(FileSystem fs, Path provisionedResourcePath){ try { FileStatus scFileStatus = fs.getFileStatus(provisionedResourcePath); LocalResource localResource = LocalResource.newInstance( ConverterUtils.getYarnUrlFromURI(provisionedResourcePath.toUri()), LocalReso...
python
def put(self, key, value, lease=None): """Put puts the given key into the key-value store. A put request increments the revision of the key-value store and generates one event in the event history. :param key: :param value: :param lease: :return: boolean ...
java
@Override protected void checkForSessionIdListenerAndAdd(Object listener){ // Added for Servlet 3.1 support if (isHttpSessionIdListener(listener)) { // add to the HttpSessionIdListener list ((IHttpSessionContext31)this.sessionCtx).addHttpSessionIdListener((javax.servlet.http....
java
@Override public Collection<String> sendEmailMessages(final Collection<EmailMessage> emailMessages) throws MessagingException { final List<String> messageIds = new ArrayList<>(); for (final EmailMessage emailMessage : emailMessages) { final String messageId = sendEmailMessage(emailMessage); messageIds.a...
java
public void setTransportControlFlags(int transportControlFlags) { if (sHasRemoteControlAPIs) { try { sRCCSetTransportControlFlags.invoke(mActualRemoteControlClient, transportControlFlags); } catch (Exception e) { throw new RuntimeEx...
java
protected void closeDialog(boolean breakingUp) { m_controller.stopEditingGroupcontainer(); m_editingPlaceholder.removeFromParent(); m_editorDialog.hide(); RootPanel.get().removeStyleName(I_CmsLayoutBundle.INSTANCE.containerpageCss().groupcontainerEditing()); if (!breakingUp) { ...
java
@Override public Object invokeMethod(final Class sender, final Object object, final String methodName, final Object[] arguments, final boolean isCallToSuper, final boolean fromInsideClass) { return doCall(object, methodName, arguments, interceptor, new Callable() { public Object call() { ...
java
public static long count_filtered(nitro_service service, String monitorname, String filter) throws Exception{ lbmonbindings_service_binding obj = new lbmonbindings_service_binding(); obj.set_monitorname(monitorname); options option = new options(); option.set_count(true); option.set_filter(filter); lbmonbin...
python
def get_index(lis, argument): """Find the index of an item, given either the item or index as an argument. Particularly useful as a wrapper for arguments like channel or axis. Parameters ---------- lis : list List to parse. argument : int or object Argument. Returns --...
java
@Deprecated public void fatal(Object message, Object[] params) { doLog(Level.FATAL, FQCN, message, params, null); }
python
def get_all_allowed_plugins(self): """ Return which plugins are allowed by the placeholder fields. """ # Get all allowed plugins of the various placeholders together. if not hasattr(self.model, '_meta_placeholder_fields'): # No placeholder fields in the model, no need...
java
public SignedJWT signToken(JWTClaimsSet claims) { try { SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claims); signedJWT.sign(new MACSigner(this.jwtSharedSecret)); return signedJWT; } catch (JOSEException e) { throw new RuntimeExce...
java
@XmlElementDecl(namespace = "http://www.w3.org/1998/Math/MathML", name = "arcsech") public JAXBElement<ElementaryFunctionsType> createArcsech(ElementaryFunctionsType value) { return new JAXBElement<ElementaryFunctionsType>(_Arcsech_QNAME, ElementaryFunctionsType.class, null, value); }
java
public static <S extends RepresentationModel<?>> HeaderLinksResponseEntity<S> wrap(S entity) { Assert.notNull(entity, "ResourceSupport must not be null!"); return new HeaderLinksResponseEntity<>(ResponseEntity.ok(entity)); }
java
@XmlElementDecl(namespace = "http://www.ibm.com/websphere/wim", name = "jpegPhoto") public JAXBElement<byte[]> createJpegPhoto(byte[] value) { return new JAXBElement<byte[]>(_JpegPhoto_QNAME, byte[].class, null, (value)); }
java
private static int parseDotted(String javaVersion) { try { String[] parts = javaVersion.split("[._]"); int firstVer = Integer.parseInt(parts[0]); if (firstVer == 1 && parts.length > 1) { return Integer.parseInt(parts[1]); } else { return firstVer; } } catch (NumberF...
python
def get_gconf_http_proxy (): """Return host:port for GConf HTTP proxy if found, else None.""" try: import gconf except ImportError: return None try: client = gconf.client_get_default() if client.get_bool("/system/http_proxy/use_http_proxy"): host = client.get_...
python
def _decode8(self, offset): """ Decode an UTF-8 String at the given offset :param offset: offset of the string inside the data :return: str """ # UTF-8 Strings contain two lengths, as they might differ: # 1) the UTF-16 length str_len, skip = self._decode_...
python
def vector_drive(self, vx, vy, vw, tm_diff): """Call this from your :func:`PhysicsEngine.update_sim` function. Will update the robot's position on the simulation field. This moves the robot using a velocity vector relative to the robot instead of by speed/rotation sp...
java
public void setMobileCarrierTargeting(com.google.api.ads.admanager.axis.v201805.MobileCarrierTargeting mobileCarrierTargeting) { this.mobileCarrierTargeting = mobileCarrierTargeting; }
java
public RetryTemplateBuilder customPolicy(RetryPolicy policy) { Assert.notNull(policy, "Policy should not be null"); Assert.isNull(this.baseRetryPolicy, "You have already selected another retry policy"); this.baseRetryPolicy = policy; return this; }
java
public void checkServerTrusted( X509Certificate[] chain, String authType ) throws CertificateException { X509Certificate certificate = chain[0]; String cert = fingerprint( certificate ); if ( this.fingerprint == null ) { try { sav...
java
public void setAuthorizationPersistencePolicy(PersistencePolicy policy) { if (policy == null) { throw new IllegalArgumentException("The policy argument cannot be null"); } if (preferences.persistencePolicy.get() != policy) { preferences.persistencePolicy.set(policy); ...
python
def drag(self, NewPt): # //Mouse drag, calculate rotation (Point2fT Quat4fT) """ drag (Point2fT mouse_coord) -> new_quaternion_rotation_vec """ X = 0 Y = 1 Z = 2 W = 3 self.m_EnVec = self._mapToSphere(NewPt) # //Compute the vector perpendicular t...
java
private static Object deserializePage(String value, Type resultType, Type wireType, SerializerAdapter serializer, SerializerEncoding encoding) throws IOException { final Type wireResponseType; if (wireType == Page.class) { // If the type is the 'Page' interface [i.e. `@ReturnValueWireType(P...
python
def set(cls, var_name: str, value: Any) -> 'Configuration': """ Set the variable :param var_name: Variable name :param value: Value of variable :return: :class:`~haps.config.Configuration` instance for easy\ chaining """ with cls._lock: ...
python
def unregister(self, alias): """Unregisters a service instance. Stops a service and removes it from the manager. Args: alias: string, the alias of the service instance to unregister. """ if alias not in self._service_objects: raise Error(self._device, ...
java
protected synchronized static void drawAt(final Canvas canvas, final Drawable drawable, final int x, final int y, final boolean shadow, final float aMapOrientation) { canvas.save(); canvas.rotate(-aMapOrientation, x, y); drawable.copyBounds(mRect); drawable.setBounds(mRect.left + x, mR...
java
public com.google.api.ads.admanager.axis.v201902.Location[] getExcludedLocations() { return excludedLocations; }
java
public boolean wrapInAnchor() { if (ext(ANCHORLINKS | EXTANCHORLINKS)) { SuperNode node = (SuperNode) peek(); List<Node> children = node.getChildren(); if (ext(EXTANCHORLINKS)) { if (children.size() > 0) { AnchorNodeInfo nodeInfo = new Anch...
python
def is_iframe(self, el): """Check if element is an `iframe`.""" return ((el.name if self.is_xml_tree(el) else util.lower(el.name)) == 'iframe') and self.is_html_tag(el)
python
def _rule2path(cls, rule): """Convert relative Flask rule to absolute OpenAPI path.""" typeless = re.sub(r'<\w+?:', '<', rule) # remove Flask types return typeless.replace('<', '{').replace('>', '}')
java
protected ClientVersionBean getClientVersionInternal(String organizationId, String clientId, String version, boolean hasPermission) { try { storage.beginTx(); ClientVersionBean clientVersion = storage.getClientVersion(organizationId, clientId, version); if (client...
java
@Modified protected void modified(ComponentContext context) throws Exception { processProperties(context.getProperties()); deregisterJavaMailMBean(); registerJavaMailMBean(); }
java
@SuppressWarnings({ "unchecked", "rawtypes" }) @Deprecated public <T, I extends Serializable> ResourceRepositoryStub<T, I> getQueryParamsRepository(Class<T> resourceClass) { init(); RegistryEntry entry = resourceRegistry.findEntry(resourceClass); // TODO fix this in katharsis, should be able to get original r...
python
def count_start(tokenizer): """ A decorator which wrap the given tokenizer to yield (token, start). Notice! the decorated tokenizer must take a int arguments stands for the start position of the input context/sentence >>> tokenizer = lambda sentence: sentence.split(' ') >>> tokenizer('The quick bro...
python
def duplicate_transcript(self, transcript_id, organism=None, sequence=None): """ Duplicate a transcripte :type transcript_id: str :param transcript_id: Transcript UUID :type organism: str :param organism: Organism Common Name :type sequence: str :param ...
java
public SmbTransport getDc(String domain, SmbExtendedAuthenticator authenticator, NtlmPasswordAuthentication auth) throws SmbAuthException { // public SmbTransport getDc(String domain, // NtlmPasswordAuthentication auth) throws SmbAuthException { // SmbAuthenticator<< if (DISAB...
python
def get_domain_event(self, originator_id, position): """ Gets a domain event from the sequence identified by `originator_id` at position `eq`. :param originator_id: ID of a sequence of events :param position: get item at this position :return: domain event """ ...
python
def record_calculation_start(self, variable_name, period, **parameters): """ Record that OpenFisca started computing a variable. :param str variable_name: Name of the variable starting to be computed :param Period period: Period for which the variable is being computed ...
python
def display(self, img, title=None, colormap=None, style='image', subtitles=None, auto_contrast=False, contrast_level=None, **kws): """display image""" if title is not None: self.SetTitle(title) if subtitles is not None: self.subtitles = subtitles c...
java
private String buildCacheKey(final String[] objectIds, final String namespace) { if (objectIds.length == 1) { checkKeyPart(objectIds[0]); return namespace + SEPARATOR + objectIds[0]; } StringBuilder cacheKey = new StringBuilder(namespace); cacheKey.append(SEPARAT...
java
public Object navigation(Context context, NavigationCallback callback) { return ARouter.getInstance().navigation(context, this, -1, callback); }
python
def process_request(self, request): """ Reloads glitter URL patterns if page URLs change. Avoids having to restart the server to recreate the glitter URLs being used by Django. """ global _urlconf_pages page_list = list( Page.objects.exclude(glitter_app_name...
java
@Override public BundleHashcodeType getBundleHashcodeType(String requestedPath) { BundleHashcodeType typeBundleHashcode = BundleHashcodeType.UNKNOW_BUNDLE; String[] pathInfos = PathNormalizer.extractBundleInfoFromPath(requestedPath, bundlePrefixes); if (pathInfos != null) { String bundlePrefix = pathInfos[...
java
public Properties getProperties() { Properties props = new Properties(); for(String name : this.users.keySet()) { SimpleAccount acct = this.users.get(name); props.setProperty(USERNAME_PREFIX + name, acct.getCredentials().toString()); } return props; }
python
def eth_getTransactionByBlockHashAndIndex(self, bhash, index=0): """https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_gettransactionbyblockhashandindex :param bhash: Block hash :type bhash: str :param index: Index position (optional) :type index: int """ result...
java
private void setParentIcon(boolean iconify) { if (rootParent instanceof JFrame) { JFrame frame = (JFrame) rootParent; int state = frame.getExtendedState(); ((JFrame) rootParent).setExtendedState(iconify ? state | Frame.ICONIFIED : state & ~Frame.ICONIFIED); ...
python
def generate_scan_configuration_description(scan_parameters): '''Generate scan parameter dictionary. This is the only way to dynamically create table with dictionary, cannot be done with tables.IsDescription Parameters ---------- scan_parameters : list, tuple List of scan parameters names (stri...
python
def setup(app): """Initialize Sphinx extension.""" import sphinx from .parser import CommonMarkParser if sphinx.version_info >= (1, 8): app.add_source_suffix('.md', 'markdown') app.add_source_parser(CommonMarkParser) elif sphinx.version_info >= (1, 4): app.add_source_parser(...
python
def ret_range_minions(self): ''' Return minions that are returned by a range query ''' if HAS_RANGE is False: raise RuntimeError("Python lib 'seco.range' is not available") minions = {} range_hosts = _convert_range_to_list(self.tgt, __opts__['range_server']) ...
python
def split_args_text_to_list(self, args_text): """Split the text including multiple arguments to list. This function uses a comma to separate arguments and ignores a comma in brackets ans quotes. """ args_list = [] idx_find_start = 0 idx_arg_start = 0 ...
java
boolean isEquivalent(final Path other) { if (pathComponents.isEmpty() && other.pathComponents.isEmpty()) { return true; } if (pathComponents.isEmpty() || other.pathComponents.isEmpty()) { return false; } final String thisFirst = this.pathComponents.getFi...
java
B append(String path) { Preconditions.checkArgument( path != null && !path.isEmpty(), "'path' must be a non-empty String"); ImmutableList.Builder<String> components = ImmutableList.builder(); components.addAll(this.getSegments()); components.add(splitChildPath(path)); return createPathWithSe...
python
def _match_to_morph_parents(self, type, results): """ Match the results for a given type to their parent. :param type: The parent type :type type: str :param results: The results to match to their parent :type results: Collection """ for result in result...