language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public final BELScriptWalker.argument_return argument() throws RecognitionException { BELScriptWalker.argument_return retval = new BELScriptWalker.argument_return(); retval.start = input.LT(1); CommonTree root_0 = null; CommonTree _first_0 = null; CommonTree _last = null; ...
python
def store_source_info(self, calc_times): """ Save (weight, num_sites, calc_time) inside the source_info dataset """ if calc_times: source_info = self.datastore['source_info'] arr = numpy.zeros((len(source_info), 3), F32) ids, vals = zip(*sorted(calc_ti...
java
public IntStreamEx sorted(Comparator<Integer> comparator) { return new IntStreamEx(stream().boxed().sorted(comparator).mapToInt(Integer::intValue), context); }
python
def describe(name, tags=None, region=None, key=None, keyid=None, profile=None): ''' Return RDS instance details. CLI example:: salt myminion boto_rds.describe myrds ''' res = __salt__['boto_rds.exists'](name, tags, region, key, keyid, pro...
python
def snr(vref, vcmp): """ Compute Signal to Noise Ratio (SNR) of two images. Parameters ---------- vref : array_like Reference image vcmp : array_like Comparison image Returns ------- x : float SNR of `vcmp` with respect to `vref` """ dv = np.var(vref) ...
java
public boolean dropColumn (Connection conn, String table, String column) throws SQLException { if (!tableContainsColumn(conn, table, column)) { return false; } executeQuery(conn, "ALTER TABLE " + tableSQL(table) + " DROP COLUMN " + columnSQL(column)); log("Database column...
python
def particles(self): """ Access the variational particles corresponding to this set of variational equations. The function returns a list of particles which are sorted in the same way as those in sim.particles The particles are pointers and thus can be modified. If t...
java
public <T> List<T> load( String serviceType ) { List<T> services = new ArrayList<T>(); String resourceName = "/META-INF/services/" + serviceType; try { Enumeration<URL> resources = classLoader.getResources( resourceName ); while( resources.hasMoreElements() ) ...
python
def feed(self, data): """ :param data: One of these: - ``str``, ``unicode`` (Python 2.7), or ``bytes`` (Python 3, decoded using UTF-8) representing a JSON-serialized `Update <https://core.telegram.org/bots/api#update>`_ object. - a ``dict`` representing...
python
def to_string(s, encoding=None, errors='strict'): """Inverse of to_bytes""" if isinstance(s, bytes): return s.decode(encoding or 'utf-8', errors) elif not isinstance(s, str): return str(s) else: return s
python
def _format_sha1(graph, node): """Return formatted text with the submodule information.""" try: submodules = node.submodules if submodules: submodule = ':'.join(submodules) return click.style(submodule, fg='green') + '@' + click.style( node.commit.hexsha[...
java
@XmlElementDecl(namespace = "http://www.opengis.net/gml", name = "usesVerticalDatum") public JAXBElement<VerticalDatumRefType> createUsesVerticalDatum(VerticalDatumRefType value) { return new JAXBElement<VerticalDatumRefType>(_UsesVerticalDatum_QNAME, VerticalDatumRefType.class, null, value); }
java
@SuppressWarnings("unchecked") public <Metadata> Optional<Metadata> get(MetadataKey<Metadata> key) { return Optional.ofNullable((Metadata) metadataMap.get(key)); }
python
def handle_left_double_click(self, info): """Whatever we want to do, when the VideoWidget has been double-clicked with the left button """ if (self.double_click_focus == False): # turn focus on print(self.pre, "handle_left_double_click: focus on") self.cb_focus() ...
java
@Override public Terms terms(String field) throws IOException { return new MtasTerms(delegateFieldsProducer.terms(field), indexInputList, indexInputOffsetList, version); }
java
public void detachIdentifier(String identifier) { if (!StringUtils.equals(identifier, getIdentifier())) { Sysprop s = CoreUtils.getInstance().getDao().read(getAppid(), identifier); if (s != null && StringUtils.equals(getId(), s.getCreatorid())) { deleteIdentifier(identifier); } } }
java
@SuppressWarnings("unchecked") public EList<IfcClassificationItem> getContains() { return (EList<IfcClassificationItem>) eGet(Ifc2x3tc1Package.Literals.IFC_CLASSIFICATION__CONTAINS, true); }
java
public static RefundNotifyReqInfo decryptRefundNotifyReqInfo(String req_info, String key) { try { Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); Key sKeySpec = new SecretKeySpec(DigestUtils.md5Hex(key).getBytes(), "AES"); cipher.init(Cipher.DECRYPT_MODE, sKeySpec); byte[] resultByte = ciphe...
java
public void setMinTokenLength(int minTokenLength) { if(minTokenLength < 0) throw new IllegalArgumentException("Minimum token length must be non negative, not " + minTokenLength); if(minTokenLength > maxTokenLength) throw new IllegalArgumentException("Minimum token length can ...
python
def stop(self): """Stops read loop and closes socket if it has been created. """ self._running = False if self._socket is None: return try: self._socket.shutdown(socket.SHUT_RDWR) self._socket.close() except socket.error: p...
python
def predict (self, mjd, complain=True, n=20000): """Predict the object position at a given MJD. The return value is a tuple ``(ra, dec, major, minor, pa)``, all in radians. These are the predicted position of the object and its uncertainty at *mjd*. If *complain* is True, print out warn...
java
private List<List<K>> prepareKeysForParallelism() { // Calculate the number of row keys to be queried at a time. // Consider whether parallelism is enabled or not. // When numThreads is calculated, the int truncation // causes one fewer thread to be used if numKeys isn't evenly divided // into maxRowCountPerQ...
python
def _set_view(self): """Assign a view to current graph""" view_class = ReverseView if self.inverse_y_axis else View self.view = view_class( self.width - self.margin_box.x, self.height - self.margin_box.y, self._box )
python
def readinto(self, b): """Read up to len(b) bytes into the writable buffer *b* and return the number of bytes read. If the socket is non-blocking and no bytes are available, None is returned. If *b* is non-empty, a 0 return value indicates that the connection was shutdown at th...
java
public T getHighestRankedService() { Iterator<T> iterator = getServices(); return iterator.hasNext() ? iterator.next() : null; }
python
def on_transfer(self, transfer): """ This handles the echo logic, as described in https://github.com/raiden-network/raiden/issues/651: - for transfers with an amount that satisfies `amount % 3 == 0`, it sends a transfer with an amount of `amount - 1` back to the initiator ...
java
public static CommerceAccountUserRel findByCommerceAccountUserId_First( long commerceAccountUserId, OrderByComparator<CommerceAccountUserRel> orderByComparator) throws com.liferay.commerce.account.exception.NoSuchAccountUserRelException { return getPersistence() .findByCommerceAccountUserId_First(commerc...
python
def signed_face_areas(faces, axis=1): ''' signed_face_areas(faces) yields a potential function f(x) that calculates the signed area of each face represented by the simplices matrix faces. If faces is None, then the parameters must arrive in the form of a flattened (n x 3 x 2) matrix where n is th...
python
def main(operation, profile, auto, debug, user_name=''): """ End-to-end renew of access keys for a specific profile in local awscli config """ if user_name: logger.info('user_name parameter given (%s) as surrogate' % user_name) try: if operation in VALID_INSTALL: print(op...
java
public String getDocumentId(Object instance) { if (instance == null) { return null; } DocumentInfo value = documentsByEntity.get(instance); return value != null ? value.getId() : null; }
python
def set_telephone(self, tel): """ 更新电话 @structure bool :param tel: 电话号码, 需要满足手机和普通电话的格式, 例如 `18112345678` 或者 '0791-1234567' """ return type(tel)(self.query(SetTelephone(tel))) == tel
python
def create(self, value): """Create the troposphere type from the value. Args: value (Union[dict, list]): A dictionary or list of dictionaries (see class documentation for details) to use as parameters to create the Troposphere type instance. E...
python
def _compress_hextets(cls, hextets): """Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(...
java
public static <N extends TreeNode<N>> boolean equalsWithoutOrder(N tree1, N tree2) { if (!tree1.getName().equals(tree2.getName())) { return false; } List<N> children1 = tree1.getChildren(); List<N> children2 = tree2.getChildren(); if (children1.size() != children2.size()) { return false; } for (N ...
python
def turn_physical_off(Pot): """ NAME: turn_physical_off PURPOSE: turn off automatic returning of outputs in physical units INPUT: (none) OUTPUT: (none) HISTORY: 2016-01-30 - Written - Bovy (UofT) """ if isinstance(Pot,list): for po...
java
@Deprecated public static String getParameter(final Request request, final String parameterName) { return PageParametersExtensions.getParameter(request, parameterName); }
java
public void parse(CmsResource resource) throws CmsException { CmsFile file = m_cms.readFile(resource); m_resource = resource; CmsXmlContent content = CmsXmlContentFactory.unmarshal(m_cms, file); parse(content); }
java
@NotNull public <R> R[] toArray(@NotNull IntFunction<R[]> generator) { return Operators.toArray(iterator, generator); }
python
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: CountryContext for this CountryInstance :rtype: twilio.rest.pricing.v2.voice.country.CountryConte...
python
def begin_batch(self): ''' Starts the batch operation. Intializes the batch variables is_batch: batch operation flag. batch_table: the table name of the batch operation batch_partition_key: the PartitionKey of the batch requests. batch...
python
def intervals_ms(self, timeout_ms): """Generate a series of interval lengths, in ms, which will add up to the number of ms in timeout_ms. If timeout_ms is None, keep returning intervals forever. """ if timeout_ms is config.FOREVER: while True: yield se...
java
protected void parseWorkspaceElement(final Element element) throws ProponoException { final Element titleElem = element.getChild("title", AtomService.ATOM_FORMAT); setTitle(titleElem.getText()); if (titleElem.getAttribute("type", AtomService.ATOM_FORMAT) != null) { setTitleType(title...
python
def optional(self, value = None): """Optional Getter/Setter method for optional flag Args: value (bool): If set, the method is a setter Returns: bool | None """ # If there's no value, this is a getter if value is None: return this._optional # Else, set the flag else: this._optional = ...
java
public Javalin addHandler(@NotNull HandlerType handlerType, @NotNull String path, @NotNull Handler handler, @NotNull Set<Role> roles) { servlet.addHandler(handlerType, path, handler, roles); eventManager.fireHandlerAddedEvent(new HandlerMetaInfo(handlerType, Util.prefixContextPath(servlet.getConfig().co...
java
public void marshall(RetryStageExecutionRequest retryStageExecutionRequest, ProtocolMarshaller protocolMarshaller) { if (retryStageExecutionRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(r...
python
def get_parent_objective_bank_nodes(self): """Gets the parents of this objective bank. return: (osid.learning.ObjectiveBankNodeList) - the parents of the ``id`` *compliance: mandatory -- This method must be implemented.* """ parent_objective_bank_nodes = [] ...
java
protected void _generate(SarlAgent agent, IExtraLanguageGeneratorContext context) { final JvmDeclaredType jvmType = getJvmModelAssociations().getInferredType(agent); final PyAppendable appendable = createAppendable(jvmType, context); final List<JvmTypeReference> superTypes; if (agent.getExtends() != null) { ...
java
boolean checkAddOrSubmit(Hashtable<String, KSPresentation> mentions) throws InterruptedException{ if (((mentions.size() % nafPopulator.batchSize) == 0) && (nafPopulator.batchSize != -1)) { addAndFreeMemory(mentions); return true; } else { return false; } }
python
def get_candidates(self): """Get all CandidateElections for this election.""" candidate_elections = CandidateElection.objects.filter(election=self) return [ce.candidate for ce in candidate_elections]
java
public SplunkStormRest format(SplunkStormRestFormat format) { String strFormat; switch (format) { case JSON_NEW_LINE_TIMESTAMP: strFormat = "json_new_line"; break; default: case JSON_NEW_LINE_TIMESTAMP_META: strFormat = ...
python
def search_ip(self, searchterm): """Search for ips :type searchterm: str :rtype: list """ return self.__search(type_attribute=self.__mispiptypes(), value=searchterm)
python
def _float_ruptures(rupture_area, rupture_length, cell_area, cell_length): """ Get all possible unique rupture placements on the fault surface. :param rupture_area: The area of the rupture to float on the fault surface, in squared km. :param rupture_length: The target length (spatial ex...
python
def config_dir(mkcustom=False): """Returns the configuration directory for custom package settings. """ from acorn.utility import reporoot from acorn.base import testmode from os import path alternate = path.join(path.abspath(path.expanduser("~")), ".acorn") if testmode or (not path.isdir(al...
java
private void commitSource() { int partitionId = getPartitionId(); InternalPartitionServiceImpl partitionService = getService(); PartitionReplicaManager replicaManager = partitionService.getReplicaManager(); ILogger logger = getLogger(); int sourceNewReplicaIndex = migrationInfo...
python
def active(self): """ Returns if task is active. """ if not os.path.isfile(self._paths['active_file']): return False return self._loaded
java
public void addXSLAttribute(String name, final String value, final String uri) { if (m_elemContext.m_startTagOpen) { final String patchedName = patchName(name); final String localName = getLocalName(patchedName); addAttributeAlways(uri,localName, patchedName, "CD...
python
def getDueDate(self): """Used to populate getDueDate index and metadata. This calculates the difference between the time the analysis processing started and the maximum turnaround time. If the analysis has no turnaround time set or is not yet ready for proces, returns None """ ...
java
public boolean compareAndSet(double expect, double update) { long e = Double.doubleToLongBits(expect); long u = Double.doubleToLongBits(update); return value.compareAndSet(e, u); }
python
def setup_logging(cls, log_dir="./logs", log_name=None, header=None, names=None, delimiter=";", logger_name='WD_logger'): """ A static method which initiates log files compatible to .csv format, allowing for easy further analysis. :param log_dir: allows for setting relative...
java
@Action(name = "List Remover", outputs = { @Output(RESPONSE), @Output(RETURN_RESULT), @Output(RETURN_CODE) }, responses = { @Response(text = SUCCESS, field = RETURN_CODE, value = RETURN_CODE_SUCCESS, matc...
python
def get_online_date(self, **kwargs): """Get the online date from the meta creation date.""" qualifier = kwargs.get('qualifier', '') content = kwargs.get('content', '') # Handle meta-creation-date element. if qualifier == 'metadataCreationDate': date_match = META_CREAT...
python
def login(self, login, password, url=None): """login page """ auth = self._auth(login, password) cherrypy.session['isadmin'] = auth['isadmin'] cherrypy.session['connected'] = auth['connected'] if auth['connected']: if auth['isadmin']: message ...
python
def GetForwardedIps(self, interface, interface_ip=None): """Retrieve the list of configured forwarded IP addresses. Args: interface: string, the output device to query. interface_ip: string, current interface ip address. Returns: list, the IP address strings. """ args = ['ls', 't...
python
def replace_entities(self, html): """ Replace htmlentities with unicode characters @Params html - html source to replace entities in @Returns String html with entities replaced """ def fixup(text): """replace the htmlentities in some text""" ...
java
public void applyPattern(String pat) { this.pattern = pat; parsePattern(); setLocale(null, null); // reset parsed pattern items patternItems = null; }
python
def populate_classified_values( unassigned_values, assigned_values, default_classes, list_unique_values, tree_mapping_widget): """Populate lstUniqueValues and treeClasses.from the parameters. :param unassigned_values: List of values that haven't been assigned to a cl...
python
def parse_template(self, template, **context): """ To parse a template and return all the blocks """ required_blocks = ["subject", "body"] optional_blocks = ["text_body", "html_body", "return_path", "format"] if self.template_context: context = dict(self.temp...
java
protected final void shiftKeys(int pos) { // Shift entries with the same hash. int last, slot; char curr; final char[] key = this.key; for (; ; ) { pos = ((last = pos) + 1) & mask; for (; ; ) { if (((curr = key[pos]) == ((char) 0))) { ...
python
def strip_symbols(s, pass_symbols=(u'й', u'Й', u'\n')): """ Strip ugly unicode symbols from a string """ result = [] for char in s: # Pass these symbols without processing if char in pass_symbols: result.append(char) continue for c in unicodedata.normalize('NF...
java
private Map<Class<?>, Object> executeBeforeBenchClass( final Map<Class<?>, Object> instantiatedObj, final BenchmarkResult res) { final Map<Class<?>, Object> returnVal = new Hashtable<Class<?>, Object>(); // invoking before bench class for (final Class<?> clazz : instantiatedObj.keySet()) { final Objec...
java
void updateItems(List<String> updatedItems) { Set<CmsUUID> ids = new HashSet<CmsUUID>(); for (String id : updatedItems) { ids.add(new CmsUUID(id)); } m_resultTable.update(ids, false); }
python
def _cleanup(self) -> None: """Cleanup unused transports.""" if self._cleanup_handle: self._cleanup_handle.cancel() now = self._loop.time() timeout = self._keepalive_timeout if self._conns: connections = {} deadline = now - timeout ...
python
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..." for category in orm['document_library.DocumentCategory'].objects.all(): category.slug = category.documentcategorytitle_set.all()[0].title...
python
def licenses(source=DEFAULT_LICENSE_FILE): '''Feed the licenses from a JSON file''' if source.startswith('http'): json_licenses = requests.get(source).json() else: with open(source) as fp: json_licenses = json.load(fp) if len(json_licenses): log.info('Dropping existi...
java
@Override public UserTrades getTradeHistory(final TradeHistoryParams params) throws IOException { if (params instanceof RippleTradeHistoryCount) { final RippleTradeHistoryCount rippleParams = (RippleTradeHistoryCount) params; rippleParams.resetApiCallCount(); rippleParams.resetTradeCount(); ...
python
def next(self): """returns the next result :return: The next result. :rtype: dict :raises StopIteration: If no more result is left. """ if self._orderByPQ.size() > 0: targetRangeExContext = self._orderByPQ.pop() ...
java
public DefaultShardManagerBuilder setShards(Collection<Integer> shardIds) { Checks.notNull(shardIds, "shardIds"); for (Integer id : shardIds) { Checks.notNegative(id, "minShardId"); Checks.check(id < this.shardsTotal, "maxShardId must be lower than shardsTotal"); ...
java
@Override public ImageHeader readHeader(InputStream input) throws IOException { checkSkippedError(input.skip(2), 2); int current = input.read(); while (255 == current) { final int marker = input.read(); final int len = readInt(input, 2, true); ...
java
public static Date asDate(JsonNode node, String dateTimeFormat) { return node != null ? ValueUtils.convertDate(node, dateTimeFormat) : null; }
python
def _parse_tag(self, el): """Extract the namespace and tag from an element.""" ns = None tag = el.tag if tag[0] == '{': ns, tag = tag[1:].split('}', 1) if self.ns_map and ns in self.ns_map: ns = self.ns_map[ns] return ns, tag
java
public TransitionController addAnimatorSetAsTransition(@Nullable View target, @NonNull AnimatorSet animatorSet) { return addTransitionController(new DefaultTransitionController(target, animatorSet)); }
python
def parse_date(string, force_datetime=False): """ Takes a Xero formatted date, e.g. /Date(1426849200000+1300)/""" matches = DATE.match(string) if not matches: return None values = dict([ ( k, v if v[0] in '+-' else int(v) ) for k,v in matches.groupdict()....
python
def average(x): """ Return a numpy array of column average. It does not affect if the array is one dimension Parameters ---------- x : ndarray A numpy array instance Returns ------- ndarray A 1 x n numpy array instance of column average Examples -------- ...
java
public XMLResource xml(JSONPathQuery path) throws Exception { Object jsonValue = path.eval(this); return xml(jsonValue.toString()); }
python
def xmllint_format(xml): """ Pretty-print XML like ``xmllint`` does. Arguments: xml (string): Serialized XML """ parser = ET.XMLParser(resolve_entities=False, strip_cdata=False, remove_blank_text=True) document = ET.fromstring(xml, parser) return ('%s\n%s' % ('<?xml version="1.0" en...
java
private String unescapeHtml(Object content) { return content != null ? content.toString().replace("&lt;", "<").replace("&gt;", ">") : ""; }
java
public Segment enableMultithreading(boolean enable) { if (enable) config.threadNumber = Runtime.getRuntime().availableProcessors(); else config.threadNumber = 1; return this; }
python
def remove_log_action(portal): """Removes the old Log action from types """ logger.info("Removing Log Tab ...") portal_types = api.get_tool("portal_types") for name in portal_types.listContentTypes(): ti = portal_types[name] actions = map(lambda action: action.id, ti._actions) ...
java
public static DurationUtil getInstance() { if (instance == null) { synchronized (DurationUtilImpl.class) { if (instance == null) { instance = new DurationUtilImpl(); } } } return instance; }
python
def init(self): """Init the connection to the RESTful server.""" if not self.export_enable: return None # Build the RESTful URL where the stats will be posted url = '{}://{}:{}{}'.format(self.protocol, self.host, ...
python
def with_cache(function): """Return a decorator that interacts with a handler's cache. This decorator must be applied to a DefaultHandler class method or instance method as it assumes `cache`, `ca_lock` and `timeouts` are available. """ @wraps(function) def wrap...
python
def filtered_error_rate(hyps_path: Union[str, Path], refs_path: Union[str, Path], labels: Set[str]) -> float: """ Returns the error rate of hypotheses in hyps_path against references in refs_path after filtering only for labels in labels. """ if isinstance(hyps_path, Path): hyps_path = str(hyps_path...
python
async def transfer_data(self) -> None: """ Read incoming messages and put them in a queue. This coroutine runs in a task until the closing handshake is started. """ try: while True: message = await self.read_message() # Exit the loop...
java
public boolean addWaitingWork(final T context) { write.lock(); try { boolean result = !waitingWork.contains(context); if (result) { waitingWork.add(context); workChanged.signalAll(); // Wake up! } return result; } finally { write.unlock(); } }
java
private List<Task> receiveTasks() { synchronized (mutex) { if (tasks.isEmpty()) { return Collections.emptyList(); } else { List<Task> currentTasks = tasks; tasks = new ArrayList<Task>(); return currentTasks; } } }
python
def _basic_publish(self, msg, exchange='', routing_key='', mandatory=False, immediate=False): """Publish a message This method publishes a message to a specific exchange. The message will be routed to queues as defined by the exchange configuration and distributed...
java
@View(name = "by_uid_otp", map = "function(doc) { if(doc.token && doc.userId) { emit([doc.userId, doc.token], doc) } }") public CouchDbGoogleAuthenticatorToken findOneByUidForOtp(final String uid, final Integer otp) { val view = createQuery("by_uid_otp").key(ComplexKey.of(uid, otp)).limit(1); return...
python
def get_request(self, uuid, raw=False, multiple=False, connection_adapter=None): """Get a RPC request. :param str uuid: Rpc Identifier :param bool raw: If enabled return the frame as is, else return result as a dictionary. :param bool multipl...
java
@Override public void _whereIn(String fieldName, Collection<Object> values) { _whereIn(fieldName, values, false); }
java
private static int metadata_end_cmp_(MetaData x, MetaData y) { return x.getEnd().compareTo(y.getEnd()); }