language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def transform_symmop(self, symmop): # type: (Union[SymmOp, MagSymmOp]) -> Union[SymmOp, MagSymmOp] """ Takes a symmetry operation and transforms it. :param symmop: SymmOp or MagSymmOp :return: """ W = symmop.rotation_matrix w = symmop.translation_vector ...
python
def setUser(request): """In standalone mode, change the current user""" if not settings.PIAPI_STANDALONE or settings.PIAPI_REALUSERS: raise Http404 request.session['plugit-standalone-usermode'] = request.GET.get('mode') return HttpResponse('')
java
@Override public java.util.List<com.liferay.commerce.model.CommerceAddressRestriction> getCommerceAddressRestrictions( int start, int end) { return _commerceAddressRestrictionLocalService.getCommerceAddressRestrictions(start, end); }
java
public static void makeAccessible(Constructor<?> ctor) { if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) && !ctor.isAccessible()) { ctor.setAccessible(true); } }
python
def init_app(self, app): """Flask application initialization. :param app: The Flask application. :returns: The :class:`invenio_pages.ext.InvenioPages` instance initialized. """ self.init_config(app) self.wrap_errorhandler(app) app.extensions['invenio...
java
Stream<String> writeMeter(Meter meter) { // Snapshot values should be used throughout this method as there are chances for values to be changed in-between. List<Attribute> attributes = new ArrayList<>(); for (Measurement measurement : meter.measure()) { double value = measurement.get...
python
def track(context, file_names): """Keep track of each file in list file_names. Tracking does not create or delete the actual file, it only tells the version control system whether to maintain versions (to keep track) of the file. """ context.obj.find_repo_type() for fn in file_names: ...
python
def MI_get_item(self, key, index=0): 'return list of item' index = _key_to_index_single(force_list(self.indices.keys()), index) if index != 0: key = self.indices[index][key] # always use first index key # key must exist value = super(MIMapping, self).__getitem__(key) N = len(self.indice...
python
def _isomorphism_rewrite_to_NECtree(q_s, qgraph): """ Neighborhood Equivalence Class tree (see Turbo_ISO paper) """ qadj = qgraph.adj adjsets = lambda x: set(chain.from_iterable(qadj[x].values())) t = ([q_s], []) # (NEC_set, children) visited = {q_s} vcur, vnext = [t], [] while vcur...
java
private static OptionalEntity<StemmerOverrideItem> getEntity(final CreateForm form) { switch (form.crudMode) { case CrudMode.CREATE: final StemmerOverrideItem entity = new StemmerOverrideItem(0, StringUtil.EMPTY, StringUtil.EMPTY); return OptionalEntity.of(entity); case C...
java
private void doWakeUpWorker() { if (idleWorkers.get() == 0) { synchronized (workers) { if (workers.size() >= getMaximumPoolSize()) { return; } if (workers.isEmpty() || (idleWorkers.get() == 0)) { addWorkerUnsafe...
python
def importPreflibFile(self, fileName): """ Imports a preflib format file that contains all the information of a Profile. This function will completely override all members of the current Profile object. Currently, we assume that in an election where incomplete ordering are allowed, if a...
python
def insert(self, s): ''' Insert string @s at the current cursor location. ''' for c in s: self.text.insert(self.cursor_loc, c) self.cursor_loc += 1
java
@Override public SetIdentityMailFromDomainResult setIdentityMailFromDomain(SetIdentityMailFromDomainRequest request) { request = beforeClientExecution(request); return executeSetIdentityMailFromDomain(request); }
java
public boolean data_setCookie(Integer userId, CharSequence cookieName, CharSequence cookieValue, Long expiresTimestamp, CharSequence path) throws FacebookException, IOException { if (null == userId || 0 >= userId) throw new IllegalArgumentException("userId should be provided."); if (null == cookieNam...
python
def get_predictions_under_minimal_repair(instance, repair_options, optimum): ''' Computes the set of signs on edges/vertices that can be cautiously derived from [instance], minus those that are a direct consequence of obs_[ev]label predicates ''' inst = instance.to_file() repops = repair...
java
public final MessageSerializer getDefaultSerializer() { // Construct a default serializer if we don't have one if (null == this.defaultSerializer) { // Don't grab a lock unless we absolutely need it synchronized(this) { // Now we have a lock, double check there's ...
python
def reflectance(self, band): """ :param band: An optical band, i.e. 1-5, 7 :return: At satellite reflectance, [-] """ if band == 6: raise ValueError('LT5 reflectance must be other than band 6') rad = self.radiance(band) esun = self.ex_atm_irrad[band...
java
public static <M extends Model> FXMLComponentBase loadFXML(final M model, final String fxmlPath) { return loadFXML(model, fxmlPath, null); }
java
public RESTResponse runCommand(Command command) { if (this.applicationName != null) { command.setApplicationName(this.applicationName); } if (this.storageService != null) { command.setStorageService(this.storageService); } if (this.restMetadataJson...
java
@Override protected boolean internalEquals(ValueData another) { if (another instanceof StreamPersistedValueData) { StreamPersistedValueData streamValue = (StreamPersistedValueData)another; if (file != null && file.equals(streamValue.file)) { return true; ...
java
public Object getEnumValue(String name) { if (this.kind != Kind.ENUM) throw new RuntimeException("getEnumValue(..) can only be called on an enum"); Object[] vals = getEnumValues(); if (vals != null) { for (Object val : vals) { if (((Enum<?>)val).name().equals(name)) return val; } } return nu...
python
def element_not_contains(self, element_id, value): """ Assert provided content is not contained within an element found by ``id``. """ elem = world.browser.find_elements_by_xpath(str( 'id("{id}")[contains(., "{value}")]'.format( id=element_id, value=value))) assert not elem, \ ...
java
public OvhPrivateLinkRoute serviceName_privateLink_peerServiceName_route_network_GET(String serviceName, String peerServiceName, String network) throws IOException { String qPath = "/router/{serviceName}/privateLink/{peerServiceName}/route/{network}"; StringBuilder sb = path(qPath, serviceName, peerServiceName, net...
java
private static void exportSymbols(SymbolTable syms, String filename) { if (syms == null) { return; } try (PrintWriter out = new PrintWriter(new FileWriter(filename))) { for (ObjectIntCursor<String> sym : syms) { out.println(sym.key + "\t" + sym.value); } } catch (IOException e...
java
@Override public Vector<Object> marshallize() { Vector<Object> vector = super.marshallize(); // replace the URL set by DocumentNode. This is to maintain backwar compatibility. Shifting the indexes would break everything. String url = null; if (vector.size() == 5) { url = (String) vector.set(NODE_REPOSITOR...
python
def clustering_coef_bu(G): ''' The clustering coefficient is the fraction of triangles around a node (equiv. the fraction of nodes neighbors that are neighbors of each other). Parameters ---------- A : NxN np.ndarray binary undirected connection matrix Returns ------- C : N...
java
protected boolean executeGenerator() throws MojoExecutionException { // Add resources and output directory to plugins classpath List<Object> classpathEntries = new ArrayList<Object>(); classpathEntries.addAll(project.getResources()); classpathEntries.add(project.getBuild().getOutputDirectory()); extendPlugin...
java
public static String dateFormat(long ts, String format, TimeZone tz) { SimpleDateFormat formatter = FORMATTER_CACHE.get(format); formatter.setTimeZone(tz); Date dateTime = new Date(ts); return formatter.format(dateTime); }
java
public void setWhitelistRules(java.util.Collection<InputWhitelistRuleCidr> whitelistRules) { if (whitelistRules == null) { this.whitelistRules = null; return; } this.whitelistRules = new java.util.ArrayList<InputWhitelistRuleCidr>(whitelistRules); }
python
def configure(self, transport, auth, address, port): """ Connect paramiko transport :type auth: :py:class`margaritashotgun.auth.AuthMethods` :param auth: authentication object :type address: str :param address: remote server ip or hostname :type port: int ...
java
public XMLString fixWhiteSpace(boolean trimHead, boolean trimTail, boolean doublePunctuationSpaces) { // %OPT% !!!!!!! int len = this.length(); char[] buf = new char[len]; this.getChars(0, len, buf, 0); boolean edit = false; int s; for (s = 0; s < len; ...
python
def sample_distinct(self, n_to_sample, **kwargs): """Sample a sequence of items from the pool until a minimum number of distinct items are queried Parameters ---------- n_to_sample : int number of distinct items to sample. If sampling with replacement, th...
java
private Iterator<Vector3> getConvexHullVerticesIterator() { List<Vector3> ans = new ArrayList<Vector3>(); Triangle curr = this.startTriangleHull; boolean cont = true; double x0 = bbMin.x, x1 = bbMax.x; double y0 = bbMin.y, y1 = bbMax.y; boolean sx, sy; while (cont) { sx = curr.p1().x == x0 || c...
python
def raw_repr(obj): '''Produce a representation using the default repr() regardless of whether the object provides an implementation of its own.''' if isproxy(obj): return '<%s with prime_id=%d>' % (obj.__class__.__name__, obj.prime_id) else: return repr(obj)
java
public String next(String ignoreZone) { if (entry == null) return null; entry = entry.next; if (entry.element.equals(ignoreZone)) { return entry.next.element; } else { return entry.element; } }
java
@Override public List<Scope> getScopesByCollector(ObjectId collectorId) { List<Scope> scopes = scopeRepository.findByCollectorId(collectorId); //clean up needed for < > characters for (Scope scope : scopes) { scope.setName( scope.getName().replaceAll("[<>]", "") ); scope.setProjectPath( scope.getProje...
java
private void registerServletDescriptor(ServletDescriptor servletDescriptor) { try { servletDescriptor.register(httpService); } catch (RuntimeException e) { LOG.error( "Registration of ServletDescriptor under mountpoint {} fails with unexpected RuntimeException!", ...
python
def add_routes(meteor_app, url_path=''): """ Adds search and retrieval routes to a :class:`meteorpi_server.MeteorServer` instance :param MeteorApp meteor_app: The :class:`meteorpi_server.MeteorApp` to which routes should be added :param string url_path: The base path used for the query ...
python
def _is_multiframe_4d(dicom_input): """ Use this function to detect if a dicom series is a philips multiframe 4D dataset """ # check if it is multi frame dicom if not common.is_multiframe_dicom(dicom_input): return False header = dicom_input[0] # check if there are multiple stacks ...
java
public static Resource temporaryDirectory() { File tempDir = new File(SystemInfo.JAVA_IO_TMPDIR); String baseName = System.currentTimeMillis() + "-"; for (int i = 0; i < 1_000_000; i++) { File tmp = new File(tempDir, baseName + i); if (tmp.mkdir()) { return new FileResour...
python
def load_components(*paths, **kwargs): """ Loads all components on the paths. Each path should be a package or module. All components beneath a path are loaded. Args: paths (str): A package or module to load Keyword Args: include (str): A regular expression of packages and modules ...
java
private String resolveName(String localName, String qualifiedName) { if ((localName == null) || (localName.length() == 0)) { return qualifiedName; } else { return localName; } }
python
def addFeature(self, feature): '''Appends Feature''' if isinstance(feature, Feature): self.features.append(feature) else: raise TypeError( 'feature Type should be Feature, not %s' % type(feature))
java
@Override protected void defineWidgets() { super.defineWidgets(); // widgets to display in first block (like edit view) addWidget(new CmsWidgetDialogParameter(getSearchIndexIndex(), "name", PAGES[0], new CmsDisplayWidget())); addWidget(new CmsWidgetDialogParameter(getSearchIndexInd...
python
def cal_frame_according_boundaries(left, right, top, bottom, parent_size, gaphas_editor=True, group=True): """ Generate margin and relative position and size handed boundary parameter and parent size """ # print("parent_size ->", parent_size) margin = cal_margin(parent_size) # Add margin and ensure that...
python
def metadata(ctx, archive_name): ''' Get an archive's metadata ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) click.echo(pprint.pformat(var.get_metadata()))
python
def remove_edges(self, from_idx, to_idx, symmetric=False, copy=False): '''Removes all from->to and to->from edges. Note: the symmetric kwarg is unused.''' flat_inds = self._pairs.dot((self._num_vertices, 1)) # convert to sorted order and flatten to_remove = (np.minimum(from_idx, to_idx) * self._num_...
python
def update(self, **params): """ Sends locally staged mutations to Riak. :param w: W-value, wait for this many partitions to respond before returning to client. :type w: integer :param dw: DW-value, wait for this many partitions to confirm the write before retur...
java
protected boolean objectVisibleToUser(String objectTenancyPath, String userTenancyPath) { // if in "same hierarchy" return objectTenancyPath.startsWith(userTenancyPath) || userTenancyPath.startsWith(objectTenancyPath); }
java
public static MemberUpdater updater(final String pathAccountSid, final String pathQueueSid, final String pathCallSid, final URI url, final HttpMethod method...
python
def peek_all(self, model_class): """Return a list of models from the local cache. Args: model_class (:class:`cinder_data.model.CinderModel`): A subclass of :class:`cinder_data.model.CinderModel` of your chosen model. Returns: list: A list of instances of...
java
private JButton getHelpButton() { if (btnHelp == null) { btnHelp = new JButton(); btnHelp.setBorder(null); btnHelp.setIcon(new ImageIcon(AbstractParamContainerPanel.class.getResource("/resource/icon/16/201.png"))); // help icon btnHelp.addActionListener(getSh...
python
def limit_current(self, curr): """Sets the current limit on the Grizzly. The units are in amps. The internal default value is 5 amps.""" if curr <= 0: raise ValueError("Current limit must be a positive number. You provided: %s" % str(curr)) current = int(curr * (1024.0 / 5.0)...
python
def setSpeed(self, personID, speed): """setSpeed(string, double) -> None Sets the maximum speed in m/s for the named person for subsequent step. """ self._connection._sendDoubleCmd( tc.CMD_SET_PERSON_VARIABLE, tc.VAR_SPEED, personID, speed)
python
def echo_attributes(request, config_loader_path=None, template='djangosaml2/echo_attributes.html'): """Example view that echo the SAML attributes of an user""" state = StateCache(request.session) conf = get_config(config_loader_path, request) client = Saml2Client...
java
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case AfplibPackage.BSG__REG_NAME: return getREGName(); case AfplibPackage.BSG__TRIPLETS: return getTriplets(); } return super.eGet(featureID, resolve, coreType); }
java
@Nullable public static CurrentLegAnnotation createCurrentAnnotation(CurrentLegAnnotation currentLegAnnotation, RouteLeg leg, double legDistanceRemaining) { LegAnnotation legAnnotation = leg.annotation(); if (legAnnotation == null) { return null; ...
python
def connect(host, username, password, port=443, verify=False, debug=False): ''' Connect to a vCenter via the API :param host: Hostname or IP of the vCenter :type host: str or unicode :param username: Username :type user: str or unicode :param password: Password :type user: str or unicode...
java
public boolean endsWith(String str, String suffix) { return (str == null || suffix == null) ? (str == suffix) : str.endsWith(suffix); }
python
def change_name(self, new_name): """Change the name of the shell, possibly updating the maximum name length""" if not new_name: name = self.hostname else: name = new_name.decode() self.display_name = display_names.change( self.display_name, nam...
python
def marshal_dict( obj, types, method=None, fields=None, **m_kwargs ): """ Recursively marshal a Python object to a dict that can be passed to json.{dump,dumps}, a web client, or a web server, document database, etc... Args: obj: object, It's members can be neste...
java
public static DZcs cs_symperm(DZcs A, int[] pinv, boolean values) { int i, j, p, q, i2, j2, n, Ap[], Ai[], Cp[], Ci[], w[] ; DZcsa Cx = new DZcsa(), Ax = new DZcsa() ; DZcs C ; if (!CS_CSC (A)) return (null) ; /* check inputs */ n = A.n ; Ap = A.p ; Ai = A.i ; Ax.x = A.x ; C = cs_spalloc (n, n, Ap[...
python
def _line_format(line): """Determine the column format pattern for a line in an ASCII segment file. """ for pat in (FOUR_COL_REGEX, THREE_COL_REGEX, TWO_COL_REGEX): if pat.match(line): return pat raise ValueError("unable to parse segment from line {!r}".format(line))
java
public MavenInstallation getMaven() { for( MavenInstallation i : getDescriptor().getInstallations() ) { if(mavenName !=null && mavenName.equals(i.getName())) return i; } return null; }
python
def PenForNode( self, node, depth=0 ): """Determine the pen to use to display the given node""" if node == self.selectedNode: return self.SELECTED_PEN return self.DEFAULT_PEN
java
@Override public ListHsmsResult listHsms(ListHsmsRequest request) { request = beforeClientExecution(request); return executeListHsms(request); }
java
public void marshall(NodeOverrides nodeOverrides, ProtocolMarshaller protocolMarshaller) { if (nodeOverrides == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(nodeOverrides.getNumNodes(), NUMNODES_BI...
python
def find_prepositions(chunked): """ The input is a list of [token, tag, chunk]-items. The output is a list of [token, tag, chunk, preposition]-items. PP-chunks followed by NP-chunks make up a PNP-chunk. """ # Tokens that are not part of a preposition just get the O-tag. for ch in chunked...
python
def grid(lon_edges, lat_edges, values, cmap, alpha=255, vmin=None, vmax=None, levels=10, colormap_scale='lin', show_colorbar=True): """ Values on a uniform grid :param lon_edges: longitude edges :param lat_edges: latitude edges :param values: matrix representing values on th...
python
def _fetch_app_role_token(vault_url, role_id, secret_id): """Get a Vault token, using the RoleID and SecretID""" url = _url_joiner(vault_url, 'v1/auth/approle/login') resp = requests.post(url, data={'role_id': role_id, 'secret_id': secret_id}) resp.raise_for_status() data = resp....
python
def map_equal_contributions(contributors): """assign numeric values to each unique equal-contrib id""" equal_contribution_map = {} equal_contribution_keys = [] for contributor in contributors: if contributor.get("references") and "equal-contrib" in contributor.get("references"): for ...
python
def compile_file(self, path, incl_search_paths=None): """ Parse & compile a single file and append it to RDLCompiler's root namespace. If any exceptions (:class:`~systemrdl.RDLCompileError` or other) occur during compilation, then the RDLCompiler object should be discarded. ...
python
def get_img_heatmap(orig_img, activation_map): """Draw a heatmap on top of the original image using intensities from activation_map""" heatmap = cv2.applyColorMap(activation_map, cv2.COLORMAP_COOL) heatmap = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB) img_heatmap = np.float32(heatmap) + np.float32(orig_img...
python
def compute_samples(channels, nsamples=None): ''' create a generator which computes the samples. essentially it creates a sequence of the sum of each function in the channel at each sample in the file for each channel. ''' return islice(izip(*(imap(sum, izip(*channel)) for channel in channels)),...
java
protected String encrypt(String randomStr, String plainText) { ByteGroup byteCollector = new ByteGroup(); byte[] randomStringBytes = randomStr.getBytes(CHARSET); byte[] plainTextBytes = plainText.getBytes(CHARSET); byte[] bytesOfSizeInNetworkOrder = number2BytesInNetworkOrder(plainTextBytes.length);...
python
def task_property_present_predicate(service, task, prop): """ True if the json_element passed is present for the task specified. """ try: response = get_service_task(service, task) except Exception as e: pass return (response is not None) and (prop in response)
java
JsMsgPart getPart(int accessor, JMFSchema schema) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getPart", new Object[]{accessor, schema}); JsMsgPart result = null; try { if (jmfPart.isPresent(accessor)) result = new JsMsgPart(jmfPart.getNativePart(ac...
python
def walk(self): """Walk over the message tree, yielding each subpart. The walk is performed in depth-first order. This method is a generator. """ yield self if self.is_multipart(): for subpart in self.get_payload(): for subsubpart in subpart.walk(): yield su...
python
def get_configs(self): """ :return: overall index, agent config, loadout config in that order """ loadout_config = self.loadout_preset.config.copy() config_path = None if self.agent_preset.config_path is not None: # Might be none if preset was never saved to disk. ...
python
def read_file(file_path, default_content=''): """ Read file at the specified path. If file doesn't exist, it will be created with default-content. Returns the file content. """ if not os.path.exists(file_path): write_file(file_path, default_content) handler = open(file_path, 'r') ...
java
@Override public void tryUnchecked(ActionToTry<E> action) { tryUnchecked(noParam -> { action.execute(); return null; }, null); }
python
def locations_for(self, city_name, country=None, matching='nocase'): """ Returns a list of Location objects corresponding to the int IDs and relative toponyms and 2-chars country of the cities matching the provided city name. The rule for identifying matchings is according to the...
java
public static base_response update(nitro_service client, clusternodegroup resource) throws Exception { clusternodegroup updateresource = new clusternodegroup(); updateresource.name = resource.name; updateresource.strict = resource.strict; return updateresource.update_resource(client); }
python
def read_file(self, infile): """Read a reST file into a string. """ try: with open(infile, 'rt') as file: return file.read() except UnicodeDecodeError as e: err_exit('Error reading %s: %s' % (infile, e)) except (IOError, OSError) as e: ...
python
def read_from(value): """Read file and return contents.""" path = normalized_path(value) if not os.path.exists(path): raise argparse.ArgumentTypeError("%s is not a valid path." % path) LOG.debug("%s exists.", path) with open(path, 'r') as reader: read = reader.read() return read
python
def auto_type(s): """ Get a XML response and tries to convert it to Python base object """ if isinstance(s, bool): return s elif s is None: return '' elif s == 'TRUE': return True elif s == 'FALSE': return False else: try: try: ...
python
def get_last_components_by_type(component_types, topic_id, db_conn=None): """For each component type of a topic, get the last one.""" db_conn = db_conn or flask.g.db_conn schedule_components_ids = [] for ct in component_types: where_clause = sql.and_(models.COMPONENTS.c.type == ct, ...
java
public String[] getContext(int i, String[] toks, String[] tags, String[] preds) { List<String> e = new ArrayList<String>(); if(isWiderContext) createWindowFeats(i, toks, tags, preds, e); else create3WindowFeats(i, toks, tags, preds, e); if(i > 0) wrappWindowFeatures("prev_", i-1...
java
@Override public String getDataQuery(QueryFilter filter) { String query = getQuery(); String whereClause = filter.getWhereClause(); String result = null; if (whereClause != null && whereClause.length() > 0) { result = query.replaceAll(SUBSTITUTION_STRING, " AND " + whereC...
python
def _get_content(self, response): """Checks for errors in the response. Returns response content, in bytes. :param response: response object :raise: :UnexpectedResponse: if the server responded with an unexpected response :return: - ServiceNow response content ...
python
def _prepare_inputs(self, X, y=None, type_of_inputs='classic', **kwargs): """Initializes the preprocessor and processes inputs. See `check_input` for more details. Parameters ---------- input: array-like The input data array to check. y : array-like The input ...
java
@Override public DescribeFleetUtilizationResult describeFleetUtilization(DescribeFleetUtilizationRequest request) { request = beforeClientExecution(request); return executeDescribeFleetUtilization(request); }
java
public T get(final ProcessCase processCase) { if(!isPresent(processCase)) { throw new NoSuchElementException(String.format("No value present in processCase '%s'.", processCase.name())); } return value.get(); }
python
def query_term(self, term, verbose=False): """Given a GO ID, return GO object.""" if term not in self: sys.stderr.write("Term %s not found!\n" % term) return rec = self[term] if verbose: print(rec) sys.stderr.write("all parents: {}\n".form...
python
def _chk_truncate(self): ''' Checks whether the frame should be truncated. If so, slices the frame up. ''' # Column of which first element is used to determine width of a dot col self.tr_size_col = -1 # Cut the data to the information actually printed ma...
java
public static <J extends Job<J,R>, R extends Run<J,R>> RunList<R> fromJobs(Iterable<? extends J> jobs) { List<Iterable<R>> runLists = new ArrayList<>(); for (Job j : jobs) runLists.add(j.getBuilds()); return new RunList<>(combine(runLists)); }
java
@SuppressWarnings("static-method") public List<Integer> findIntValues(JvmAnnotationReference reference) { assert reference != null; final List<Integer> values = new ArrayList<>(); for (final JvmAnnotationValue value : reference.getValues()) { if (value instanceof JvmIntAnnotationValue) { for (final Intege...
python
def sidereal_time(t): """Compute Greenwich sidereal time at the given ``Time``.""" # Compute the Earth Rotation Angle. Time argument is UT1. theta = earth_rotation_angle(t.ut1) # The equinox method. See Circular 179, Section 2.6.2. # Precession-in-RA terms in mean sidereal time taken from third...
java
private boolean checkChecksumISBN10(final String isbn) { int sum = 0; for (int i = 0; i < isbn.length() - 1; i++) { sum += (isbn.charAt(i) - '0') * (i + 1); } final char checkSum = isbn.charAt(9); return sum % 11 == (checkSum == 'X' ? 10 : checkSum - '0'); }