language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private byte transitionToNextToken(boolean lastChunk) { int endNextToken = findNextChar(responseContent, ':'); if (endNextToken < 0 && !lastChunk) { return queryParsingState; } if (endNextToken < 0 && lastChunk && queryParsingState >= QUERY_STATE_STATUS) { return...
java
public CloudhopperBuilder bindType(String... bindType) { for (String b : bindType) { if (b != null) { bindTypes.add(b); } } return this; }
python
def subsample_indexes(data, n_samples=1000, size=0.5): """ Given data points data, where axis 0 is considered to delineate points, return a list of arrays where each array is indexes a subsample of the data of size ``size``. If size is >= 1, then it will be taken to be an absolute size. If size < 1, it will be take...
python
async def query_available_abilities( self, units: Union[List[Unit], "Units"], ignore_resource_requirements: bool = False ) -> List[List[AbilityId]]: """ Query abilities of multiple units """ if not isinstance(units, list): """ Deprecated, accepting a single unit may be removed in...
python
def detect_loud_glitches(strain, psd_duration=4., psd_stride=2., psd_avg_method='median', low_freq_cutoff=30., threshold=50., cluster_window=5., corrupt_time=4., high_freq_cutoff=None, output_intermediates=False): """Automatic identification...
java
public static <S1, I, T1, S2, T2, SP2, TP2> Mapping<S1, S2> rawCopy(TSTraversalMethod method, TransitionSystem<S1, ? super I, T1> in, int limit, ...
python
def do_int(value, default=0, base=10): """Convert the value into an integer. If the conversion doesn't work it will return ``0``. You can override this default using the first parameter. You can also override the default base (10) in the second parameter, which handles input with prefixes such as ...
python
def from_string(string): """ Reads a Kpoints object from a KPOINTS string. Args: string (str): KPOINTS string. Returns: Kpoints object """ lines = [line.strip() for line in string.splitlines()] comment = lines[0] num_kpts = int(l...
java
public static Condition textCaseSensitive(final String text) { return new Condition("textCaseSensitive") { @Override public boolean apply(Driver driver, WebElement element) { return Html.text.containsCaseSensitive(element.getText(), text); } @Override public String toString() ...
java
public static void writeUTF8WithLength(OutputStream out, String str) throws IOException { byte[] s = str.getBytes(UTF8); writeInt4(out, s.length); out.write(s); }
java
public void init(Object parent, Object obj) { super.init(parent, obj); /** Create the JTreeModel. */ BaseApplet applet = (BaseApplet)obj; RemoteSession parentSessionObject = null;//?this.getTourCalendarScreen().getRemoteSession(); RemoteSession remoteSession = applet.makeRemo...
python
def set_split_extents(self): """ Sets split extents (:attr:`split_begs` and :attr:`split_ends`) calculated using selected attributes set from :meth:`__init__`. """ self.check_split_parameters() self.update_tile_extent_bounds() if self.indices_per_axis is...
java
public HierarchicalProperty getProperty(String name) throws RepositoryException { if ("jcr:primaryType".equals(name) || "jcr:mixinTypes".equals(name)) return null; if (content == null) return null; if (content.getProperty(name) != null) { return content.getPropert...
python
def _subscribed(self): """ Called when the subscription was accepted successfully. """ self.logger.debug('Subscription confirmed.') self.state = 'subscribed' for message in self.message_queue: self.send(message)
java
@Override public URL getFromRulesDirAsUrl(String path) { String completePath = getCompleteRulesUrl(path); URL resource = ResourceDataBroker.class.getResource(completePath); assertNotNull(resource, path, completePath); return resource; }
java
private static Collection<Class> scanEntityClasses(String... persistenceXmlFiles) { DDLGenerator.Profile profile = new DDLGenerator.Profile(null); profile.addPersistenceFile(persistenceXmlFiles); return profile.getEntityClasses(); }
python
def local_independencies(self, variables): """ Returns an instance of Independencies containing the local independencies of each of the variables. Parameters ---------- variables: str or array like variables whose local independencies are to found. ...
java
public void putString(String value) { if (value.length() > Byte.MAX_VALUE * 2 + 1) { putLongString(value); } else { putShortString(value); } }
python
def cdrom_image(self, cdrom_image): """ Sets the cdrom image for this QEMU VM. :param cdrom_image: QEMU cdrom image path """ self._cdrom_image = self.manager.get_abs_image_path(cdrom_image) log.info('QEMU VM "{name}" [{id}] has set the QEMU cdrom image path to {cdrom_ima...
python
def demo_args(self): """ Additional method for replacing input arguments by demo ones. """ argv = random.choice(self.examples).replace("--demo", "") self._reparse_args['pos'] = shlex.split(argv)
java
public static Set<String> listAllLinks(OperationContext context, String overlay) { Set<String> serverGoupNames = listServerGroupsReferencingOverlay(context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS), overlay); Set<String> links = new HashSet<>(); for (String serverGoupName : serverGoupNames...
java
public DateTimeFormatterBuilder append(DateTimeFormatter formatter) { if (formatter == null) { throw new IllegalArgumentException("No formatter supplied"); } return append0(formatter.getPrinter0(), formatter.getParser0()); }
java
@Override public File getPermanentDirectory() { // Note: We're initializing the permanent directory here instead of in an Initializable.initialize() method // since otherwise we get a cyclic dependency with the Configuration Source implementation used to get the // Environment configurat...
python
def _InitApiApprovalFromAff4Object(api_approval, approval_obj): """Initializes Api(Client|Hunt|CronJob)Approval from an AFF4 object.""" api_approval.id = approval_obj.urn.Basename() api_approval.reason = approval_obj.Get(approval_obj.Schema.REASON) api_approval.requestor = approval_obj.Get(approval_obj.Schema....
python
def log_data_send(self, id, ofs, count, data, force_mavlink1=False): ''' Reply to LOG_REQUEST_DATA id : Log id (from LOG_ENTRY reply) (uint16_t) ofs : Offset into the log (uint32_t) count ...
python
def controller(self, *paths, **query_kwargs): """create a new url object using the controller path as a base if you have a controller `foo.BarController` then this would create a new Url instance with `host/foo/bar` as the base path, so any *paths will be appended to `/foo/bar` ...
java
public SingleOutputStreamOperator<T> assignTimestampsAndWatermarks( AssignerWithPunctuatedWatermarks<T> timestampAndWatermarkAssigner) { // match parallelism to input, otherwise dop=1 sources could lead to some strange // behaviour: the watermark will creep along very slowly because the elements // from the s...
java
public static void setDefault(ProxySelector ps) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { // sm.checkPermission(SecurityConstants.SET_PROXYSELECTOR_PERMISSION); } theProxySelector = ps; }
java
private <T extends IEntity> String prepareQBOUri(String entityName, Context context, Map<String, String> requestParameters) throws FMSException { StringBuilder uri = new StringBuilder(); if(entityName.equalsIgnoreCase("Taxservice")) { entityName = entityName + "/" + "taxcode"; } // constructs...
python
def get_instance(self, payload): """ Build an instance of ThisMonthInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMon...
python
def get_request_data(self, var_name, full_data=False): """ :param var_name: :param full_data: If you want `.to_array()` with this data, ready to be sent. :return: A tuple of `to_array()` dict and the files (:py:func:`InputFile.get_request_files()`). Files can be None, if...
java
public BDDUBASE createBDDUBASEFromString(EDataType eDataType, String initialValue) { BDDUBASE result = BDDUBASE.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'"); return result; }
python
def get_item_metric_pair(item_lst, metric_lst, id_lst): """ align bleu and specific score in item_lst, reconstruct the data as (rank_score, bleu) pairs, query_dic. Detail: query dict is input parameter used by metrics: top-x-bleu, kendall-tau query dict is reconstructed dict type data c...
java
@Override public void setMaxHostConnections(int maxHostConnections) { connectionManager.getParams().setDefaultMaxConnectionsPerHost(maxHostConnections); connectionManager.getParams().setMaxConnectionsPerHost(hostConfiguration, maxHostConnections); }
python
def generate_repr(*members): """ Decorator that binds an auto-generated ``__repr__()`` function to a class. The generated ``__repr__()`` function prints in following format: <ClassName object(field1=1, field2='A string', field3=[1, 2, 3]) at 0xAAAA> Note that this decorator modifies the given clas...
python
def solve_step(self): """Perform a single solve step. """ self.solve_begun = True if self.status != SolverStatus.unsolved: return if self.pr: self.pr.header("SOLVE #%d (%d fails so far)...", self.solve_count + 1, self.num_fails)...
python
def create(cls, name, protocol_number, protocol_agent=None, comment=None): """ Create the IP Service :param str name: name of ip-service :param int protocol_number: ip proto number for this service :param str,ProtocolAgent protocol_agent: optional protocol agent for ...
python
def _check_if_tag_already_exists(self): """Check if tag already exists and show the difference if so""" version = self.data['new_version'] if self.vcs.tag_exists(version): return True else: return False
java
public Account getAccountForInputText(String inputText) { if ( selectedProfile != null ) return selectedProfile; Account account = pwmProfiles.findAccountByUrl(inputText); if ( account == null ) return getDefaultAccount(); return account; }
python
def validate(instance, schema, cls=None, *args, **kwargs): """ Validate an instance under the given schema. >>> validate([2, 3, 4], {"maxItems": 2}) Traceback (most recent call last): ... ValidationError: [2, 3, 4] is too long :func:`validate` will first verify that the...
python
def logger_add (self, loggerclass): """Add a new logger type to the known loggers.""" self.loggers[loggerclass.LoggerName] = loggerclass self[loggerclass.LoggerName] = {}
java
@Override public void setContext(DisplayContext context) { super.setContext(context); if (!capitalizationInfoIsSet && (context==DisplayContext.CAPITALIZATION_FOR_UI_LIST_OR_MENU || context==DisplayContext.CAPITALIZATION_FOR_STANDALONE)) { initCapitalizationContextInfo(local...
python
def ShowUnspentCoins(wallet, asset_id=None, from_addr=None, watch_only=False, do_count=False): """ Show unspent coin objects in the wallet. Args: wallet (neo.Wallet): wallet to show unspent coins from. asset_id (UInt256): a bytearray (len 32) representing an asset on the blockchain. ...
python
async def _storeAppt(self, appt): ''' Store a single appointment ''' await self._hivedict.set(appt.iden, appt.pack())
python
def get_message(cls, signals=True, farms=False, buffer_size=65536, timeout=-1): """Block until a mule message is received and return it. This can be called from multiple threads in the same programmed mule. :param bool signals: Whether to manage signals. :param bool farms: Whether to ...
python
def multiply(a, col): """Multiply a matrix by one column.""" a = a.reshape(4, 4, 4) col = col.reshape(4, 8) return fcat( rowxcol(a[0], col), rowxcol(a[1], col), rowxcol(a[2], col), rowxcol(a[3], col), )
python
def get_first_mapping(cls): """This allows for Django-like inheritance of mapping configurations""" from .models import Indexable if issubclass(cls, Indexable) and hasattr(cls, "Mapping"): return cls.Mapping for base in cls.__bases__: mapping = get_first_mapping(base) if mapping...
python
def rpc_get_consensus_at( self, block_id, **con_info ): """ Return the consensus hash at a block number. Return {'status': True, 'consensus': ...} on success Return {'error': ...} on error """ if not check_block(block_id): return {'error': 'Invalid block heigh...
java
public static String getDesc(final CtMethod m) throws NotFoundException { StringBuilder ret = new StringBuilder(m.getName()).append('('); CtClass[] parameterTypes = m.getParameterTypes(); for (int i = 0; i < parameterTypes.length; i++) ret.append(getDesc(parameterTypes[i])); ret.append(')').append(getDesc(m....
python
def html_result(html: str, extraheaders: TYPE_WSGI_RESPONSE_HEADERS = None) \ -> WSGI_TUPLE_TYPE: """ Returns ``(contenttype, extraheaders, data)`` tuple for UTF-8 HTML. """ extraheaders = extraheaders or [] return 'text/html; charset=utf-8', extraheaders, html.encode("utf-8"...
python
def ns(ns): """Class decorator that sets default tags namespace to use with its instances.""" def setup_ns(cls): setattr(cls, ENTITY_DEFAULT_NS_ATTR, ns) return cls return setup_ns
python
def update_invoice(self, invoice_id, invoice_dict): """ Updates an invoice :param invoice_id: the invoice id :param invoice_dict: dict :return: dict """ return self._create_put_request(resource=INVOICES, billomat_id=invoice_id, send_data=invoice_dict)
java
@SuppressWarnings("unchecked") @Override public PairSet<T, I> convert(Collection<?> c) { if (c == null) return empty(); // useless to convert... if (hasSameIndices(c)) return (PairSet<T, I>) c; // convert PairSet<T, I> res = empty(); for (Pair<T, I> p : (Collection<Pair<T,I>>) c) r...
python
def start_serving(self, delegate: httputil.HTTPServerConnectionDelegate) -> None: """Starts serving requests on this connection. :arg delegate: a `.HTTPServerConnectionDelegate` """ assert isinstance(delegate, httputil.HTTPServerConnectionDelegate) fut = gen.convert_yielded(self...
java
public VerifyDKIMResponse verifyDKIM(VerifyDKIMRequest request) { checkNotNull(request, "object request should not be null."); assertStringNotNullOrEmpty(request.getDomainName(), "object domainName should not be null or empty"); InternalRequest internalRequest = this.createReque...
python
def log_status (self): """Log a status message.""" duration = time.time() - self.start_time checked, in_progress, queue = self.aggregator.urlqueue.status() num_urls = len(self.aggregator.result_cache) self.logger.log_status(checked, in_progress, queue, duration, num_urls)
java
public void setConnectionNotificationIds(java.util.Collection<String> connectionNotificationIds) { if (connectionNotificationIds == null) { this.connectionNotificationIds = null; return; } this.connectionNotificationIds = new com.amazonaws.internal.SdkInternalList<String...
java
private void drawTexts(Canvas canvas, float textSize, Typeface typeface, String[] texts, float[] textGridWidths, float[] textGridHeights) { mPaint.setTextSize(textSize); mPaint.setTypeface(typeface); Paint[] textPaints = assignTextColors(texts); canvas.drawText(texts[0], text...
java
@Override public Request<DescribeAvailabilityZonesRequest> getDryRunRequest() { Request<DescribeAvailabilityZonesRequest> request = new DescribeAvailabilityZonesRequestMarshaller().marshall(this); request.addParameter("DryRun", Boolean.toString(true)); return request; }
python
def get_handler(self, *args, **options): """ Returns the django.contrib.staticfiles handler. """ handler = WSGIHandler() try: from django.contrib.staticfiles.handlers import StaticFilesHandler except ImportError: return handler use_static_h...
python
def update(self, v): """Adds point v""" self.t += 1 g = self.gamma() self.mu = (1. - g) * self.mu + g * v mv = v - self.mu self.Sigma = ((1. - g) * self.Sigma + g * np.dot(mv[:, np.newaxis], mv[np.newaxis, :])) try: self.L = chole...
java
public Observable<ServiceResponse<Page<P2SVpnServerConfigurationInner>>> listByVirtualWanWithServiceResponseAsync(final String resourceGroupName, final String virtualWanName) { return listByVirtualWanSinglePageAsync(resourceGroupName, virtualWanName) .concatMap(new Func1<ServiceResponse<Page<P2SVpnS...
java
static JbcSrcJavaValue of(Expression expr, JbcSrcValueErrorReporter reporter) { if (expr instanceof SoyExpression) { return new JbcSrcJavaValue( expr, /* method= */ null, /* allowedType= */ ((SoyExpression) expr).soyType(), /* constantNull= */ false, /* error=...
java
public void computeH( DMatrixRMaj H ) { H.reshape(4,4); CommonOps_DDRM.insert(PA,H,0,0); for (int i = 0; i < 4; i++) { H.unsafe_set(i,3,ns.data[i]); } }
java
public static <K, V> EntryStream<K, V> of(Spliterator<? extends Entry<K, V>> spliterator) { return of(StreamSupport.stream(spliterator, false)); }
python
def get_confirmed_blockhash(self): """ Gets the block CONFIRMATION_BLOCKS in the past and returns its block hash """ confirmed_block_number = self.web3.eth.blockNumber - self.default_block_num_confirmations if confirmed_block_number < 0: confirmed_block_number = 0 return sel...
java
private boolean matchesNode(Node template, Node ast) { if (isTemplateParameterNode(template)) { int paramIndex = (int) (template.getDouble()); Node previousMatch = paramNodeMatches.get(paramIndex); if (previousMatch != null) { // If this named node has already been matched against, make su...
java
public void updateWeightAndPrune(float[] dataRow, int modelIndex, int ng, int bestIndex, float bestWeight) { int index = modelIndex; float weightTotal = 0; for (int i = 0; i < ng; ) { float weight = dataRow[index]; // if( ng > 1 ) // System.out.println("["+i+"] = "+ng+" weight "+weight); weight = wei...
java
public boolean extend(SpatialComparable obj) { final int dim = min.length; assert (obj.getDimensionality() == dim); boolean extended = false; for(int i = 0; i < dim; i++) { final double omin = obj.getMin(i); final double omax = obj.getMax(i); if(omin < min[i]) { min[i] = omin; ...
python
def fnr(y, z): """False negative rate `fn / (fn + tp)` """ tp, tn, fp, fn = contingency_table(y, z) return fn / (fn + tp)
java
public void updateIntModel(AjaxBehaviorEvent event) { intModel.setValue(intModel.getValue() + UPDATE_INT_VALUE); eduContext.update("int-model-changed"); }
python
def _spectrum(self, photon_energy): """Compute differential bremsstrahlung spectrum for energies in ``photon_energy``. Parameters ---------- photon_energy : :class:`~astropy.units.Quantity` instance Photon energy array. """ Eph = _validate_ene(photon...
python
def _knit(fin, fout, opts_knit='progress=FALSE, verbose=FALSE', opts_chunk='eval=FALSE'): """Use knitr to convert r markdown (or anything knitr supports) to markdown. fin / fout - strings, input / output filenames. opts_knit - string, options to pass to knit ...
python
def get_openmp_flags(): """ Utility for returning compiler and linker flags possibly needed for OpenMP support. Returns ------- result : `{'compiler_flags':<flags>, 'linker_flags':<flags>}` Notes ----- The flags returned are not tested for validity, use `check_openmp_support(op...
python
def save(self): """Save the state to the JSON file in the config dir.""" logger.debug("Save the GUI state to `%s`.", self.path) _save_json(self.path, {k: v for k, v in self.items() if k not in ('config_dir', 'name')})
python
def shape(self): """Total spaces per axis, computed recursively. The recursion ends at the fist level that does not have a shape. Examples -------- >>> r2, r3 = odl.rn(2), odl.rn(3) >>> pspace = odl.ProductSpace(r2, r3) >>> pspace.shape (2,) >>> ...
python
def update(self, properties=None): # pylint: disable=W0212 """ If called without properties, only notifies listeners Update the properties of this Configuration object. Stores the properties in persistent storage after adding or overwriting the following properties: ...
python
def generate_overlapping_psds(opt, gwstrain, flen, delta_f, flow, dyn_range_factor=1., precision=None): """Generate a set of overlapping PSDs to cover a stretch of data. This allows one to analyse a long stretch of data with PSD measurements that change with time. Paramete...
java
public void execute( TransformerImpl transformer) throws TransformerException { try { // Note the content model is: // <!ENTITY % instructions " // %char-instructions; // | xsl:processing-instruction // | xsl:comment // | xsl:element // | xsl:att...
python
def deferred_emails(): """Checks for deferred email, that otherwise fill up the queue.""" status = SERVER_STATUS['OK'] count = Message.objects.deferred().count() if DEFERRED_WARNING_THRESHOLD <= count < DEFERRED_DANGER_THRESHOLD: status = SERVER_STATUS['WARNING'] if count >= DEFERRED_DANGER...
python
def resolver(self): """ Resolver for JSON Schema references. This can be based around a file or HTTP-based resolution base URI. """ if self._resolver is None: self._resolver = RefResolver(self.base_uri, {}) # if self.base_uri not in self._resolver.store: # self._re...
java
public static void removeInputMap(Node node, InputMap<?> im) { // getInputMap calls init, so can use unsafe setter setInputMapUnsafe(node, getInputMap(node).without(im)); }
java
public void info( Object messagePattern, Object arg ) { if( m_delegate.isInfoEnabled() ) { String msgStr = (String) messagePattern; msgStr = MessageFormatter.format( msgStr, arg ); m_delegate.inform( msgStr, null ); } }
java
public static void sqlspace(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException { singleArgumentFunctionCall(buf, "repeat(' ',", "space", parsedArgs); }
python
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return ECDSA_Curve(key) if key not in ECDSA_Curve._member_map_: extend_enum(ECDSA_Curve, key, default) return ECDSA_Curve[key]
java
public long deleteAll(final QueryableCriteria criteria) { return getHibernateTemplate().execute((GrailsHibernateTemplate.HibernateCallback<Integer>) session -> { JpaQueryBuilder builder = new JpaQueryBuilder(criteria); builder.setConversionService(getMappingContext().getConversionService...
java
private void convertAsyncGenerator(NodeTraversal t, Node originalFunction) { checkNotNull(originalFunction); checkState(originalFunction.isAsyncGeneratorFunction()); Node asyncGeneratorWrapperRef = astFactory.createAsyncGeneratorWrapperReference(originalFunction.getJSType(), t.getScope()); Node...
java
public String format(Map<?, ?> map, char keyValueSeparator) { if (map == null) { return StringUtils.EMPTY; } Preconditions.checkArgument(keyValueSeparator != ' '); StringBuilder rowString = new StringBuilder(); for (Iterator<?> itr = map.entrySet().iterator(); itr.hasNext(); ) { Map.Ent...
python
def solve_recaptcha(self, google_key, page_url, timeout = 15 * 60): ''' Solve a recaptcha on page `page_url` with the input value `google_key`. Timeout is `timeout` seconds, defaulting to 60 seconds. Return value is either the `g-recaptcha-response` value, or an exceptionj is raised (generally `CaptchaSolver...
python
def attach_import_node(node, modname, membername): """create a ImportFrom node and register it in the locals of the given node with the specified name """ from_node = nodes.ImportFrom(modname, [(membername, None)]) _attach_local_node(node, from_node, membername)
python
def create_csr(ca_name, bits=2048, CN='localhost', C='US', ST='Utah', L='Salt Lake City', O='SaltStack', OU=None, emailAddress=None, subjectAltName=None, cacert_path=None...
python
def parse(self, stream, mimetype, content_length, options=None): """Parses the information from the given stream, mimetype, content length and mimetype parameters. :param stream: an input stream :param mimetype: the mimetype of the data :param content_length: the content length ...
java
protected void reset() { fields[LANGUAGE] = null; fields[SCRIPT] = null; fields[TERRITORY] = null; fields[VARIANT] = null; }
python
def ximplotxy(x, y, fmt=None, plottype=None, xlim=None, ylim=None, xlabel=None, ylabel=None, title=None, show=True, geometry=(0, 0, 640, 480), tight_layout=True, debugplot=0, using_jupyter=False, **kwargs): """ Parameters ---------- ...
python
def get_tree_members(self): """ Retrieves all members from this node of the tree down.""" members = [] queue = deque() queue.appendleft(self) visited = set() while len(queue): node = queue.popleft() if node not in visited: ...
java
@Override public String getName(String languageId, boolean useDefault) { return _cpMeasurementUnit.getName(languageId, useDefault); }
python
def start_review(self): """Mark our review as started.""" if self.set_status: self.github_repo.create_status( state="pending", description="Static analysis in progress.", context="inline-plz", sha=self.last_sha, )
python
def response_continue(self): """ Signals that a partial reception of data has occurred and that the exporter should continue to send data for this entity. This should also be used if import-side caching has missed, in which case the response will direct the exporter to re-send the full d...
python
def add_files_to_git_repository(base_dir, files, description): """ Add and commit all files given in a list into a git repository in the base_dir directory. Nothing is done if the git repository has local changes. @param files: the files to commit @param description: the commit message """ ...
python
def parse_motion_state(val): """Convert motion state byte to seconds.""" number = val & 0b00111111 unit = (val & 0b11000000) >> 6 if unit == 1: number *= 60 # minutes elif unit == 2: number *= 60 * 60 # hours elif unit == 3 and number < 32: ...