language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
private Animator preparePulseAnimation() { AnimatorSet animation = new AnimatorSet(); Animator firstBounce = ObjectAnimator.ofFloat(drawable, CircularProgressDrawable.CIRCLE_SCALE_PROPERTY, drawable.getCircleScale(), 0.88f); firstBounce.setDuration(300); firstBounce.setI...
java
public static int validatePortNumber(String portStringValue) { final int portNumber; final StringBuilder exceptionMessageBuilder = new StringBuilder(); exceptionMessageBuilder.append("Invalid value '").append(portStringValue) .append("' for input '").append(HttpClientInputs.PROXY...
python
def read1(self, n): """Read up to n bytes with at most one read() system call.""" # Simplify algorithm (branching) by transforming negative n to large n. if n < 0 or n is None: n = self.MAX_N # Bytes available in read buffer. len_readbuffer = len(self._readbuffer) -...
python
def _determine_base_url(document, page_url): """Determine the HTML document's base URL. This looks for a ``<base>`` tag in the HTML document. If present, its href attribute denotes the base URL of anchor tags in the document. If there is no such tag (or if it does not have a valid href attribute), the ...
java
public Observable<ServiceResponse<JobResponseInner>> getJobWithServiceResponseAsync(String resourceGroupName, String resourceName, String jobId) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");...
java
public void process(final Node aNode) { // Only attributes are permitted here. Attr attribute = (Attr) aNode; // Change the fileName. String newFilename = namespaceUriToNewFilenameMap.get(getNamespace(attribute)); attribute.setValue(newFilename); }
python
def crypto_box_open_afternm(ciphertext, nonce, k): """ Decrypts and returns the encrypted message ``ciphertext``, using the shared key ``k`` and the nonce ``nonce``. :param ciphertext: bytes :param nonce: bytes :param k: bytes :rtype: bytes """ if len(nonce) != crypto_box_NONCEBYTES...
java
public int parseArgument(Options opt, String[] args, int start) throws BadCommandLineException, IOException { int consumed = 0; final String optionPrefix = "-" + getOptionName() + "-"; final int optionPrefixLength = optionPrefix.length(); final String arg = args[start]; final int equalsPosition = arg.ind...
python
def strip_msa_100(msa, threshold, plot = False): """ strip out columns of a MSA that represent gaps for X percent (threshold) of sequences """ msa = [seq for seq in parse_fasta(msa)] columns = [[0, 0] for pos in msa[0][1]] # [[#bases, #gaps], [#bases, #gaps], ...] for seq in msa: for position, base in enumerate...
python
def get_resource(self, resource_id): """Gets the ``Resource`` specified by its ``Id``. In plenary mode, the exact ``Id`` is found or a ``NotFound`` results. Otherwise, the returned ``Resource`` may have a different ``Id`` than requested, such as the case where a duplicate ``Id``...
python
def fprob(dfnum, dfden, F): """ Returns the (1-tailed) significance level (p-value) of an F statistic given the degrees of freedom for the numerator (dfR-dfF) and the degrees of freedom for the denominator (dfF). Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn """ p = betai(0.5 * dfden,...
python
def loader(self, file_name, bad_steps=None, **kwargs): """Loads data from biologics .mpr files. Args: file_name (str): path to .res file. bad_steps (list of tuples): (c, s) tuples of steps s (in cycle c) to skip loading. Returns: new_tests (list...
java
public final void commitPersistLock(PersistentTransaction transaction) throws SevereMessageStoreException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "commitPersistLock", transaction); AbstractItem item = null; boolean hasBecomePersis...
python
def normalize_mask(mask, is_micro): """\ Normalizes the (user specified) mask. :param mask: A mask constant :type mask: int or None :param bool is_micro: Indicates if the mask is meant to be used for a Micro QR Code. """ if mask is None: return None try: mask...
python
def check_command(self, command): """ Check if command can be called. """ # Use `command` to see if command is callable, store exit code code = os.system("command -v {0} >/dev/null 2>&1 || {{ exit 1; }}".format(command)) # If exit code is not 0, report which command fai...
python
def generate_uncertainties(N, dist='Gamma', rseed=None): """ This function generates a uncertainties for the white noise component in the synthetic light curve. Parameters --------- N: positive integer Lenght of the returned uncertainty vector dist: {'EMG', 'Gamma'} Pro...
java
public static String getUniqueId() { char[] data = new char[36]; long l0 = System.currentTimeMillis(); UUID uuid = UUID.randomUUID(); long l1 = uuid.getMostSignificantBits(); long l2 = uuid.getLeastSignificantBits(); //we don't use Long.toString(long, radix) becaus...
java
@Override public void setObserver(HttpOutputStreamObserver obs) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "obs ->" + obs); } this.obs = obs; }
python
def _read_csv_with_offset_pyarrow_on_ray( fname, num_splits, start, end, kwargs, header ): # pragma: no cover """Use a Ray task to read a chunk of a CSV into a pyarrow Table. Note: Ray functions are not detected by codecov (thus pragma: no cover) Args: fname: The filename of the file to open....
java
public static Thread consumeProcessOutputStream(Process self, Appendable output) { Thread thread = new Thread(new TextDumper(self.getInputStream(), output)); thread.start(); return thread; }
java
public void setResult(R result) { try { lock.lock(); this.result = result; notifyHaveResult(); } finally { lock.unlock(); } }
python
def register_patches(self): """ Registers the patches. :return: Method success. :rtype: bool """ if not self.__paths: return False unregistered_patches = [] for path in self.paths: for file in foundations.walkers.files_walker(pat...
java
public ScoreNode nextScoreNode() throws IOException { while (childHits != null) { ScoreNode sn = childHits.nextScoreNode(); if (sn != null) { return sn; } else { fetchNextChildHits(); } } // if we get here there are ...
java
void fireEntryLeave(AsteriskQueueEntryImpl entry) { synchronized (listeners) { for (AsteriskQueueListener listener : listeners) { try { listener.onEntryLeave(entry); } catch (Exception e) ...
python
def parse_pagination(headers): """ Parses headers to create a pagination objects :param headers: HTTP Headers :type headers: dict :return: Navigation object for pagination :rtype: _Navigation """ links = { link.rel: parse_qs(link.href).get("page", None) for link in link_head...
python
def get_email_regex(self): """ Return a regex pattern matching valid email addresses. Uses the same logic as the django validator, with the folowing exceptions: - Internationalized domain names not supported - IP addresses not supported - Strips lookbehinds (not supporte...
java
@Override public int countByG_E(long groupId, String engineKey) { FinderPath finderPath = FINDER_PATH_COUNT_BY_G_E; Object[] finderArgs = new Object[] { groupId, engineKey }; Long count = (Long)finderCache.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundl...
java
public String convertServiceSimpleTypeToString(EDataType eDataType, Object instanceValue) { return instanceValue == null ? null : instanceValue.toString(); }
java
public int rank(Type t) { t = t.unannotatedType(); switch(t.getTag()) { case CLASS: { ClassType cls = (ClassType)t; if (cls.rank_field < 0) { Name fullname = cls.tsym.getQualifiedName(); if (fullname == names.java_lang_Object) ...
java
void checkInternalConsistency() throws IllegalStateException { if (encryptionKey == null) { throw new IllegalStateException("Missing encryption key"); } switch (state) { case LOGGED_IN: if (StringUtils.isNullOrEmpty(userId)) { throw new IllegalStateException("Missing user id"); } break; ...
java
public DoubleProperty arcHeightProperty() { if (this.arcHeight == null) { this.arcHeight = new DependentSimpleDoubleProperty<ReadOnlyDoubleProperty>( this, MathFXAttributeNames.ARC_HEIGHT, heightProperty()) { @Override protected void invalidated(ReadOnlyDoubleProperty dependency) { final double v...
java
public static InstanceTypeDescription construct(InstanceType instanceType, HardwareDescription hardwareDescription, int numberOfAvailableInstances) { return new InstanceTypeDescription(instanceType, hardwareDescription, numberOfAvailableInstances); }
python
def format(self, altitude=None, deg_char='', min_char='m', sec_char='s'): """ Format decimal degrees (DD) to degrees minutes seconds (DMS) """ latitude = "%s %s" % ( format_degrees(abs(self.latitude), symbols={ 'deg': deg_char, 'arcmin': min_char, 'arcsec': se...
java
@BetaApi public final Operation removeHealthCheckTargetPool( String targetPool, TargetPoolsRemoveHealthCheckRequest targetPoolsRemoveHealthCheckRequestResource) { RemoveHealthCheckTargetPoolHttpRequest request = RemoveHealthCheckTargetPoolHttpRequest.newBuilder() .setTargetPool(ta...
python
def create_executable_script(filepath, body, program=None): """Create an executable script. Args: filepath (str): File to create. body (str or callable): Contents of the script. If a callable, its code is used as the script body. program (str): Name of program to launch the ...
java
public AttributeValue getAttributeValueObject_2() throws DevFailed { // Build a DeviceAttribute_3 from this final DeviceAttribute_3DAODefaultImpl att = new DeviceAttribute_3DAODefaultImpl(); att.setAttributeValue(this); return att.getAttributeValueObject_2(); }
java
protected static void assertArgumentNotNull(String variableName, Object value) { if (variableName == null) { String msg = "The value should not be null: variableName=null value=" + value; throw new IllegalArgumentException(msg); } if (value == null) { String m...
java
public static ShopGetResult shopGet(String accessToken, ShopInfo shopInfo) { return shopGet(accessToken, JsonUtil.toJSONString(shopInfo)); }
python
def send_document(chat_id, document, reply_to_message_id=None, reply_markup=None, **kwargs): """ Use this method to send general files. :param chat_id: Unique identifier for the message recipient — User or GroupChat id :param document: File to send. You can either pa...
python
def visit_assignname(self, node, parent, node_name=None): """visit a node and return a AssignName node""" newnode = nodes.AssignName( node_name, getattr(node, "lineno", None), getattr(node, "col_offset", None), parent, ) self._save_assignme...
python
def mod(self): """ Cached compiled binary of the Generic_Code class. To clear cache invoke :meth:`clear_mod_cache`. """ if self._mod is None: self._mod = self.compile_and_import_binary() return self._mod
java
private void writeObject(ObjectOutputStream out) throws IOException { super.write(out); out.writeUTF(this.mapreduceInputFormat.getClass().getName()); out.writeUTF(this.keyClass.getName()); out.writeUTF(this.valueClass.getName()); this.configuration.write(out); }
python
def _parseSCPDActions(self, actionListElement, actions, variableParameterDict): """Internal method to parse the SCPD definitions. :param actionListElement: the action xml element :type actionListElement: xml.etree.ElementTree.Element :param dict actions: a container to store all actions...
python
def cli(env, identifier, label, note): """Edits an SSH key.""" mgr = SoftLayer.SshKeyManager(env.client) key_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'SshKey') if not mgr.edit_key(key_id, label=label, notes=note): raise exceptions.CLIAbort('Failed to edit SSH key')
python
def get_components_old(A, no_depend=False): ''' Returns the components of an undirected graph specified by the binary and undirected adjacency matrix adj. Components and their constitutent nodes are assigned the same index and stored in the vector, comps. The vector, comp_sizes, contains the number ...
python
def NotifyAboutEnd(self): """Send out a final notification about the end of this flow.""" flow_ref = None if self.runner_args.client_id: flow_ref = rdf_objects.FlowReference( client_id=self.client_id, flow_id=self.urn.Basename()) num_results = len(self.ResultCollection()) notificati...
python
def is_jail(name): ''' Return True if jail exists False if not CLI Example: .. code-block:: bash salt '*' poudriere.is_jail <jail name> ''' jails = list_jails() for jail in jails: if jail.split()[0] == name: return True return False
java
@Deprecated double adjustNumberAsInFormatting(double number) { if (Double.isNaN(number)) { return number; } number = round(multiply(number)); if (Double.isInfinite(number)) { return number; } return toDigitList(number).getDouble(); }
python
def import_app_credentials(filename=CREDENTIALS_FILENAME): """Import app credentials from configuration file. Parameters filename (str) Name of configuration file. Returns credentials (dict) All your app credentials and information imported from the conf...
java
protected void init(int code, String phrase, boolean isError) { this.myPhrase = phrase; this.myPhraseBytes = HttpChannelUtils.getEnglishBytes(phrase); this.myIntCode = code; if (isError) { this.myError = new HttpError(code, this.myPhrase); } initSpecialArrays(...
java
public DockerRuleBuilder waitForMessage(String waitForMessage, int waitSeconds) { this.waitConditions.add(WaitFor.logMessage(waitForMessage)); this.waitForSeconds = waitSeconds; return this; }
java
@Override @Nonnull @OverridingMethodsMustInvokeSuper protected IMicroNode internalConvertToMicroNode (@Nonnull final IHCConversionSettingsToNode aConversionSettings) { // Create the element final IMicroElement ret = createMicroElement (aConversionSettings); if (ret == null) throw new IllegalSt...
java
public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid) throws PersistenceBrokerException { return getKeyValues(cld, oid, true); }
python
def running(name, image=None, skip_translate=None, ignore_collisions=False, validate_ip_addrs=True, force=False, watch_action='force', start=True, shutdown_timeout=None, client_timeout=salt.utils.docker.CLIENT_TI...
python
def can_pp_seq_no_be_in_view(self, view_no, pp_seq_no): """ Checks if the `pp_seq_no` could have been in view `view_no`. It will return False when the `pp_seq_no` belongs to a later view than `view_no` else will return True :return: """ if view_no > self.viewNo: ...
java
public static CompositeConfiguration getConfig() { if (config == null) { config = new CompositeConfiguration(); String configFile = "bard.properties"; if (Util.class.getClassLoader().getResource(configFile) == null) { return config; } ...
python
def add_event(self, event_collection, event_body, timestamp=None): """ Adds an event. Depending on the persistence strategy of the client, this will either result in the event being uploaded to Keen immediately or will result in saving the event to some local cache. :param even...
python
def validate_arrangement_version(self): """Validate if the arrangement_version is supported This is for autorebuilds to fail early otherwise they may failed on workers because of osbs-client validation checks. Method should be called after self.adjust_build_kwargs Shows a warn...
python
def set_config_value(self, name, value, quiet=False): """a client helper function to set a configuration value, meaning reading in the configuration file (if it exists), saving a new config value, and then writing back Parameters ========== name: the name ...
python
def WriteBlobs(self, blob_id_data_map, cursor=None): """Writes given blobs.""" chunks = [] for blob_id, blob in iteritems(blob_id_data_map): chunks.extend(_BlobToChunks(blob_id.AsBytes(), blob)) for values in _PartitionChunks(chunks): _Insert(cursor, "blobs", values)
java
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in any hidden stuff s.defaultReadObject(); // Read in size (number of Mappings) int size = s.readInt(); if (size < 0) throw new java.io.StreamCo...
python
def complete_abstract_value( exe_context, # type: ExecutionContext return_type, # type: Union[GraphQLInterfaceType, GraphQLUnionType] field_asts, # type: List[Field] info, # type: ResolveInfo path, # type: List[Union[int, str]] result, # type: Any ): # type: (...) -> Dict[str, Any] ...
java
public OutgoingFileTransfer createOutgoingFileTransfer(EntityFullJid userID) { // We need to create outgoing file transfers with a full JID since this method will later // use XEP-0095 to negotiate the stream. This is done with IQ stanzas that need to be addressed to a full JID // in order to re...
python
def response_result(self, **kwargs): """ default will fetch MAX_AP pages yield `self.driver.page_source, self.driver.current_url, 1` after mock submit, the first page is crawled. so start@ index of 1, and yield first page first when running over, use else to yield the last page....
python
def second_order_moments(adata, adjusted=False): """Computes second order moments for stochastic velocity estimation. Arguments --------- adata: `AnnData` Annotated data matrix. Returns ------- Mss: Second order moments for spliced abundances Mus: Second order moments for splic...
java
public final <T> String evalWhereForField( final Map<String, Object> pAddParam, final T pEntity, final String pFieldFor) throws Exception { String[] fieldsNames = new String[] {pFieldFor}; pAddParam.put("fieldsNames", fieldsNames); ColumnsValues columnsValues = evalColumnsValues(pAddParam, pEntity...
java
private void updateStart(DownloadRequest request, long totalBytes) { /* if the request has failed before, donnot deliver callback */ if (request.downloadState() == DownloadState.FAILURE) { updateState(request, DownloadState.RUNNING); return; } /* set the download state of this request as ru...
python
def server_poweroff(host=None, admin_username=None, admin_password=None, module=None): ''' Powers down the managed server. host The chassis host. admin_username The username used to access the chassis. admin_password ...
python
def parse_time(self, input_str, reference_time=''): """Parses input with Duckling for occurences of times. Args: input_str: An input string, e.g. 'Let's meet at 11:45am'. reference_time: Optional reference time for Duckling. Returns: A preprocessed list of r...
java
boolean compareLists(AnalyzedTokenReadings[] tokens, int startIndex, int endIndex, Pattern[] patterns) { if (startIndex < 0) { return false; } int i = 0; for (int j = startIndex; j <= endIndex; j++) { if (i >= patterns.length || j >= tokens.length || !patterns[i].matcher(tokens[j].getToken()...
python
def generate_read_batches( self, table, columns, keyset, index="", partition_size_bytes=None, max_partitions=None, ): """Start a partitioned batch read operation. Uses the ``PartitionRead`` API request to initiate the partitioned read....
python
def _set_load_action(self, mem_addr, rec_count, retries, read_complete=False): """Calculate the next record to read. If the last record was successful and one record was being read then look for the next record until we get to the high water mark. If the last r...
java
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.GSAP__P: setP(P_EDEFAULT); return; case AfplibPackage.GSAP__Q: setQ(Q_EDEFAULT); return; case AfplibPackage.GSAP__R: setR(R_EDEFAULT); return; case AfplibPackage.GSAP__S: setS(S_EDEFAULT); ...
java
public Entry getNext() { checkEntryParent(); Entry entry = null; if(!isLast()) { entry = next; } return entry; }
java
public SignalRResourceInner beginCreateOrUpdate(String resourceGroupName, String resourceName, SignalRCreateParameters parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, resourceName, parameters).toBlocking().single().body(); }
java
@Override public void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2 = (Graphics2D) g.create(); g2.setComposite(AlphaComposite.SrcAtop.derive(alpha)); icon.paintIcon(c, g2, x, y); g2.dispose(); }
java
public String getNamespaceURIFromPrefix(String prefix) { String uri = null; if (m_prefixMap != null) uri = m_prefixMap.lookupNamespace(prefix); return uri; }
python
def iterate(infile): '''iterate over ``samtools pileup -c`` formatted file. *infile* can be any iterator over a lines. The function yields named tuples of the type :class:`pysam.Pileup.PileupSubstitution` or :class:`pysam.Pileup.PileupIndel`. .. note:: The parser converts to 0-based coord...
java
public static boolean hasField(Class<?> beanClass, String name) throws SecurityException { return null != getField(beanClass, name); }
java
public Long getProcessId(String procname) throws Exception { Process proc = ProcessCache.getProcess(procname, 0); if (proc == null) throw new DataAccessException(0, "Cannot find process with name " + procname + ", version 0"); return proc.getId(); }
python
def split(self, max_commands): """ Split this action into an equivalent list of actions, each of which have at most max_commands commands. :param max_commands: max number of commands allowed in any action :return: the list of commands created from this one """ a_prior = A...
java
@Override public List<CPOptionCategory> getCPOptionCategoriesByUuidAndCompanyId( String uuid, long companyId) { return cpOptionCategoryPersistence.findByUuid_C(uuid, companyId); }
python
def monitor(name, callback): ''' monitors actions on the specified container, callback is a function to be called on ''' global _monitor if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) if _monitor: if _monitor.is_monitored...
python
def create(style_dataset, content_dataset, style_feature=None, content_feature=None, max_iterations=None, model='resnet-16', verbose=True, batch_size = 6, **kwargs): """ Create a :class:`StyleTransfer` model. Parameters ---------- style_dataset: SFrame Input style images. Th...
python
def get_images(config, name=None, quiet=False, all=True, *args, **kwargs): ''' List docker images :type name: string :param name: A repository name to filter on :type quiet: boolean :param quiet: Only show image ids :type all: boolean :param all: Show all images :rtype: dict ...
python
def is_moderated(self, curr_time, pipe): ''' Tests to see if the moderation limit is not exceeded @return: True if the moderation limit is exceeded ''' # get key, otherwise default the moderate key expired and # we dont care value = pipe.get(self.moderate_key) ...
java
public static XElement parseXML(File file) throws XMLStreamException { try (InputStream in = new FileInputStream(file)) { return parseXML(in); } catch (IOException ex) { throw new XMLStreamException(ex); } }
python
def size(self): """Tuple[int, int]: The width and height of the window.""" size = ffi.new('int[]', 2) lib.SDL_GetWindowSize(self._ptr, size + 0, size + 1) return (size[0], size[1])
java
@Override public void delete() throws JMSException { if (connection == null) throw new FFMQException("Temporary queue already deleted","QUEUE_DOES_NOT_EXIST"); connection.deleteTemporaryQueue(name); connection = null; }
java
private <T> String buildClassListTag(final T t) { return (exportClassFullName != null) ? exportClassFullName : t.getClass().getSimpleName() + exportClassEnding; }
python
def get_objects(self, subject, predicate): """ Search for all subjects related to the specified subject and predicate. :param subject: :param object: :rtype: generator of RDF statements """ for statement in self.spo_search(subject=subject, predicate=predicate): ...
python
def _binary_exp(expression, op): # type: (QuilParser.ExpressionContext, Callable) -> Number """ Apply an operator to two expressions. Start by evaluating both sides of the operator. """ [arg1, arg2] = expression.expression() return op(_expression(arg1), _expression(arg2))
java
@Trivial protected String processString(String name, String expression, boolean immediateOnly) { return processString(name, expression, immediateOnly, false); }
python
def lF_value (ER,EF,dfnum,dfden): """ Returns an F-statistic given the following: ER = error associated with the null hypothesis (the Restricted model) EF = error associated with the alternate hypothesis (the Full model) dfR-dfF = degrees of freedom of the numerator dfF = degrees o...
java
public Tree clear(String path) { Tree child = getChild(path, false); if (child == null) { child = putMap(path); } else { child.clear(); } return child; }
python
def safe_unicode(string): '''Safely transform any object into utf8 encoded bytes''' if not isinstance(string, basestring): string = unicode(string) if isinstance(string, unicode): string = string.encode('utf8') return string
java
public FaunusPipeline simplePath() { this.state.assertNotLocked(); this.state.assertNoProperty(); this.compiler.addMap(CyclicPathFilterMap.Map.class, NullWritable.class, FaunusVertex.class, CyclicPathFilterMap.createConfiguration(this.state.getEle...
java
protected boolean tryBridgeMethod(MethodNode target, Expression receiver, boolean implicitThis, TupleExpression args, ClassNode thisClass) { ClassNode lookupClassNode; if (target.isProtected()) { lookupClassNode = controller.getClassNode(); w...
java
private File saveAsFile(ResponseBody responseBody) { if (responseBody == null) { return null; } try { File file = new File(destDirectory + File.separator + fileName + retrieveUniqueId() + "." + extension); InputStream inputStream = null; OutputStream outputStream = null; try ...
java
@Override protected boolean isPresent(final Request request) { if (isAllowNoSelection()) { String id = getId(); return request.getParameter(id + "-h") != null; } else { return super.isPresent(request); } }