text
stringlengths
2
1.04M
meta
dict
from django.conf import settings from django.core.urlresolvers import reverse from django.contrib import messages from django.core.mail import EmailMultiAlternatives from django.template import RequestContext from django.template.loader import render_to_string from django.views.generic import CreateView from feedback.utils import send_threaded from feedback.forms import FeedbackForm from feedback.models import Feedback class FeedbackView(CreateView): form_class = FeedbackForm template_name = 'feedback/feedback.html' def get_form_kwargs(self): kwargs = super(FeedbackView, self).get_form_kwargs() instance = Feedback( url = self.request.META.get("HTTP_REFERER", ''), user = self.request.user if self.request.user.is_authenticated() else None ) kwargs.update({ "instance": instance, }) return kwargs def form_valid(self, *args, **kwargs): if getattr(settings, 'FEEDBACK_SEND_EMAIL', False): context = {"feedback":self.object} send_threaded(EmailMultiAlternatives( render_to_string('feedback/emails/feedback_subject.txt', context), render_to_string('feedback/emails/feedback_body.txt', context), settings.DEFAULT_FROM_EMAIL, [getattr(settings, 'FEEDBACK_TO_EMAIL', settings.DEFAULT_FROM_EMAIL),] ) ) if 'django.contrib.messages' in settings.INSTALLED_APPS: messages.success(self.request, "Your feedback has been sent. Thank you!") return super(FeedbackView, self).form_valid(*args, **kwargs) def form_invalid(self, form): # Update our context to avoid being overwritten by context processors context = RequestContext(self.request, self.get_context_data()) context['feedback_form'] = form return self.render_to_response(context) def get_success_url(self): return self.request.META.get("HTTP_REFERER", reverse('django-user-feedback'))
{ "content_hash": "a62017aa77c46d68b6b62fc8a18f4428", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 90, "avg_line_length": 42, "alnum_prop": 0.6671525753158406, "repo_name": "gabrielhurley/django-user-feedback", "id": "158b71e1691caeab648522a83d9f96e2932e3d2e", "size": "2058", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "feedback/views.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "16540" } ], "symlink_target": "" }
package com.amazonaws.services.simplesystemsmanagement.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.simplesystemsmanagement.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * GetOpsMetadataResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetOpsMetadataResultJsonUnmarshaller implements Unmarshaller<GetOpsMetadataResult, JsonUnmarshallerContext> { public GetOpsMetadataResult unmarshall(JsonUnmarshallerContext context) throws Exception { GetOpsMetadataResult getOpsMetadataResult = new GetOpsMetadataResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return getOpsMetadataResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("ResourceId", targetDepth)) { context.nextToken(); getOpsMetadataResult.setResourceId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("Metadata", targetDepth)) { context.nextToken(); getOpsMetadataResult.setMetadata(new MapUnmarshaller<String, MetadataValue>(context.getUnmarshaller(String.class), MetadataValueJsonUnmarshaller.getInstance()).unmarshall(context)); } if (context.testExpression("NextToken", targetDepth)) { context.nextToken(); getOpsMetadataResult.setNextToken(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return getOpsMetadataResult; } private static GetOpsMetadataResultJsonUnmarshaller instance; public static GetOpsMetadataResultJsonUnmarshaller getInstance() { if (instance == null) instance = new GetOpsMetadataResultJsonUnmarshaller(); return instance; } }
{ "content_hash": "261f726fdfcb895fb63d6a40ce623a1d", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 136, "avg_line_length": 39.90277777777778, "alnum_prop": 0.6477549599721545, "repo_name": "aws/aws-sdk-java", "id": "3bed996fe4194f44d4b894e9552baaa124fe5d43", "size": "3453", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/GetOpsMetadataResultJsonUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#include <iostream> #include <vector> #include <Shotgun/Entity.h> #include <Shotgun/Shotgun.h> #include <Shotgun/Project.h> namespace SG { // ***************************************************************************** Project::Project(Shotgun *sg, const xmlrpc_c::value &attrs) : Entity(sg) { m_entityType = m_classType = "Project"; if (attrs.type() != xmlrpc_c::value::TYPE_NIL) { m_attrs = new xmlrpc_c::value(attrs); } } // ***************************************************************************** Project::Project(const Project &ref) : Entity(ref.m_sg) { m_entityType = m_classType = "Project"; m_attrs = new xmlrpc_c::value(*ref.m_attrs); } // ***************************************************************************** Project::~Project() { // Nothing } // ***************************************************************************** List Project::defaultReturnFields() { return List("id") .append("project") .append("created_at") .append("updated_at") .append("name"); } } // End namespace SG
{ "content_hash": "68124d6d4b2effa0c352ca2ab0e50bd4", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 80, "avg_line_length": 23.145833333333332, "alnum_prop": 0.42304230423042305, "repo_name": "shotgunsoftware/cplusplus-api", "id": "c756f1145db685e2948f563d07cf35f877c2a9c2", "size": "2668", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/Shotgun/Project.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "14959" }, { "name": "C++", "bytes": "377399" }, { "name": "Python", "bytes": "12925" }, { "name": "Shell", "bytes": "1525" } ], "symlink_target": "" }
Additional header content Gets or sets maximun value of axis. **Namespace:**&nbsp;<a href="N_iTin_Export_Model">iTin.Export.Model</a><br />**Assembly:**&nbsp;iTin.Export.Core (in iTin.Export.Core.dll) Version: 2.0.0.0 (2.0.0.0) ## Syntax **C#**<br /> ``` C# public string Maximun { get; set; } ``` **VB**<br /> ``` VB Public Property Maximun As String Get Set ``` #### Property Value Type: String<br />A String that contains the maximun value of axis. Accepts only numbers in floating point. The default is `Autodetect`. ## Remarks **ITEE Object Element Usage**<br /> ``` XML <Marks Maximun="Autodetect|float" .../> ``` <strong>Compatibility table with native writers.</strong><table><tr><th>Comma-Separated Values<br /><a href="T_iTin_Export_Writers_CsvWriter">CsvWriter</a></th><th>Tab-Separated Values<br /><a href="T_iTin_Export_Writers_TsvWriter">TsvWriter</a></th><th>SQL Script<br /><a href="T_iTin_Export_Writers_SqlScriptWriter">SqlScriptWriter</a></th><th>XML Spreadsheet 2003<br /><a href="T_iTin_Export_Writers_Spreadsheet2003TabularWriter">Spreadsheet2003TabularWriter</a></th></tr><tr><td align="center">No has effect</td><td align="center">No has effect</td><td align="center">No has effect</td><td align="center">No has effect</td></tr></table> A <strong>`X`</strong> value indicates that the writer supports this element. ## See Also #### Reference <a href="T_iTin_Export_Model_AxisDefinitionValuesModel">AxisDefinitionValuesModel Class</a><br /><a href="N_iTin_Export_Model">iTin.Export.Model Namespace</a><br />
{ "content_hash": "cc1b8faaeea148ad7bddcfe0fc05f0f1", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 718, "avg_line_length": 38.7, "alnum_prop": 0.7099483204134367, "repo_name": "iAJTin/iExportEngine", "id": "fdb58a62f177d010761e7daf2e69828ff17ccfd4", "size": "1594", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "source/documentation/iTin.Export.Documentation/Documentation/P_iTin_Export_Model_AxisDefinitionValuesModel_Maximun.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2298" }, { "name": "C#", "bytes": "2815693" }, { "name": "Smalltalk", "bytes": "7632" }, { "name": "XSLT", "bytes": "14099" } ], "symlink_target": "" }
from cffi import FFI ffi = FFI() pmemobj_structs = """ /* for pmemobj.py */ typedef PMEMoid PObjPtr; typedef struct { PObjPtr type_table; PObjPtr root_object; } PRoot; typedef struct { size_t ob_refcnt; size_t ob_type; } PObject; typedef struct { PObject ob_base; size_t ob_size; } PVarObject; typedef struct { PVarObject ob_base; PObjPtr ob_items; size_t allocated; } PListObject; typedef struct { PObject ob_base; double fval; } PFloatObject; """ ffi.set_source("_pmem", """ #include <libpmem.h> #include <libpmemlog.h> #include <libpmemblk.h> #include <libpmemobj.h> """ + pmemobj_structs, libraries=['pmem', 'pmemlog', 'pmemblk', 'pmemobj']) ffi.cdef(""" /* libpmem */ typedef int mode_t; const char *pmem_errormsg(void); void *pmem_map_file(const char *path, size_t len, int flags, mode_t mode, size_t *mapped_lenp, int *is_pmemp); int pmem_unmap(void *addr, size_t len); int pmem_has_hw_drain(void); int pmem_is_pmem(void *addr, size_t len); const char *pmem_check_version( unsigned major_required, unsigned minor_required); void pmem_persist(void *addr, size_t len); int pmem_msync(void *addr, size_t len); void pmem_flush(void *addr, size_t len); void pmem_drain(void); /* libpmemlog */ typedef struct pmemlog PMEMlogpool; typedef int off_t; const char *pmemlog_errormsg(void); PMEMlogpool *pmemlog_open(const char *path); PMEMlogpool *pmemlog_create(const char *path, size_t poolsize, mode_t mode); void pmemlog_close(PMEMlogpool *plp); size_t pmemlog_nbyte(PMEMlogpool *plp); void pmemlog_rewind(PMEMlogpool *plp); off_t pmemlog_tell(PMEMlogpool *plp); int pmemlog_check(const char *path); int pmemlog_append(PMEMlogpool *plp, const void *buf, size_t count); const char *pmemlog_check_version( unsigned major_required, unsigned minor_required); void pmemlog_walk(PMEMlogpool *plp, size_t chunksize, int (*process_chunk)(const void *buf, size_t len, void *arg), void *arg); /* libpmemblk */ typedef struct pmemblk PMEMblkpool; const char *pmemblk_errormsg(void); PMEMblkpool *pmemblk_open(const char *path, size_t bsize); PMEMblkpool *pmemblk_create(const char *path, size_t bsize, size_t poolsize, mode_t mode); void pmemblk_close(PMEMblkpool *pbp); int pmemblk_check(const char *path, size_t bsize); size_t pmemblk_bsize(PMEMblkpool *pbp); size_t pmemblk_nblock(PMEMblkpool *pbp); int pmemblk_read(PMEMblkpool *pbp, void *buf, off_t blockno); int pmemblk_write(PMEMblkpool *pbp, const void *buf, off_t blockno); int pmemblk_set_zero(PMEMblkpool *pbp, off_t blockno); int pmemblk_set_error(PMEMblkpool *pbp, off_t blockno); const char *pmemblk_check_version( unsigned major_required, unsigned minor_required); /* libpmemobj */ typedef ... va_list; typedef struct pmemobjpool PMEMobjpool; #define PMEMOBJ_MIN_POOL ... #define PMEMOBJ_MAX_ALLOC_SIZE ... typedef struct pmemoid { uint64_t pool_uuid_lo; uint64_t off; } PMEMoid; static const PMEMoid OID_NULL; enum pobj_tx_stage { TX_STAGE_NONE, TX_STAGE_WORK, TX_STAGE_ONCOMMIT, TX_STAGE_ONABORT, TX_STAGE_FINALLY, ... }; const char *pmemobj_errormsg(void); PMEMobjpool *pmemobj_open(const char *path, const char *layout); PMEMobjpool *pmemobj_create(const char *path, const char *layout, size_t poolsize, mode_t mode); void pmemobj_close(PMEMobjpool *pop); int pmemobj_check(const char *path, const char *layout); PMEMoid pmemobj_root(PMEMobjpool *pop, size_t size); size_t pmemobj_root_size(PMEMobjpool *pop); void *pmemobj_direct(PMEMoid oid); int pmemobj_tx_begin(PMEMobjpool *pop, void *env, va_list *); void pmemobj_tx_abort(int errnum); void pmemobj_tx_commit(void); int pmemobj_tx_end(void); int pmemobj_tx_add_range(PMEMoid oid, uint64_t off, size_t size); int pmemobj_tx_add_range_direct(const void *ptr, size_t size); PMEMoid pmemobj_tx_alloc(size_t size, uint64_t type_num); PMEMoid pmemobj_tx_zalloc(size_t size, uint64_t type_num); PMEMoid pmemobj_tx_realloc(PMEMoid oid, size_t size, uint64_t type_num); PMEMoid pmemobj_tx_zrealloc(PMEMoid oid, size_t size, uint64_t type_num); PMEMoid pmemobj_tx_strdup(const char *s, uint64_t type_num); int pmemobj_tx_free(PMEMoid oid); enum pobj_tx_stage pmemobj_tx_stage(void); PMEMoid pmemobj_first(PMEMobjpool *pop); PMEMoid pmemobj_next(PMEMoid oid); uint64_t pmemobj_type_num(PMEMoid oid); """ + pmemobj_structs) if __name__ == "__main__": ffi.compile()
{ "content_hash": "dafd978d84fac4d3a21d2d95ac3b9ce0", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 80, "avg_line_length": 34.84027777777778, "alnum_prop": 0.6340442495515248, "repo_name": "bitdancer/pynvm", "id": "36478ea10691caaa61860db30072826ba9388425", "size": "5017", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nvm/libex.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "102344" } ], "symlink_target": "" }
UIElement = {} UIElement.__index = UIElement setmetatable(UIElement, { __index = UIElement, __call = function (cls, ...) local self = setmetatable({}, cls) self:_init(...) return self end, }) function UIElement:_init(name, x, y, up, down, left, right, confirm, image, highlight, text, textXOffset, textYOffset) self.name = name self.x = x self.y = y self.up = up self.down = down self.left = left self.right = right self.confirm = confirm self.image = image self.highlight = highlight self.text = text self.textXOffset = textXOffset self.textYOffset = textYOffset end
{ "content_hash": "f063e73f6954ac3d26666934897e52c9", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 118, "avg_line_length": 19.0625, "alnum_prop": 0.6672131147540984, "repo_name": "daniel-david-gabriel/mystrust", "id": "3056fdde0c39d83ece93438aa3ebc4c95730bcb6", "size": "610", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lua/view/menu/uiElement.lua", "mode": "33188", "license": "mit", "language": [ { "name": "Lua", "bytes": "103122" } ], "symlink_target": "" }
#include <assert.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include "apr.h" #include "apr_general.h" #include "apr_proc_mutex.h" #include "apr_global_mutex.h" #include "apr_thread_proc.h" #if !APR_HAS_THREADS int main(void) { printf("This test requires APR thread support.\n"); return 0; } #else /* APR_HAS_THREADS */ static apr_thread_mutex_t *thread_mutex; static apr_proc_mutex_t *proc_mutex; static apr_global_mutex_t *global_mutex; static apr_pool_t *p; static volatile int counter; typedef enum {TEST_GLOBAL, TEST_PROC} test_mode_e; static void lock_init(apr_lockmech_e mech, test_mode_e test_mode) { if (test_mode == TEST_PROC) { assert(apr_proc_mutex_create(&proc_mutex, NULL, mech, p) == APR_SUCCESS); } else { assert(apr_global_mutex_create(&global_mutex, NULL, mech, p) == APR_SUCCESS); } } static void lock_destroy(test_mode_e test_mode) { if (test_mode == TEST_PROC) { assert(apr_proc_mutex_destroy(proc_mutex) == APR_SUCCESS); } else { assert(apr_global_mutex_destroy(global_mutex) == APR_SUCCESS); } } static void lock_grab(test_mode_e test_mode) { if (test_mode == TEST_PROC) { assert(apr_proc_mutex_lock(proc_mutex) == APR_SUCCESS); } else { assert(apr_global_mutex_lock(global_mutex) == APR_SUCCESS); } } static void lock_release(test_mode_e test_mode) { if (test_mode == TEST_PROC) { assert(apr_proc_mutex_unlock(proc_mutex) == APR_SUCCESS); } else { assert(apr_global_mutex_unlock(global_mutex) == APR_SUCCESS); } } static void * APR_THREAD_FUNC eachThread(apr_thread_t *id, void *p) { test_mode_e test_mode = (test_mode_e)p; lock_grab(test_mode); ++counter; assert(apr_thread_mutex_lock(thread_mutex) == APR_SUCCESS); assert(apr_thread_mutex_unlock(thread_mutex) == APR_SUCCESS); lock_release(test_mode); apr_thread_exit(id, 0); return NULL; } static void test_mech_mode(apr_lockmech_e mech, const char *mech_name, test_mode_e test_mode) { apr_thread_t *threads[20]; int numThreads = 5; int i; apr_status_t rv; printf("Trying %s mutexes with mechanism `%s'...\n", test_mode == TEST_GLOBAL ? "global" : "proc", mech_name); assert(numThreads <= sizeof(threads) / sizeof(threads[0])); assert(apr_pool_create(&p, NULL) == APR_SUCCESS); assert(apr_thread_mutex_create(&thread_mutex, 0, p) == APR_SUCCESS); assert(apr_thread_mutex_lock(thread_mutex) == APR_SUCCESS); lock_init(mech, test_mode); counter = 0; i = 0; while (i < numThreads) { rv = apr_thread_create(&threads[i], NULL, eachThread, (void *)test_mode, p); if (rv != APR_SUCCESS) { fprintf(stderr, "apr_thread_create->%d\n", rv); exit(1); } ++i; } apr_sleep(apr_time_from_sec(5)); if (test_mode == TEST_PROC) { printf(" Mutex mechanism `%s' is %sglobal in scope on this platform.\n", mech_name, counter == 1 ? "" : "not "); } else { if (counter != 1) { fprintf(stderr, "\n!!!apr_global_mutex operations are broken on this " "platform for mutex mechanism `%s'!\n" "They don't block out threads within the same process.\n", mech_name); fprintf(stderr, "counter value: %d\n", counter); exit(1); } else { printf(" no problems encountered...\n"); } } assert(apr_thread_mutex_unlock(thread_mutex) == APR_SUCCESS); i = 0; while (i < numThreads) { apr_status_t ignored; rv = apr_thread_join(&ignored, threads[i]); assert(rv == APR_SUCCESS); ++i; } lock_destroy(test_mode); apr_thread_mutex_destroy(thread_mutex); apr_pool_destroy(p); } static void test_mech(apr_lockmech_e mech, const char *mech_name) { test_mech_mode(mech, mech_name, TEST_PROC); test_mech_mode(mech, mech_name, TEST_GLOBAL); } int main(void) { struct { apr_lockmech_e mech; const char *mech_name; } lockmechs[] = { {APR_LOCK_DEFAULT, "default"} #if APR_HAS_FLOCK_SERIALIZE ,{APR_LOCK_FLOCK, "flock"} #endif #if APR_HAS_SYSVSEM_SERIALIZE ,{APR_LOCK_SYSVSEM, "sysvsem"} #endif #if APR_HAS_POSIXSEM_SERIALIZE ,{APR_LOCK_POSIXSEM, "posix"} #endif #if APR_HAS_FCNTL_SERIALIZE ,{APR_LOCK_FCNTL, "fcntl"} #endif #if APR_HAS_PROC_PTHREAD_SERIALIZE ,{APR_LOCK_PROC_PTHREAD, "proc_pthread"} #endif }; int i; assert(apr_initialize() == APR_SUCCESS); for (i = 0; i < sizeof(lockmechs) / sizeof(lockmechs[0]); i++) { test_mech(lockmechs[i].mech, lockmechs[i].mech_name); } apr_terminate(); return 0; } #endif /* APR_HAS_THREADS */
{ "content_hash": "1b95b8242acbf1dd28949187e4a9b9f3", "timestamp": "", "source": "github", "line_count": 205, "max_line_length": 80, "avg_line_length": 26.078048780487805, "alnum_prop": 0.542648709315376, "repo_name": "asimihsan/masspinger", "id": "f44bc3936cb6f4a2d1b6f5ee65a519829bc39dee", "size": "6158", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "deps/win32/apr/test/testmutexscope.c", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "5161319" }, { "name": "C++", "bytes": "2150895" }, { "name": "Java", "bytes": "2899" }, { "name": "Perl", "bytes": "37138" }, { "name": "Python", "bytes": "9749" }, { "name": "Shell", "bytes": "463105" } ], "symlink_target": "" }
control 'filter_lines_delete_between' do describe file('/tmp/delete_between') do it { should exist } its('content') { should_not match /^kernel/ } end describe matches('/tmp/delete_between', /crashkernel/) do its('count') { should eq 1 } end describe file_ext('/tmp/delete_between') do it { should have_correct_eol } its('size_lines') { should eq 18 } end end
{ "content_hash": "cb2ceaf0313947df1278ff54d6a631d4", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 59, "avg_line_length": 30.153846153846153, "alnum_prop": 0.6530612244897959, "repo_name": "someara/line-cookbook", "id": "492f50e68643967baf9e0172ef67bacb9834312d", "size": "440", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "test/integration/filter_lines/controls/filter_lines_delete_between.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ruby", "bytes": "27287" } ], "symlink_target": "" }
{% extends 'checkout/layout.html' %} {% block js %} <script type="text/javascript"> $(function() { var form = $('section.auth form'); var email = form.find('#id_email'); form.find('#id_email').focus(); form.submit(function(event) { if (email.val().length == 0) { event.preventDefault(); return false; } if (form.find('input[type="radio"]:checked').length == 0) { form.find('.row-password').css('display', 'table-row'); event.preventDefault(); return false; } }); form.find('input[type="radio"]').change(function(event) { var that = $(this); switch (that.val()) { case 'yes': form.find('.row-password-input').css('display', 'table-cell'); break; case 'no': form.find('.row-password-input').hide().removeAttr('value'); break; } }); }); </script> {% endblock %} {% block content %} <section class="auth"> <h1 style="">Авторизация</h1> <form action="." method="post">{% csrf_token %} <table> <tbody> <tr> <td colspan="2"> <h4>E-mail</h4> </td> </tr> <tr> <td class="row-label"> <label for="id_email">Введите адрес своей почты <span class="required">*</span> </label> </td> <td> <input type="email" id="id_email" name="email" {% if form.email.value %} value="{{ form.email.value }}"{% endif %}> <div class="field-hint">Мы отправим подтверждение вашего заказа на этот адрес</div> </td> </tr> <tr class="row-password{% if wrong_password or busy_email %} active{% endif %}"> <td colspan="2"> <h4>У вас есть пароль?</h4> </td> </tr> <tr class="row-password{% if wrong_password or busy_email %} active{% endif %}"> <td colspan="2" class="row-label row-radio"> <input type="radio" id="id_password_no" name="have_password" value="no"> <label for="id_password_no">Нет (аккаунт будет создан автоматически)</label> </td> </tr> <tr class="row-password{% if wrong_password or busy_email %} active{% endif %}"> <td class="row-label row-radio"> <input type="radio" id="id_password_yes" name="have_password" value="yes"> <label for="id_password_yes">Да, мой пароль:</label> </td> <td class="row-password-input{% if have_password %} active{% endif %}"> <input type="password" name="password"> </td> </tr> <tr class="row-password-errors"> <td colspan="2"> {% if wrong_password %} <p>Пожалуйста, проверьте свой пароль. <a href="{% url 'users.auth.remind' %}">Забыли</a>?</p> {% elif busy_email %} <p>Пользователь с таким e-mail уже существует. <a href="{% url 'users.auth.remind' %}">Напомнить пароль</a>?</p> {% endif %} </td> </tr> </tbody> </table> <button class="btn btn-primary"> Продолжить <span class="glyphicon glyphicon-chevron-right"></span> </button> </form> </section> {% endblock %}
{ "content_hash": "64aa9834d0753bf562841c0ad48a78af", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 144, "avg_line_length": 40.93333333333333, "alnum_prop": 0.3929734760353653, "repo_name": "Lisaveta-K/lisaveta-k.github.io", "id": "d25b2f4bd1faa330cbf7abf24e8d07f4d9568fc4", "size": "4527", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_site/tomat/apps/checkout/templates/checkout/steps/auth.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "159937" }, { "name": "HTML", "bytes": "275262" }, { "name": "JavaScript", "bytes": "34638" }, { "name": "Python", "bytes": "664204" } ], "symlink_target": "" }
<!doctype html> <html lang="en"> <head> <title>Code coverage report for utils/unique_set.js</title> <meta charset="utf-8"> <link rel="stylesheet" href="../prettify.css"> <style> body, html { margin:0; padding: 0; } body { font-family: Helvetica Neue, Helvetica,Arial; font-size: 10pt; } div.header, div.footer { background: #eee; padding: 1em; } div.header { z-index: 100; position: fixed; top: 0; border-bottom: 1px solid #666; width: 100%; } div.footer { border-top: 1px solid #666; } div.body { margin-top: 10em; } div.meta { font-size: 90%; text-align: center; } h1, h2, h3 { font-weight: normal; } h1 { font-size: 12pt; } h2 { font-size: 10pt; } pre { font-family: Consolas, Menlo, Monaco, monospace; margin: 0; padding: 0; line-height: 14px; font-size: 14px; -moz-tab-size: 2; -o-tab-size: 2; tab-size: 2; } div.path { font-size: 110%; } div.path a:link, div.path a:visited { color: #000; } table.coverage { border-collapse: collapse; margin:0; padding: 0 } table.coverage td { margin: 0; padding: 0; color: #111; vertical-align: top; } table.coverage td.line-count { width: 50px; text-align: right; padding-right: 5px; } table.coverage td.line-coverage { color: #777 !important; text-align: right; border-left: 1px solid #666; border-right: 1px solid #666; } table.coverage td.text { } table.coverage td span.cline-any { display: inline-block; padding: 0 5px; width: 40px; } table.coverage td span.cline-neutral { background: #eee; } table.coverage td span.cline-yes { background: #b5d592; color: #999; } table.coverage td span.cline-no { background: #fc8c84; } .cstat-yes { color: #111; } .cstat-no { background: #fc8c84; color: #111; } .fstat-no { background: #ffc520; color: #111 !important; } .cbranch-no { background: yellow !important; color: #111; } .cstat-skip { background: #ddd; color: #111; } .fstat-skip { background: #ddd; color: #111 !important; } .cbranch-skip { background: #ddd !important; color: #111; } .missing-if-branch { display: inline-block; margin-right: 10px; position: relative; padding: 0 4px; background: black; color: yellow; } .skip-if-branch { display: none; margin-right: 10px; position: relative; padding: 0 4px; background: #ccc; color: white; } .missing-if-branch .typ, .skip-if-branch .typ { color: inherit !important; } .entity, .metric { font-weight: bold; } .metric { display: inline-block; border: 1px solid #333; padding: 0.3em; background: white; } .metric small { font-size: 80%; font-weight: normal; color: #666; } div.coverage-summary table { border-collapse: collapse; margin: 3em; font-size: 110%; } div.coverage-summary td, div.coverage-summary table th { margin: 0; padding: 0.25em 1em; border-top: 1px solid #666; border-bottom: 1px solid #666; } div.coverage-summary th { text-align: left; border: 1px solid #666; background: #eee; font-weight: normal; } div.coverage-summary th.file { border-right: none !important; } div.coverage-summary th.pic { border-left: none !important; text-align: right; } div.coverage-summary th.pct { border-right: none !important; } div.coverage-summary th.abs { border-left: none !important; text-align: right; } div.coverage-summary td.pct { text-align: right; border-left: 1px solid #666; } div.coverage-summary td.abs { text-align: right; font-size: 90%; color: #444; border-right: 1px solid #666; } div.coverage-summary td.file { text-align: right; border-left: 1px solid #666; white-space: nowrap; } div.coverage-summary td.pic { min-width: 120px !important; } div.coverage-summary a:link { text-decoration: none; color: #000; } div.coverage-summary a:visited { text-decoration: none; color: #333; } div.coverage-summary a:hover { text-decoration: underline; } div.coverage-summary tfoot td { border-top: 1px solid #666; } div.coverage-summary .yui3-datatable-sort-indicator, div.coverage-summary .dummy-sort-indicator { height: 10px; width: 7px; display: inline-block; margin-left: 0.5em; } div.coverage-summary .yui3-datatable-sort-indicator { background: url("https://yui-s.yahooapis.com/3.6.0/build/datatable-sort/assets/skins/sam/sort-arrow-sprite.png") no-repeat scroll 0 0 transparent; } div.coverage-summary .yui3-datatable-sorted .yui3-datatable-sort-indicator { background-position: 0 -20px; } div.coverage-summary .yui3-datatable-sorted-desc .yui3-datatable-sort-indicator { background-position: 0 -10px; } .high { background: #b5d592 !important; } .medium { background: #ffe87c !important; } .low { background: #fc8c84 !important; } span.cover-fill, span.cover-empty { display:inline-block; border:1px solid #444; background: white; height: 12px; } span.cover-fill { background: #ccc; border-right: 1px solid #444; } span.cover-empty { background: white; border-left: none; } span.cover-full { border-right: none !important; } pre.prettyprint { border: none !important; padding: 0 !important; margin: 0 !important; } .com { color: #999 !important; } .ignore-none { color: #999; font-weight: normal; } </style> </head> <body> <div class="header high"> <h1>Code coverage report for <span class="entity">utils/unique_set.js</span></h1> <h2> Statements: <span class="metric">96.43% <small>(27 / 28)</small></span> &nbsp;&nbsp;&nbsp;&nbsp; Branches: <span class="metric">93.75% <small>(15 / 16)</small></span> &nbsp;&nbsp;&nbsp;&nbsp; Functions: <span class="metric">100% <small>(8 / 8)</small></span> &nbsp;&nbsp;&nbsp;&nbsp; Lines: <span class="metric">96.43% <small>(27 / 28)</small></span> &nbsp;&nbsp;&nbsp;&nbsp; Ignored: <span class="metric"><span class="ignore-none">none</span></span> &nbsp;&nbsp;&nbsp;&nbsp; </h2> <div class="path"><a href="../index.html">All files</a> &#187; <a href="index.html">utils/</a> &#187; unique_set.js</div> </div> <div class="body"> <pre><table class="coverage"> <tr><td class="line-count">1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121</td><td class="line-coverage"><span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">4</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">17</span> <span class="cline-any cline-yes">17</span> <span class="cline-any cline-yes">2</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">15</span> <span class="cline-any cline-yes">4</span> <span class="cline-any cline-yes">3</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">11</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">7</span> <span class="cline-any cline-yes">7</span> <span class="cline-any cline-no">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">7</span> <span class="cline-any cline-yes">5</span> <span class="cline-any cline-yes">5</span> <span class="cline-any cline-yes">3</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">5</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">2</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-yes">12</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-yes">1</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span> <span class="cline-any cline-neutral">&nbsp;</span></td><td class="text"><pre class="prettyprint lang-js">'use strict'; &nbsp; /** * @ngdoc service * @name utils.unique_set:UniqueSet * @function * * @description * This is used to maintain lists of userIds to socketIds and channelIds to socketIds */ exports.UniqueSet = (function() { &nbsp; function UniqueSet() { this.data = {}; } &nbsp; /** * @ngdoc service * @name utils.UniqueSet#add * @methodOf utils.unique_set:UniqueSet * @function * * @description * Add specific `key/value` set * * @param {String} key Key name * @param {Mixed} value Value to be assigned to the `key` */ UniqueSet.prototype.add = function(key, value) { var set; if (!((key != null) &amp;&amp; (value != null))) { return false; } if (set = this.data[key]) { if (!(set.indexOf(value) &gt;= 0)) { return set.push(value); } } else { return this.data[key] = [value]; } }; &nbsp; /** * @ngdoc service * @name utils.UniqueSet#remove * @methodOf utils.unique_set:UniqueSet * @function * * @description * Remove specific `key/value` set * * @param {String} key Key name * @param {Mixed} value Value related to the `key` * @return {Boolean} Remove state */ UniqueSet.prototype.remove = function(key, value) { var i; <span class="missing-if-branch" title="if path not taken" >I</span>if (this.data[key] === void 0) { <span class="cstat-no" title="statement not covered" > return;</span> } if ((i = this.data[key].indexOf(value)) &gt;= 0) { this.data[key].splice(i, 1); if (this.data[key].length === 0) { return delete this.data[key]; } } }; &nbsp; /** * @ngdoc service * @name utils.UniqueSet#removeFromAll * @methodOf utils.unique_set:UniqueSet * @function * * @description * Remove all specific `key/value` sets accotding to `value` * * @param {Mixed} value Value as a link for removal all the sets * @return {Boolean} Removal status */ UniqueSet.prototype.removeFromAll = function(value) { var _this = this; return this.keys().forEach(function(key) { return _this.remove(key, value); }); }; &nbsp; /** * @ngdoc service * @name utils.UniqueSet#keys * @methodOf utils.unique_set:UniqueSet * @function * * @description * Returns array of keys * * @return {Array} Array of all the keys names */ UniqueSet.prototype.keys = function() { return Object.keys(this.data); }; &nbsp; /** * @ngdoc service * @name utils.UniqueSet#members * @methodOf utils.unique_set:UniqueSet * @function * * @description * Returns array with all the values by certain `key` * * @return {Array} Array of all the keys for specified `key` */ UniqueSet.prototype.members = function(key) { return this.data[key] || []; }; &nbsp; return UniqueSet; &nbsp; })(); &nbsp;</pre></td></tr> </table></pre> </div> <div class="footer"> <div class="meta">Generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Sat Oct 04 2014 10:34:07 GMT+0100 (BST)</div> </div> <script src="../prettify.js"></script> <script src="https://yui-s.yahooapis.com/3.6.0/build/yui/yui-min.js"></script> <script> YUI().use('datatable', function (Y) { var formatters = { pct: function (o) { o.className += o.record.get('classes')[o.column.key]; try { return o.value.toFixed(2) + '%'; } catch (ex) { return o.value + '%'; } }, html: function (o) { o.className += o.record.get('classes')[o.column.key]; return o.record.get(o.column.key + '_html'); } }, defaultFormatter = function (o) { o.className += o.record.get('classes')[o.column.key]; return o.value; }; function getColumns(theadNode) { var colNodes = theadNode.all('tr th'), cols = [], col; colNodes.each(function (colNode) { col = { key: colNode.getAttribute('data-col'), label: colNode.get('innerHTML') || ' ', sortable: !colNode.getAttribute('data-nosort'), className: colNode.getAttribute('class'), type: colNode.getAttribute('data-type'), allowHTML: colNode.getAttribute('data-html') === 'true' || colNode.getAttribute('data-fmt') === 'html' }; col.formatter = formatters[colNode.getAttribute('data-fmt')] || defaultFormatter; cols.push(col); }); return cols; } function getRowData(trNode, cols) { var tdNodes = trNode.all('td'), i, row = { classes: {} }, node, name; for (i = 0; i < cols.length; i += 1) { name = cols[i].key; node = tdNodes.item(i); row[name] = node.getAttribute('data-value') || node.get('innerHTML'); row[name + '_html'] = node.get('innerHTML'); row.classes[name] = node.getAttribute('class'); //Y.log('Name: ' + name + '; Value: ' + row[name]); if (cols[i].type === 'number') { row[name] = row[name] * 1; } } //Y.log(row); return row; } function getData(tbodyNode, cols) { var data = []; tbodyNode.all('tr').each(function (trNode) { data.push(getRowData(trNode, cols)); }); return data; } function replaceTable(node) { if (!node) { return; } var cols = getColumns(node.one('thead')), data = getData(node.one('tbody'), cols), table, parent = node.get('parentNode'); table = new Y.DataTable({ columns: cols, data: data, sortBy: 'file' }); parent.set('innerHTML', ''); table.render(parent); } Y.on('domready', function () { replaceTable(Y.one('div.coverage-summary table')); if (typeof prettyPrint === 'function') { prettyPrint(); } }); }); </script> </body> </html>
{ "content_hash": "687727cb906684f98adbd8f162666ff6", "timestamp": "", "source": "github", "line_count": 682, "max_line_length": 158, "avg_line_length": 30.134897360703814, "alnum_prop": 0.5840307512650836, "repo_name": "rybon/Remocial", "id": "dc15f2cb951ad5359dca54cb87a5f33887e15c40", "size": "20552", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/socketstream/coverage/lcov-report/utils/unique_set.js.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "33624" }, { "name": "CoffeeScript", "bytes": "63019" }, { "name": "JavaScript", "bytes": "30503" } ], "symlink_target": "" }
package org.apache.ignite.testsuites; import java.util.Set; import junit.framework.TestSuite; import org.apache.ignite.internal.ComputeJobCancelWithServiceSelfTest; import org.apache.ignite.internal.GridCommunicationSelfTest; import org.apache.ignite.internal.GridDiscoveryEventSelfTest; import org.apache.ignite.internal.GridDiscoverySelfTest; import org.apache.ignite.internal.GridFailedInputParametersSelfTest; import org.apache.ignite.internal.GridHomePathSelfTest; import org.apache.ignite.internal.GridKernalConcurrentAccessStopSelfTest; import org.apache.ignite.internal.IgniteConcurrentEntryProcessorAccessStopTest; import org.apache.ignite.internal.GridListenActorSelfTest; import org.apache.ignite.internal.GridLocalEventListenerSelfTest; import org.apache.ignite.internal.GridNodeFilterSelfTest; import org.apache.ignite.internal.GridNodeLocalSelfTest; import org.apache.ignite.internal.GridNodeVisorAttributesSelfTest; import org.apache.ignite.internal.GridRuntimeExceptionSelfTest; import org.apache.ignite.internal.GridSameVmStartupSelfTest; import org.apache.ignite.internal.GridSpiExceptionSelfTest; import org.apache.ignite.internal.GridVersionSelfTest; import org.apache.ignite.internal.IgniteUpdateNotifierPerClusterSettingSelfTest; import org.apache.ignite.internal.managers.GridManagerStopSelfTest; import org.apache.ignite.internal.managers.communication.GridCommunicationSendMessageSelfTest; import org.apache.ignite.internal.managers.deployment.GridDeploymentManagerStopSelfTest; import org.apache.ignite.internal.managers.discovery.GridDiscoveryManagerAliveCacheSelfTest; import org.apache.ignite.internal.managers.discovery.GridDiscoveryManagerAttributesSelfTest; import org.apache.ignite.internal.managers.discovery.GridDiscoveryManagerSelfTest; import org.apache.ignite.internal.managers.discovery.IgniteTopologyPrintFormatSelfTest; import org.apache.ignite.internal.managers.events.GridEventStorageManagerSelfTest; import org.apache.ignite.internal.managers.swapspace.GridSwapSpaceManagerSelfTest; import org.apache.ignite.internal.processors.cluster.GridAddressResolverSelfTest; import org.apache.ignite.internal.processors.cluster.GridUpdateNotifierSelfTest; import org.apache.ignite.internal.processors.port.GridPortProcessorSelfTest; import org.apache.ignite.internal.processors.service.GridServiceClientNodeTest; import org.apache.ignite.internal.processors.service.GridServicePackagePrivateSelfTest; import org.apache.ignite.internal.processors.service.GridServiceProcessorMultiNodeConfigSelfTest; import org.apache.ignite.internal.processors.service.GridServiceProcessorMultiNodeSelfTest; import org.apache.ignite.internal.processors.service.GridServiceProcessorProxySelfTest; import org.apache.ignite.internal.processors.service.GridServiceProcessorSingleNodeSelfTest; import org.apache.ignite.internal.processors.service.GridServiceProcessorStopSelfTest; import org.apache.ignite.internal.processors.service.GridServiceProxyClientReconnectSelfTest; import org.apache.ignite.internal.processors.service.GridServiceProxyNodeStopSelfTest; import org.apache.ignite.internal.processors.service.GridServiceReassignmentSelfTest; import org.apache.ignite.internal.processors.service.GridServiceSerializationSelfTest; import org.apache.ignite.internal.processors.service.IgniteServiceDeployment2ClassLoadersDefaultMarshallerTest; import org.apache.ignite.internal.processors.service.IgniteServiceDeployment2ClassLoadersJdkMarshallerTest; import org.apache.ignite.internal.processors.service.IgniteServiceDeployment2ClassLoadersOptimizedMarshallerTest; import org.apache.ignite.internal.processors.service.IgniteServiceDeploymentClassLoadingDefaultMarshallerTest; import org.apache.ignite.internal.processors.service.IgniteServiceDeploymentClassLoadingJdkMarshallerTest; import org.apache.ignite.internal.processors.service.IgniteServiceDeploymentClassLoadingOptimizedMarshallerTest; import org.apache.ignite.internal.processors.service.IgniteServiceReassignmentTest; import org.apache.ignite.internal.processors.service.ServicePredicateAccessCacheTest; import org.apache.ignite.internal.util.GridStartupWithSpecifiedWorkDirectorySelfTest; import org.apache.ignite.internal.util.GridStartupWithUndefinedIgniteHomeSelfTest; import org.apache.ignite.spi.communication.GridCacheMessageSelfTest; import org.apache.ignite.testframework.GridTestUtils; /** * Kernal self test suite. */ public class IgniteKernalSelfTestSuite extends TestSuite { /** * @return Kernal test suite. * @throws Exception If failed. */ public static TestSuite suite() throws Exception { return suite(null); } /** * @param ignoredTests Tests don't include in the execution. * @return Test suite. * @throws Exception Thrown in case of the failure. */ public static TestSuite suite(Set<Class> ignoredTests) throws Exception { TestSuite suite = new TestSuite("Ignite Kernal Test Suite"); suite.addTestSuite(GridSameVmStartupSelfTest.class); suite.addTestSuite(GridSpiExceptionSelfTest.class); suite.addTestSuite(GridRuntimeExceptionSelfTest.class); suite.addTestSuite(GridFailedInputParametersSelfTest.class); suite.addTestSuite(GridNodeFilterSelfTest.class); suite.addTestSuite(GridNodeVisorAttributesSelfTest.class); suite.addTestSuite(GridDiscoverySelfTest.class); suite.addTestSuite(GridCommunicationSelfTest.class); suite.addTestSuite(GridEventStorageManagerSelfTest.class); suite.addTestSuite(GridSwapSpaceManagerSelfTest.class); suite.addTestSuite(GridCommunicationSendMessageSelfTest.class); suite.addTestSuite(GridCacheMessageSelfTest.class); suite.addTestSuite(GridDeploymentManagerStopSelfTest.class); suite.addTestSuite(GridManagerStopSelfTest.class); suite.addTestSuite(GridDiscoveryManagerAttributesSelfTest.RegularDiscovery.class); suite.addTestSuite(GridDiscoveryManagerAttributesSelfTest.ClientDiscovery.class); suite.addTestSuite(GridDiscoveryManagerAliveCacheSelfTest.class); suite.addTestSuite(GridDiscoveryManagerSelfTest.RegularDiscovery.class); suite.addTestSuite(GridDiscoveryManagerSelfTest.ClientDiscovery.class); suite.addTestSuite(GridDiscoveryEventSelfTest.class); suite.addTestSuite(GridPortProcessorSelfTest.class); suite.addTestSuite(GridHomePathSelfTest.class); GridTestUtils.addTestIfNeeded(suite, GridStartupWithSpecifiedWorkDirectorySelfTest.class, ignoredTests); suite.addTestSuite(GridStartupWithUndefinedIgniteHomeSelfTest.class); GridTestUtils.addTestIfNeeded(suite, GridVersionSelfTest.class, ignoredTests); suite.addTestSuite(GridListenActorSelfTest.class); suite.addTestSuite(GridNodeLocalSelfTest.class); suite.addTestSuite(GridKernalConcurrentAccessStopSelfTest.class); suite.addTestSuite(IgniteConcurrentEntryProcessorAccessStopTest.class); suite.addTestSuite(GridUpdateNotifierSelfTest.class); suite.addTestSuite(GridAddressResolverSelfTest.class); suite.addTestSuite(IgniteUpdateNotifierPerClusterSettingSelfTest.class); suite.addTestSuite(GridLocalEventListenerSelfTest.class); suite.addTestSuite(IgniteTopologyPrintFormatSelfTest.class); suite.addTestSuite(ComputeJobCancelWithServiceSelfTest.class); // Managed Services. suite.addTestSuite(GridServiceProcessorSingleNodeSelfTest.class); suite.addTestSuite(GridServiceProcessorMultiNodeSelfTest.class); suite.addTestSuite(GridServiceProcessorMultiNodeConfigSelfTest.class); suite.addTestSuite(GridServiceProcessorProxySelfTest.class); suite.addTestSuite(GridServiceReassignmentSelfTest.class); suite.addTestSuite(GridServiceClientNodeTest.class); suite.addTestSuite(GridServiceProcessorStopSelfTest.class); suite.addTestSuite(ServicePredicateAccessCacheTest.class); suite.addTestSuite(GridServicePackagePrivateSelfTest.class); suite.addTestSuite(GridServiceSerializationSelfTest.class); suite.addTestSuite(GridServiceProxyNodeStopSelfTest.class); suite.addTestSuite(GridServiceProxyClientReconnectSelfTest.class); suite.addTestSuite(IgniteServiceReassignmentTest.class); suite.addTestSuite(IgniteServiceDeploymentClassLoadingDefaultMarshallerTest.class); suite.addTestSuite(IgniteServiceDeploymentClassLoadingOptimizedMarshallerTest.class); suite.addTestSuite(IgniteServiceDeploymentClassLoadingJdkMarshallerTest.class); suite.addTestSuite(IgniteServiceDeployment2ClassLoadersDefaultMarshallerTest.class); suite.addTestSuite(IgniteServiceDeployment2ClassLoadersOptimizedMarshallerTest.class); suite.addTestSuite(IgniteServiceDeployment2ClassLoadersJdkMarshallerTest.class); return suite; } }
{ "content_hash": "97d0c793f364049fa71cc4483f444568", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 113, "avg_line_length": 63.255319148936174, "alnum_prop": 0.836192398250925, "repo_name": "kromulan/ignite", "id": "b91fff42e40f09a9f0c18a1590c6825326ca525a", "size": "9721", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "modules/core/src/test/java/org/apache/ignite/testsuites/IgniteKernalSelfTestSuite.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "38221" }, { "name": "C", "bytes": "7524" }, { "name": "C#", "bytes": "3824144" }, { "name": "C++", "bytes": "1969202" }, { "name": "CSS", "bytes": "98406" }, { "name": "Groovy", "bytes": "15092" }, { "name": "HTML", "bytes": "411123" }, { "name": "Java", "bytes": "23974499" }, { "name": "JavaScript", "bytes": "963263" }, { "name": "M4", "bytes": "5528" }, { "name": "Makefile", "bytes": "98604" }, { "name": "PHP", "bytes": "11079" }, { "name": "PowerShell", "bytes": "6281" }, { "name": "Scala", "bytes": "680703" }, { "name": "Shell", "bytes": "544923" }, { "name": "Smalltalk", "bytes": "1908" } ], "symlink_target": "" }
/* Variables */ #define os_psq ((P_PSQ)&os_fifo) extern int os_tick_irqn; /* Functions */ extern U32 rt_suspend (void); extern void rt_resume (U32 sleep_time); extern void rt_tsk_lock (void); extern void rt_tsk_unlock (void); extern void rt_psh_req (void); extern void rt_pop_req (void); extern void rt_systick (void); extern void rt_stk_check (void); /*---------------------------------------------------------------------------- * end of file *---------------------------------------------------------------------------*/
{ "content_hash": "513bde335cbc99e4119a03aac7b86003", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 79, "avg_line_length": 27.6, "alnum_prop": 0.4673913043478261, "repo_name": "AtmelUniversityFrance/SAMD21-XPRO", "id": "f56c8342143e7dbe91a1d6fc3c48c16a0c082911", "size": "2578", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Examples/CMSIS/CMSIS_RTX/SRC/rt_System.h", "mode": "33188", "license": "bsd-2-clause", "language": [], "symlink_target": "" }
require 'spec_helper' shared_context 'kitchen config' do let(:kitchen_config) { double(Kitchen::Config) } let(:kitchen_instances) { double('instances') } let(:foo) { double('foo', name: 'foo') } let(:bar) { double('bar', name: 'bar') } before do allow(foo).to receive_messages( verify: true, destroy: true ) allow(bar).to receive_messages( converge: true, destroy: true ) allow(kitchen_instances).to receive(:get) .with('foo') .and_return(foo) allow(kitchen_instances).to receive(:get) .with('bar') .and_return(bar) allow(kitchen_config).to receive(:instances).and_return(kitchen_instances) allow(Kitchen::Config).to receive(:new).and_return(kitchen_config) end end describe Cocina::Config do context 'when creating a new config' do context 'with no instance configuration' do let(:config) { Cocina::Config.new('foobar') } before do allow(IO).to receive(:read).with('foobar').and_return('') end it 'reads configuration from a file' do expect(config.cocinafile).to eq('foobar') end it 'has an empty instance list' do expect(config.instances).to eq([]) end end context 'with instance configuration' do let(:content) { "instance 'foo' do\n depends 'bar'\nend" } let(:config) { Cocina::Config.new('foobar') } let(:baz) { double('baz', name: 'baz') } include_context 'kitchen config' before do allow(IO).to receive(:read).with('foobar').and_return(content) end it 'has the correct instance list' do instances = config.instances first = instances.first expect(instances.length).to eq(2) expect(first.name).to eq('foo') end it 'exposes the instances' do instance = config['foo'] expect(instance).to be_a(Cocina::Instance) expect(instance.name).to eq('foo') expect(instance.dependencies).to eq(['bar']) end end context 'with nested dependencies' do let(:content) do String.new.tap do |cfg| cfg << "instance 'foo' do\n depends 'bar'\nend\n" cfg << "instance 'bar' do\n depends 'baz'\nend\n" end end let(:config) { Cocina::Config.new('foobar') } let(:baz) { double('baz', name: 'baz') } include_context 'kitchen config' before do allow(baz).to receive_messages( converge: true, destroy: true ) allow(kitchen_instances).to receive(:get) .with('baz') .and_return(baz) allow(IO).to receive(:read).with('foobar').and_return(content) end it 'has the correct instance list' do instances = config.instances expect(instances.length).to eq(3) expect(instances.map(&:name)).to eq(['foo', 'bar', 'baz']) end end end end
{ "content_hash": "a47ce67e245e85afb3cc8500d3657bb3", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 78, "avg_line_length": 28.339805825242717, "alnum_prop": 0.5943816375471052, "repo_name": "brandocorp/cocina", "id": "1a0dc5512bb36e3c31c62f8c7d6ad5ce0ede3323", "size": "2919", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/cocina/config_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "21852" } ], "symlink_target": "" }
using UnityEngine; using System.Collections; using System.Collections.Generic; // Require a character controller to be attached to the same game object [RequireComponent(typeof(CharacterController))] [AddComponentMenu("Character/Character Motor")] public class CharacterMotor : MonoBehaviour { // Does this script currently respond to input? bool canControl = true; bool useFixedUpdate = true; // For the next variables, [System.NonSerialized] tells Unity to not serialize the variable or show it in the inspector view. // Very handy for organization! // The current global direction we want the character to move in. [System.NonSerialized] public Vector3 inputMoveDirection = Vector3.zero; // Is the jump button held down? We use this interface instead of checking // for the jump button directly so this script can also be used by AIs. [System.NonSerialized] public bool inputJump = false; [System.Serializable] public class CharacterMotorMovement { // The maximum horizontal speed when moving public float maxForwardSpeed = 3.0f; public float maxSidewaysSpeed = 2.0f; public float maxBackwardsSpeed = 2.0f; // Curve for multiplying speed based on slope(negative = downwards) public AnimationCurve slopeSpeedMultiplier = new AnimationCurve(new Keyframe(-90, 1), new Keyframe(0, 1), new Keyframe(90, 0)); // How fast does the character change speeds? Higher is faster. public float maxGroundAcceleration = 30.0f; public float maxAirAcceleration = 20.0f; // The gravity for the character public float gravity = 9.81f; public float maxFallSpeed = 20.0f; // For the next variables, [System.NonSerialized] tells Unity to not serialize the variable or show it in the inspector view. // Very handy for organization! // The last collision flags returned from controller.Move [System.NonSerialized] public CollisionFlags collisionFlags; // We will keep track of the character's current velocity, [System.NonSerialized] public Vector3 velocity; // This keeps track of our current velocity while we're not grounded [System.NonSerialized] public Vector3 frameVelocity = Vector3.zero; [System.NonSerialized] public Vector3 hitPoint = Vector3.zero; [System.NonSerialized] public Vector3 lastHitPoint = new Vector3(Mathf.Infinity, 0, 0); } public CharacterMotorMovement movement = new CharacterMotorMovement(); public enum MovementTransferOnJump { None, // The jump is not affected by velocity of floor at all. InitTransfer, // Jump gets its initial velocity from the floor, then gradualy comes to a stop. PermaTransfer, // Jump gets its initial velocity from the floor, and keeps that velocity until landing. PermaLocked // Jump is relative to the movement of the last touched floor and will move together with that floor. } // We will contain all the jumping related variables in one helper class for clarity. [System.Serializable] public class CharacterMotorJumping { // Can the character jump? public bool enabled = true; // How high do we jump when pressing jump and letting go immediately public float baseHeight = 1.0f; // We add extraHeight units(meters) on top when holding the button down longer while jumping public float extraHeight = 4.1f; // How much does the character jump out perpendicular to the surface on walkable surfaces? // 0 means a fully vertical jump and 1 means fully perpendicular. public float perpAmount = 0.0f; // How much does the character jump out perpendicular to the surface on too steep surfaces? // 0 means a fully vertical jump and 1 means fully perpendicular. public float steepPerpAmount = 0.5f; // For the next variables, [System.NonSerialized] tells Unity to not serialize the variable or show it in the inspector view. // Very handy for organization! // Are we jumping?(Initiated with jump button and not grounded yet) // To see ifwe are just in the air(initiated by jumping OR falling) see the grounded variable. [System.NonSerialized] public bool jumping = false; [System.NonSerialized] public bool holdingJumpButton = false; // the time we jumped at(Used to determine for how long to apply extra jump power after jumping.) [System.NonSerialized] public float lastStartTime = 0.0f; [System.NonSerialized] public float lastButtonDownTime = -100.0f; [System.NonSerialized] public Vector3 jumpDir = Vector3.up; } public CharacterMotorJumping jumping = new CharacterMotorJumping(); [System.Serializable] public class CharacterMotorMovingPlatform { public bool enabled = true; public MovementTransferOnJump movementTransfer = MovementTransferOnJump.PermaTransfer; [System.NonSerialized] public Transform hitPlatform; [System.NonSerialized] public Transform activePlatform; [System.NonSerialized] public Vector3 activeLocalPoint; [System.NonSerialized] public Vector3 activeGlobalPoint; [System.NonSerialized] public Quaternion activeLocalRotation; [System.NonSerialized] public Quaternion activeGlobalRotation; [System.NonSerialized] public Matrix4x4 lastMatrix; [System.NonSerialized] public Vector3 platformVelocity; [System.NonSerialized] public bool newPlatform; } public CharacterMotorMovingPlatform movingPlatform = new CharacterMotorMovingPlatform(); [System.Serializable] public class CharacterMotorSliding { // Does the character slide on too steep surfaces? public bool enabled = true; // How fast does the character slide on steep surfaces? public float slidingSpeed = 15.0f; // How much can the player control the sliding direction? // ifthe value is 0.5 the player can slide sideways with half the speed of the downwards sliding speed. public float sidewaysControl = 1.0f; // How much can the player influence the sliding speed? // ifthe value is 0.5 the player can speed the sliding up to 150% or slow it down to 50%. public float speedControl = 0.4f; } public CharacterMotorSliding sliding = new CharacterMotorSliding(); [System.NonSerialized] public bool grounded = true; [System.NonSerialized] public Vector3 groundNormal = Vector3.zero; private Vector3 lastGroundNormal = Vector3.zero; private Transform tr; private CharacterController controller; void Awake() { controller = GetComponent<CharacterController>(); tr = transform; } private void UpdateFunction() { // We copy the actual velocity into a temporary variable that we can manipulate. Vector3 velocity = movement.velocity; // Update velocity based on input velocity = ApplyInputVelocityChange(velocity); // Apply gravity and jumping force velocity = ApplyGravityAndJumping(velocity); // Moving platform support Vector3 moveDistance = Vector3.zero; if (MoveWithPlatform()) { Vector3 newGlobalPoint = movingPlatform.activePlatform.TransformPoint(movingPlatform.activeLocalPoint); moveDistance = (newGlobalPoint - movingPlatform.activeGlobalPoint); if (moveDistance != Vector3.zero) controller.Move(moveDistance); // Support moving platform rotation as well: Quaternion newGlobalRotation = movingPlatform.activePlatform.rotation * movingPlatform.activeLocalRotation; Quaternion rotationDiff = newGlobalRotation * Quaternion.Inverse(movingPlatform.activeGlobalRotation); var yRotation = rotationDiff.eulerAngles.y; if (yRotation != 0) { // Prevent rotation of the local up vector tr.Rotate(0, yRotation, 0); } } // Save lastPosition for velocity calculation. Vector3 lastPosition = tr.position; // We always want the movement to be framerate independent. Multiplying by Time.deltaTime does this. Vector3 currentMovementOffset = velocity * Time.deltaTime; // Find out how much we need to push towards the ground to avoid loosing grouning // when walking down a step or over a sharp change in slope. float pushDownOffset = Mathf.Max(controller.stepOffset, new Vector3(currentMovementOffset.x, 0, currentMovementOffset.z).magnitude); if (grounded) currentMovementOffset -= pushDownOffset * Vector3.up; // Reset variables that will be set by collision function movingPlatform.hitPlatform = null; groundNormal = Vector3.zero; // Move our character! movement.collisionFlags = controller.Move(currentMovementOffset); movement.lastHitPoint = movement.hitPoint; lastGroundNormal = groundNormal; if (movingPlatform.enabled && movingPlatform.activePlatform != movingPlatform.hitPlatform) { if (movingPlatform.hitPlatform != null) { movingPlatform.activePlatform = movingPlatform.hitPlatform; movingPlatform.lastMatrix = movingPlatform.hitPlatform.localToWorldMatrix; movingPlatform.newPlatform = true; } } // Calculate the velocity based on the current and previous position. // This means our velocity will only be the amount the character actually moved as a result of collisions. Vector3 oldHVelocity = new Vector3(velocity.x, 0, velocity.z); movement.velocity = (tr.position - lastPosition) / Time.deltaTime; Vector3 newHVelocity = new Vector3(movement.velocity.x, 0, movement.velocity.z); // The CharacterController can be moved in unwanted directions when colliding with things. // We want to prevent this from influencing the recorded velocity. if (oldHVelocity == Vector3.zero) { movement.velocity = new Vector3(0, movement.velocity.y, 0); } else { float projectedNewVelocity = Vector3.Dot(newHVelocity, oldHVelocity) / oldHVelocity.sqrMagnitude; movement.velocity = oldHVelocity * Mathf.Clamp01(projectedNewVelocity) + movement.velocity.y * Vector3.up; } if (movement.velocity.y < velocity.y - 0.001) { if (movement.velocity.y < 0) { // Something is forcing the CharacterController down faster than it should. // Ignore this movement.velocity.y = velocity.y; } else { // The upwards movement of the CharacterController has been blocked. // This is treated like a ceiling collision - stop further jumping here. jumping.holdingJumpButton = false; } } // We were grounded but just loosed grounding if (grounded && !IsGroundedTest()) { grounded = false; // Apply inertia from platform if (movingPlatform.enabled && (movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer || movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer) ) { movement.frameVelocity = movingPlatform.platformVelocity; movement.velocity += movingPlatform.platformVelocity; } SendMessage("OnFall", SendMessageOptions.DontRequireReceiver); // We pushed the character down to ensure it would stay on the ground ifthere was any. // But there wasn't so now we cancel the downwards offset to make the fall smoother. tr.position += pushDownOffset * Vector3.up; } // We were not grounded but just landed on something else if (!grounded && IsGroundedTest()) { grounded = true; jumping.jumping = false; SubtractNewPlatformVelocity(); SendMessage("OnLand", SendMessageOptions.DontRequireReceiver); } // Moving platforms support if (MoveWithPlatform()) { // Use the center of the lower half sphere of the capsule as reference point. // This works best when the character is standing on moving tilting platforms. movingPlatform.activeGlobalPoint = tr.position + Vector3.up * (controller.center.y - controller.height * 0.5f + controller.radius); movingPlatform.activeLocalPoint = movingPlatform.activePlatform.InverseTransformPoint(movingPlatform.activeGlobalPoint); // Support moving platform rotation as well: movingPlatform.activeGlobalRotation = tr.rotation; movingPlatform.activeLocalRotation = Quaternion.Inverse(movingPlatform.activePlatform.rotation) * movingPlatform.activeGlobalRotation; } } void FixedUpdate() { if (movingPlatform.enabled) { if (movingPlatform.activePlatform != null) { if (!movingPlatform.newPlatform) { // unused: Vector3 lastVelocity = movingPlatform.platformVelocity; movingPlatform.platformVelocity = ( movingPlatform.activePlatform.localToWorldMatrix.MultiplyPoint3x4(movingPlatform.activeLocalPoint) - movingPlatform.lastMatrix.MultiplyPoint3x4(movingPlatform.activeLocalPoint) ) / Time.deltaTime; } movingPlatform.lastMatrix = movingPlatform.activePlatform.localToWorldMatrix; movingPlatform.newPlatform = false; } else { movingPlatform.platformVelocity = Vector3.zero; } } if (useFixedUpdate) UpdateFunction(); } void Update() { if (!useFixedUpdate) UpdateFunction(); } private Vector3 ApplyInputVelocityChange(Vector3 velocity) { if (!canControl) inputMoveDirection = Vector3.zero; // Find desired velocity Vector3 desiredVelocity; if (grounded && TooSteep()) { // The direction we're sliding in desiredVelocity = new Vector3(groundNormal.x, 0, groundNormal.z).normalized; // Find the input movement direction projected onto the sliding direction var projectedMoveDir = Vector3.Project(inputMoveDirection, desiredVelocity); // Add the sliding direction, the spped control, and the sideways control vectors desiredVelocity = desiredVelocity + projectedMoveDir * sliding.speedControl + (inputMoveDirection - projectedMoveDir) * sliding.sidewaysControl; // Multiply with the sliding speed desiredVelocity *= sliding.slidingSpeed; } else desiredVelocity = GetDesiredHorizontalVelocity(); if (movingPlatform.enabled && movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer) { desiredVelocity += movement.frameVelocity; desiredVelocity.y = 0; } if (grounded) desiredVelocity = AdjustGroundVelocityToNormal(desiredVelocity, groundNormal); else velocity.y = 0; // Enforce max velocity change float maxVelocityChange = GetMaxAcceleration(grounded) * Time.deltaTime; Vector3 velocityChangeVector = (desiredVelocity - velocity); if (velocityChangeVector.sqrMagnitude > maxVelocityChange * maxVelocityChange) { velocityChangeVector = velocityChangeVector.normalized * maxVelocityChange; } // ifwe're in the air and don't have control, don't apply any velocity change at all. // ifwe're on the ground and don't have control we do apply it - it will correspond to friction. if (grounded || canControl) velocity += velocityChangeVector; if (grounded) { // When going uphill, the CharacterController will automatically move up by the needed amount. // Not moving it upwards manually prevent risk of lifting off from the ground. // When going downhill, DO move down manually, as gravity is not enough on steep hills. velocity.y = Mathf.Min(velocity.y, 0); } return velocity; } private Vector3 ApplyGravityAndJumping(Vector3 velocity) { if (!inputJump || !canControl) { jumping.holdingJumpButton = false; jumping.lastButtonDownTime = -100; } if (inputJump && jumping.lastButtonDownTime < 0 && canControl) jumping.lastButtonDownTime = Time.time; if (grounded) velocity.y = Mathf.Min(0, velocity.y) - movement.gravity * Time.deltaTime; else { velocity.y = movement.velocity.y - movement.gravity * Time.deltaTime; // When jumping up we don't apply gravity for some time when the user is holding the jump button. // This gives more control over jump height by pressing the button longer. if (jumping.jumping && jumping.holdingJumpButton) { // Calculate the duration that the extra jump force should have effect. // ifwe're still less than that duration after the jumping time, apply the force. if (Time.time < jumping.lastStartTime + jumping.extraHeight / CalculateJumpVerticalSpeed(jumping.baseHeight)) { // Negate the gravity we just applied, except we push in jumpDir rather than jump upwards. velocity += jumping.jumpDir * movement.gravity * Time.deltaTime; } } // Make sure we don't fall any faster than maxFallSpeed. This gives our character a terminal velocity. velocity.y = Mathf.Max(velocity.y, -movement.maxFallSpeed); } if (grounded) { // Jump only ifthe jump button was pressed down in the last 0.2 seconds. // We use this check instead of checking ifit's pressed down right now // because players will often try to jump in the exact moment when hitting the ground after a jump // and ifthey hit the button a fraction of a second too soon and no new jump happens as a consequence, // it's confusing and it feels like the game is buggy. if (jumping.enabled && canControl && (Time.time - jumping.lastButtonDownTime < 0.2)) { grounded = false; jumping.jumping = true; jumping.lastStartTime = Time.time; jumping.lastButtonDownTime = -100; jumping.holdingJumpButton = true; // Calculate the jumping direction if (TooSteep()) jumping.jumpDir = Vector3.Slerp(Vector3.up, groundNormal, jumping.steepPerpAmount); else jumping.jumpDir = Vector3.Slerp(Vector3.up, groundNormal, jumping.perpAmount); // Apply the jumping force to the velocity. Cancel any vertical velocity first. velocity.y = 0; velocity += jumping.jumpDir * CalculateJumpVerticalSpeed(jumping.baseHeight); // Apply inertia from platform if (movingPlatform.enabled && (movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer || movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer) ) { movement.frameVelocity = movingPlatform.platformVelocity; velocity += movingPlatform.platformVelocity; } SendMessage("OnJump", SendMessageOptions.DontRequireReceiver); } else { jumping.holdingJumpButton = false; } } return velocity; } void OnControllerColliderHit(ControllerColliderHit hit) { if (hit.normal.y > 0 && hit.normal.y > groundNormal.y && hit.moveDirection.y < 0) { if ((hit.point - movement.lastHitPoint).sqrMagnitude > 0.001 || lastGroundNormal == Vector3.zero) groundNormal = hit.normal; else groundNormal = lastGroundNormal; movingPlatform.hitPlatform = hit.collider.transform; movement.hitPoint = hit.point; movement.frameVelocity = Vector3.zero; } } private IEnumerator SubtractNewPlatformVelocity() { // When landing, subtract the velocity of the new ground from the character's velocity // since movement in ground is relative to the movement of the ground. if (movingPlatform.enabled && (movingPlatform.movementTransfer == MovementTransferOnJump.InitTransfer || movingPlatform.movementTransfer == MovementTransferOnJump.PermaTransfer)) { // if we landed on a new platform, we have to wait for two FixedUpdates // before we know the velocity of the platform under the character if (movingPlatform.newPlatform) { Transform platform = movingPlatform.activePlatform; yield return new WaitForFixedUpdate(); yield return new WaitForFixedUpdate(); if (grounded && platform == movingPlatform.activePlatform) yield break; } movement.velocity -= movingPlatform.platformVelocity; } } private bool MoveWithPlatform() { return (movingPlatform.enabled && (grounded || movingPlatform.movementTransfer == MovementTransferOnJump.PermaLocked) && movingPlatform.activePlatform != null ); } private Vector3 GetDesiredHorizontalVelocity() { // Find desired velocity Vector3 desiredLocalDirection = tr.InverseTransformDirection(inputMoveDirection); float maxSpeed = MaxSpeedInDirection(desiredLocalDirection); if (grounded) { // Modify max speed on slopes based on slope speed multiplier curve var movementSlopeAngle = Mathf.Asin(movement.velocity.normalized.y) * Mathf.Rad2Deg; maxSpeed *= movement.slopeSpeedMultiplier.Evaluate(movementSlopeAngle); } return tr.TransformDirection(desiredLocalDirection * maxSpeed); } private Vector3 AdjustGroundVelocityToNormal(Vector3 hVelocity, Vector3 groundNormal) { Vector3 sideways = Vector3.Cross(Vector3.up, hVelocity); return Vector3.Cross(sideways, groundNormal).normalized * hVelocity.magnitude; } private bool IsGroundedTest() { return (groundNormal.y > 0.01); } float GetMaxAcceleration(bool grounded) { // Maximum acceleration on ground and in air if (grounded) return movement.maxGroundAcceleration; else return movement.maxAirAcceleration; } float CalculateJumpVerticalSpeed(float targetJumpHeight) { // From the jump height and gravity we deduce the upwards speed // for the character to reach at the apex. return Mathf.Sqrt(2 * targetJumpHeight * movement.gravity); } bool IsJumping() { return jumping.jumping; } bool IsSliding() { return (grounded && sliding.enabled && TooSteep()); } bool IsTouchingCeiling() { return (movement.collisionFlags & CollisionFlags.CollidedAbove) != 0; } bool IsGrounded() { return grounded; } bool TooSteep() { return (groundNormal.y <= Mathf.Cos(controller.slopeLimit * Mathf.Deg2Rad)); } Vector3 GetDirection() { return inputMoveDirection; } void SetControllable(bool controllable) { canControl = controllable; } // Project a direction onto elliptical quater segments based on forward, sideways, and backwards speed. // The function returns the length of the resulting vector. float MaxSpeedInDirection(Vector3 desiredMovementDirection) { if (desiredMovementDirection == Vector3.zero) return 0; else { float zAxisEllipseMultiplier = (desiredMovementDirection.z > 0 ? movement.maxForwardSpeed : movement.maxBackwardsSpeed) / movement.maxSidewaysSpeed; Vector3 temp = new Vector3(desiredMovementDirection.x, 0, desiredMovementDirection.z / zAxisEllipseMultiplier).normalized; float length = new Vector3(temp.x, 0, temp.z * zAxisEllipseMultiplier).magnitude * movement.maxSidewaysSpeed; return length; } } void SetVelocity(Vector3 velocity) { grounded = false; movement.velocity = velocity; movement.frameVelocity = Vector3.zero; SendMessage("OnExternalVelocity"); } }
{ "content_hash": "7dc0a8e3611191e29398e6e74e09c295", "timestamp": "", "source": "github", "line_count": 654, "max_line_length": 160, "avg_line_length": 40.169724770642205, "alnum_prop": 0.6270031593772601, "repo_name": "kldavis4/MinePackage", "id": "8a01c69e19f232fdd543627cc9e7e3b28c7d55b3", "size": "26273", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Scripts/Misc/CharacterMotor.cs", "mode": "33261", "license": "bsd-2-clause", "language": [ { "name": "C#", "bytes": "234088" }, { "name": "GLSL", "bytes": "7507" }, { "name": "JavaScript", "bytes": "43768" } ], "symlink_target": "" }
package wkbcommon import ( "encoding/binary" "io" "math" "github.com/twpayne/go-geom" ) func readFloat(buf []byte, byteOrder binary.ByteOrder) float64 { u := byteOrder.Uint64(buf) return math.Float64frombits(u) } // ReadUInt32 reads a uint32 from r. func ReadUInt32(r io.Reader, byteOrder binary.ByteOrder) (uint32, error) { var buf [4]byte if _, err := io.ReadFull(r, buf[:]); err != nil { return 0, err } return byteOrder.Uint32(buf[:]), nil } // ReadFloatArray reads a []float64 from r. func ReadFloatArray(r io.Reader, byteOrder binary.ByteOrder, array []float64) error { buf := make([]byte, 8*len(array)) if _, err := io.ReadFull(r, buf); err != nil { return err } // Convert to an array of floats for i := range array { array[i] = readFloat(buf[8*i:], byteOrder) } return nil } // ReadByte reads a byte from r. func ReadByte(r io.Reader) (byte, error) { var buf [1]byte if _, err := r.Read(buf[:]); err != nil { return 0, err } return buf[0], nil } func writeFloat(buf []byte, byteOrder binary.ByteOrder, value float64) { u := math.Float64bits(value) byteOrder.PutUint64(buf, u) } // WriteFloatArray writes a []float64 to w. func WriteFloatArray(w io.Writer, byteOrder binary.ByteOrder, array []float64) error { buf := make([]byte, 8*len(array)) for i, f := range array { writeFloat(buf[8*i:], byteOrder, f) } _, err := w.Write(buf) return err } // WriteUInt32 writes a uint32 to w. func WriteUInt32(w io.Writer, byteOrder binary.ByteOrder, value uint32) error { var buf [4]byte byteOrder.PutUint32(buf[:], value) _, err := w.Write(buf[:]) return err } // WriteByte wrties a byte to w. func WriteByte(w io.Writer, value byte) error { var buf [1]byte buf[0] = value _, err := w.Write(buf[:]) return err } // WriteEmptyPointAsNaN outputs EmptyPoint as NaN values. func WriteEmptyPointAsNaN(w io.Writer, byteOrder binary.ByteOrder, numCoords int) error { coords := make([]float64, numCoords) for i := 0; i < numCoords; i++ { coords[i] = geom.PointEmptyCoord() } return WriteFlatCoords0(w, byteOrder, coords) }
{ "content_hash": "ef49fe75798dfe2bc8418a75ec29dddd", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 89, "avg_line_length": 24.423529411764704, "alnum_prop": 0.680635838150289, "repo_name": "twpayne/go-geom", "id": "12c21d5b5bff5646df2c80557a04d8dc49733e94", "size": "2144", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "encoding/wkbcommon/binary.go", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Go", "bytes": "550743" }, { "name": "Makefile", "bytes": "1747" }, { "name": "Yacc", "bytes": "15931" } ], "symlink_target": "" }
<?php namespace SR\Doctrine\Exception; use Doctrine\ORM\ORMException; class GeneralException extends ORMException implements ExceptionInterface { use ExceptionTrait; }
{ "content_hash": "0a6c1a42dc6c0055b2c7943c47837548", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 73, "avg_line_length": 14.75, "alnum_prop": 0.8022598870056498, "repo_name": "scr-be/arthur-doctrine-utils-library", "id": "ac2396cbe89cf9b043d7b362bb30336d42c43128", "size": "437", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/GeneralException.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "7700" } ], "symlink_target": "" }
xcopy ..\..\source\ServiceProxy.Zmq_old\bin\Release\ServiceProxy.Zmq.dll lib\net45\ /y NuGet.exe pack ServiceProxy.Zmq.nuspec -exclude *.cmd -OutputDirectory ..\
{ "content_hash": "fe086015bab2d354f73ed192d444f865", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 86, "avg_line_length": 54, "alnum_prop": 0.7654320987654321, "repo_name": "mfelicio/ServiceProxy", "id": "bb034ce4dba8fdecdb58937bce4fa1feae42c9cd", "size": "162", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nuget/ServiceProxy.Zmq_old/pack.cmd", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "786" }, { "name": "C#", "bytes": "161764" } ], "symlink_target": "" }
<!-- __COPYRIGHT__ This file is processed by the bin/SConsDoc.py module. See its __doc__ string for a discussion of the format. --> <tool name="install"> <summary> Sets construction variables for file and directory installation. </summary> <sets> INSTALL INSTALLSTR </sets> </tool> <builder name="Install"> <summary> Installs one or more source files or directories in the specified target, which must be a directory. The names of the specified source files or directories remain the same within the destination directory. <example> env.Install('/usr/local/bin', source = ['foo', 'bar']) </example> </summary> </builder> <builder name="InstallAs"> <summary> Installs one or more source files or directories to specific names, allowing changing a file or directory name as part of the installation. It is an error if the target and source arguments list different numbers of files or directories. <example> env.InstallAs(target = '/usr/local/bin/foo', source = 'foo_debug') env.InstallAs(target = ['../lib/libfoo.a', '../lib/libbar.a'], source = ['libFOO.a', 'libBAR.a']) </example> </summary> </builder>
{ "content_hash": "586e975c6099c26a361f19317285ef51", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 62, "avg_line_length": 21.884615384615383, "alnum_prop": 0.7170474516695958, "repo_name": "azatoth/scons", "id": "4b57a688d2e7ba70532c46158fc77f636952e560", "size": "1138", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/engine/SCons/Tool/install.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "259" }, { "name": "JavaScript", "bytes": "17316" }, { "name": "Perl", "bytes": "45214" }, { "name": "Python", "bytes": "6716123" }, { "name": "Shell", "bytes": "2535" } ], "symlink_target": "" }
extern const struct wl_interface bq_buffer_interface; extern const struct wl_interface bq_consumer_interface; extern const struct wl_interface bq_provider_interface; static const struct wl_interface *types[] = { NULL, NULL, NULL, &bq_consumer_interface, NULL, NULL, NULL, NULL, &bq_provider_interface, NULL, &bq_buffer_interface, &bq_buffer_interface, NULL, NULL, NULL, NULL, NULL, &bq_buffer_interface, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &bq_buffer_interface, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &bq_buffer_interface, &bq_buffer_interface, NULL, &bq_buffer_interface, NULL, NULL, NULL, NULL, NULL, &bq_buffer_interface, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &bq_buffer_interface, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &bq_buffer_interface, &bq_buffer_interface, NULL, &bq_buffer_interface, NULL, }; static const struct wl_message bq_mgr_requests[] = { { "create_consumer", "nsiii", types + 3 }, { "create_provider", "ns", types + 8 }, }; WL_EXPORT const struct wl_interface bq_mgr_interface = { "bq_mgr", 1, 2, bq_mgr_requests, 0, NULL, }; static const struct wl_message bq_consumer_requests[] = { { "release_buffer", "o", types + 10 }, }; static const struct wl_message bq_consumer_events[] = { { "connected", "", types + 0 }, { "disconnected", "", types + 0 }, { "buffer_attached", "nsiiiu", types + 11 }, { "set_buffer_id", "oiiiiiii", types + 17 }, { "set_buffer_fd", "ohiiiiii", types + 25 }, { "buffer_detached", "o", types + 33 }, { "add_buffer", "ou", types + 34 }, }; WL_EXPORT const struct wl_interface bq_consumer_interface = { "bq_consumer", 1, 1, bq_consumer_requests, 7, bq_consumer_events, }; static const struct wl_message bq_provider_requests[] = { { "attach_buffer", "nsiiiu", types + 36 }, { "set_buffer_id", "oiiiiiii", types + 42 }, { "set_buffer_fd", "ohiiiiii", types + 50 }, { "detach_buffer", "o", types + 58 }, { "enqueue_buffer", "ou", types + 59 }, }; static const struct wl_message bq_provider_events[] = { { "connected", "iii", types + 0 }, { "disconnected", "", types + 0 }, { "add_buffer", "ou", types + 61 }, }; WL_EXPORT const struct wl_interface bq_provider_interface = { "bq_provider", 1, 5, bq_provider_requests, 3, bq_provider_events, }; WL_EXPORT const struct wl_interface bq_buffer_interface = { "bq_buffer", 1, 0, NULL, 0, NULL, };
{ "content_hash": "13cafbcdc81828cfdcff0ef503f0f51d", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 61, "avg_line_length": 18.88976377952756, "alnum_prop": 0.6423509795748228, "repo_name": "tizenorg/platform.upstream.enlightenment", "id": "fe8b98c9bc05a3cde77954cd9e81f1fc2807fe11", "size": "2466", "binary": false, "copies": "1", "ref": "refs/heads/accepted/tizen_common", "path": "src/modules/bufferqueue/bq_mgr_protocol.c", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "1876892" }, { "name": "C++", "bytes": "4328" }, { "name": "M4", "bytes": "30681" }, { "name": "Makefile", "bytes": "19392" }, { "name": "Objective-C", "bytes": "3811" }, { "name": "Shell", "bytes": "41304" } ], "symlink_target": "" }
using System; namespace Azure.ResourceManager.Compute.Models { internal static partial class OperatingSystemTypesExtensions { public static string ToSerialString(this OperatingSystemTypes value) => value switch { OperatingSystemTypes.Windows => "Windows", OperatingSystemTypes.Linux => "Linux", _ => throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown OperatingSystemTypes value.") }; public static OperatingSystemTypes ToOperatingSystemTypes(this string value) { if (string.Equals(value, "Windows", StringComparison.InvariantCultureIgnoreCase)) return OperatingSystemTypes.Windows; if (string.Equals(value, "Linux", StringComparison.InvariantCultureIgnoreCase)) return OperatingSystemTypes.Linux; throw new ArgumentOutOfRangeException(nameof(value), value, "Unknown OperatingSystemTypes value."); } } }
{ "content_hash": "b1b0f4b2d93fba29af296917c604800e", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 130, "avg_line_length": 45.476190476190474, "alnum_prop": 0.7099476439790576, "repo_name": "yugangw-msft/azure-sdk-for-net", "id": "048497f9a59e26c85bb22f79908f91196556a242", "size": "1093", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/OperatingSystemTypes.Serialization.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "118" }, { "name": "Batchfile", "bytes": "817" }, { "name": "C#", "bytes": "55680650" }, { "name": "CSS", "bytes": "685" }, { "name": "Cucumber", "bytes": "89597" }, { "name": "JavaScript", "bytes": "1719" }, { "name": "PowerShell", "bytes": "24329" }, { "name": "Shell", "bytes": "45" } ], "symlink_target": "" }
import asyncore import re import sys import socket import urllib import urllib2 from constants import MAIN_METASERVER_URL from lib.log import debug, info, warning, exception from serverclient import ConnectionToClient from serverroom import InTheLobby, OrganizingAGame, Playing, WaitingForTheGameToStart from lib.ticker import Ticker from version import VERSION import config import options REGISTER_INTERVAL = 10 * 60 # register server every 10 minutes REGISTER_URL = MAIN_METASERVER_URL + "servers_register.php" UNREGISTER_URL = MAIN_METASERVER_URL + "servers_unregister.php" WHATISMYIP_URL = open("cfg/whatismyip.txt").read().strip() class Server(asyncore.dispatcher): def __init__(self, parameters, is_standalone): self.parameters = parameters self.is_standalone = is_standalone asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.set_reuse_addr() self.bind(("", options.port)) self.listen(5) self.login = config.login self.clients = [] self.games = [] if "admin_only" in parameters: self.nb_games_max = 1 self.nb_clients_max = 20 else: self.nb_games_max = 10 self.nb_clients_max = 40 next_id = 0 def get_next_id(self, increment=True): if increment: self.next_id += 1 return self.next_id else: return self.next_id + 1 def handle_connect(self): pass def handle_read(self): pass def handle_accept(self): ConnectionToClient(self, self.accept()) def _cleanup(self): for c in self.clients[:]: if c not in asyncore.socket_map.values(): self.clients.remove(c) if self.games and not self.clients: self.games = [] def log_status(self): self._cleanup() info("%s players (%s not playing), %s games", len(self.clients), len(self.players_not_playing()), len([g for g in self.games if g.started])) def _is_admin(self, client): return client.address[0] == "127.0.0.1" and client.login == self.login def remove_client(self, client): info("disconnect: %s" % client.login) client.is_disconnected = True if client in self.clients: # not anonymous self.clients.remove(client) for c in self.players_not_playing(): if client.is_compatible(c): c.send_msg([client.login, 4259]) # ... has just disconnected self.update_menus() if isinstance(client.state, Playing): client.cmd_abort_game([]) elif isinstance(client.state, WaitingForTheGameToStart): client.cmd_unregister([]) elif isinstance(client.state, OrganizingAGame): client.cmd_cancel_game([]) if self._is_admin(client) and not self.is_standalone: info("the admin has disconnected => close the server") sys.exit() self.log_status() def handle_write(self): pass def handle_close(self): try: debug("Server.handle_close") except: pass sys.exit() def handle_error(self): try: debug("Server.handle_error %s", sys.exc_info()[0]) except: pass if sys.exc_info()[0] in [SystemExit, KeyboardInterrupt]: sys.exit() else: try: exception("Server.handle_error") except: pass def can_create(self, client): if "admin_only" in self.parameters: return self._is_admin(client) else: return len([g for g in self.games if g.started]) < self.nb_games_max def unregister(self): try: info("unregistering server...") s = urllib.urlopen(UNREGISTER_URL + "?ip=" + self.ip).read() except: s = "couldn't access to the metaserver" if s: warning("couldn't unregister from the metaserver (%s)", s[:80]) ip = "" def _get_ip_address(self): if options.ip: self.ip = options.ip return try: self.ip = urllib2.urlopen(WHATISMYIP_URL, timeout=3).read().strip() if not re.match("^[0-9.]{7,40}$", self.ip): self.ip = "" except: self.ip = "" if not self.ip: warning("could not get my IP address from %s", WHATISMYIP_URL) _first_registration = True def _register(self): try: s = urllib.urlopen(REGISTER_URL + "?version=%s&login=%s&ip=%s&port=%s" % (VERSION, self.login, self.ip, options.port)).read() except: s = "couldn't access to the metaserver" if s: warning("couldn't register to the metaserver (%s)", s[:80]) else: info("server registered") def register(self): if self._first_registration: self._get_ip_address() self._first_registration = False self._register() def _start_registering(self): self.ticker = Ticker(REGISTER_INTERVAL, self.register) self.ticker.start() def startup(self): if "no_metaserver" not in self.parameters: self._start_registering() info("server started") asyncore.loop() def update_menus(self): for c in self.clients: c.send_menu() def available_players(self, client=None): lst = [] for x in self.clients: if isinstance(x.state, InTheLobby): if client: if x.is_compatible(client): lst.append(x) else: lst.append(x) return lst def game_admins(self): return [x for x in self.clients if isinstance(x.state, OrganizingAGame)] def players_not_playing(self): return [x for x in self.clients if not isinstance(x.state, Playing)] def get_client_by_login(self, login): for c in self.clients: if c.login == login: return c def get_game_by_id(self, ident): ident = int(ident) for o in self.games: if o.id == ident: return o def start_server(parameters=sys.argv, is_standalone=True): try: server = Server(parameters, is_standalone) server.startup() finally: try: info("closing server...") if hasattr(server, "ticker"): server.ticker.cancel() server.unregister() # make sure channels are closed (useful?) for c in server.clients: c.close() server.close() except: exception("couldn't close the server") def main(): start_server() if __name__ == '__main__': main()
{ "content_hash": "8860377149adb97f1e872fa75a36aa28", "timestamp": "", "source": "github", "line_count": 237, "max_line_length": 85, "avg_line_length": 29.742616033755276, "alnum_prop": 0.5549723365016315, "repo_name": "thgcode/soundrts", "id": "22e000f9b19e78fa4926a2f889e3de4bfc316774", "size": "7049", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "soundrts/servermain.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1395" }, { "name": "Inno Setup", "bytes": "2065" }, { "name": "PHP", "bytes": "7047" }, { "name": "Python", "bytes": "503498" } ], "symlink_target": "" }
using System; public class Type_Boundaries { public static void Main() { var numberType = Console.ReadLine(); switch (numberType) { case "int": IntMaxAndMinValues(); break; case "uint": UintMaxAndMinValues(); break; case "long": LongMaxAndMinValues(); break; case "byte": ByteMaxAndMinValues(); break; case "sbyte": SByteMaxAndMinValues(); break; } } private static void SByteMaxAndMinValues() { Console.WriteLine(sbyte.MaxValue); Console.WriteLine(sbyte.MinValue); } private static void ByteMaxAndMinValues() { Console.WriteLine(byte.MaxValue); Console.WriteLine(byte.MinValue); } private static void LongMaxAndMinValues() { Console.WriteLine(long.MaxValue); Console.WriteLine(long.MinValue); } private static void UintMaxAndMinValues() { Console.WriteLine(uint.MaxValue); Console.WriteLine(uint.MinValue); } private static void IntMaxAndMinValues() { Console.WriteLine(int.MaxValue); Console.WriteLine(int.MinValue); } }
{ "content_hash": "7c4d9b6fe0b62938b338cc22ef00b344", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 46, "avg_line_length": 21.580645161290324, "alnum_prop": 0.5381165919282511, "repo_name": "bilyanahristova42/SoftUni", "id": "b147a4ba8c07db6de9e1a31ed525df8ca96ac19a", "size": "1340", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Programming Fundamentals/2. Data Types and Variables/08. Data Types and Variables - More Exercises/01. Type Boundaries/TypeBoundaries.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "108" }, { "name": "C#", "bytes": "617732" }, { "name": "CSS", "bytes": "306158" }, { "name": "HTML", "bytes": "11742" }, { "name": "Java", "bytes": "6920" }, { "name": "JavaScript", "bytes": "232693" } ], "symlink_target": "" }
<?php namespace Tests\Support\Autoloader; use CodeIgniter\Autoloader\FileLocator; use RuntimeException; /** * Class FatalLocator * * A locator replacement designed to throw * exceptions when used to indicate when * a lookup actually happens. */ class FatalLocator extends FileLocator { /** * Throws. * * @param string $file The namespaced file to locate * @param string $folder The folder within the namespace that we should look for the file. * @param string $ext The file extension the file should have. * * @return false|string The path to the file, or false if not found. */ public function locateFile(string $file, ?string $folder = null, string $ext = 'php') { $folder ??= 'null'; throw new RuntimeException("locateFile({$file}, {$folder}, {$ext})"); } /** * Searches through all of the defined namespaces looking for a file. * Returns an array of all found locations for the defined file. * * Example: * * $locator->search('Config/Routes.php'); * // Assuming PSR4 namespaces include foo and bar, might return: * [ * 'app/Modules/foo/Config/Routes.php', * 'app/Modules/bar/Config/Routes.php', * ] */ public function search(string $path, string $ext = 'php', bool $prioritizeApp = true): array { $prioritizeApp = $prioritizeApp ? 'true' : 'false'; throw new RuntimeException("search({$path}, {$ext}, {$prioritizeApp})"); } }
{ "content_hash": "be7fc6d74a277eab2b1ac0d221d26ad3", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 96, "avg_line_length": 28.27777777777778, "alnum_prop": 0.627373935821873, "repo_name": "bcit-ci/CodeIgniter4", "id": "4634557597050c133e44486bd5115df5052c322b", "size": "1770", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "tests/_support/Autoloader/FatalLocator.php", "mode": "33188", "license": "mit", "language": [ { "name": "BlitzBasic", "bytes": "2795" }, { "name": "CSS", "bytes": "143659" }, { "name": "HTML", "bytes": "24162" }, { "name": "Hack", "bytes": "2832" }, { "name": "JavaScript", "bytes": "23661" }, { "name": "Makefile", "bytes": "4622" }, { "name": "PHP", "bytes": "2728879" }, { "name": "Python", "bytes": "11561" }, { "name": "Shell", "bytes": "10172" } ], "symlink_target": "" }
package org.gradle.foundation; import org.gradle.api.Project; import org.gradle.api.Task; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * This converts Gradle's projects into ProjectView objects. These can be safely reused unlike Gradle's projects. */ public class ProjectConverter { private List<ProjectView> rootLevelResultingProjects = new ArrayList<ProjectView>(); /** * Call this to convert the projects. * * @param rootProject the root project. */ public List<ProjectView> convertProjects(Project rootProject) { rootLevelResultingProjects.clear(); addRootLevelProject(rootProject); return rootLevelResultingProjects; } /** * This adds the specified project as a root level projects. It then adds all tasks and recursively adds all sub projects. * * @param rootLevelProject a root level project. */ public void addRootLevelProject(Project rootLevelProject) { ProjectView rootLevelProjectView = new ProjectView(null, rootLevelProject.getName(), rootLevelProject.getBuildFile(), rootLevelProject.getDescription()); rootLevelResultingProjects.add(rootLevelProjectView); addSubProjects(rootLevelProject, rootLevelProjectView); addTasks(rootLevelProject, rootLevelProjectView); rootLevelProjectView.sortSubProjectsAndTasks(); } /** * Adds all sub projects of the specified GradleProject. * * @param parentProject the source parent project. Where we get the sub projects from. * @param parentProjectView the destination of the sub projects from parentProject. */ private void addSubProjects(Project parentProject, ProjectView parentProjectView) { Collection<Project> subProjects = parentProject.getChildProjects().values(); for (Project subProject : subProjects) { ProjectView projectView = new ProjectView(parentProjectView, subProject.getName(), subProject.getBuildFile(), subProject.getDescription()); addTasks(subProject, projectView); projectView.sortSubProjectsAndTasks(); addSubProjects(subProject, projectView); } } /** * Adds the tasks from the project to the GradleProject. * * @param project the source parent project. Where we get the sub projects from. * @param projectView the destination of the tasks from project. */ private void addTasks(Project project, ProjectView projectView) { List<String> defaultTasks = project.getDefaultTasks(); for (Task task : project.getTasks()) { String taskName = task.getName(); boolean isDefault = defaultTasks.contains(taskName); projectView.createTask(taskName, task.getDescription(), isDefault); } } }
{ "content_hash": "0bc1b375e5139cdc55d660ce617d2dbe", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 161, "avg_line_length": 34.74390243902439, "alnum_prop": 0.7041067041067041, "repo_name": "Pushjet/Pushjet-Android", "id": "8bb3bdd83dbec8edf787b329661b86f7e16786f2", "size": "3464", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "gradle/wrapper/dists/gradle-2.2.1-all/c64ydeuardnfqctvr1gm30w53/gradle-2.2.1/src/ui/org/gradle/foundation/ProjectConverter.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Java", "bytes": "92331" } ], "symlink_target": "" }
package com.vmware.vim25.mo; import java.rmi.RemoteException; import com.vmware.vim25.*; import com.vmware.vim25.mo.util.*; /** * The managed object class corresponding to the one defined in VI SDK API reference. * @author Steve JIN (http://www.doublecloud.org) */ public class Folder extends ManagedEntity { public Folder(ServerConnection sc, ManagedObjectReference mor) { super(sc, mor); } // the array could have different real types, therefore cannot use getManagedObjects() public ManagedEntity[] getChildEntity() throws InvalidProperty, RuntimeFault, RemoteException { ManagedObjectReference[] mors = (ManagedObjectReference[]) getCurrentProperty("childEntity");; if(mors==null) { return new ManagedEntity[] {}; } ManagedEntity[] mes = new ManagedEntity[mors.length]; for(int i=0; i<mors.length; i++) { mes[i] = MorUtil.createExactManagedEntity(getServerConnection(), mors[i]); } return mes; } public String[] getChildType() { return (String[]) getCurrentProperty("childType"); } // SDK2.5 signature for back compatibility public Task addStandaloneHost_Task(HostConnectSpec spec, ComputeResourceConfigSpec compResSpec, boolean addConnected) throws InvalidLogin, HostConnectFault, RuntimeFault, RemoteException { return addStandaloneHost_Task(spec, compResSpec, addConnected, null); } // new 4.0 signature public Task addStandaloneHost_Task(HostConnectSpec spec, ComputeResourceConfigSpec compResSpec, boolean addConnected, String license) throws InvalidLogin, HostConnectFault, RuntimeFault, RemoteException { return new Task(getServerConnection(), getVimService().addStandaloneHost_Task(getMOR(), spec, compResSpec, addConnected, license)); } public ClusterComputeResource createCluster(String name, ClusterConfigSpec spec) throws InvalidName, DuplicateName, RuntimeFault, RemoteException { return new ClusterComputeResource(getServerConnection(), getVimService().createCluster(getMOR(), name, spec) ); } public ClusterComputeResource createClusterEx(String name, ClusterConfigSpecEx spec) throws InvalidName, DuplicateName, RuntimeFault, RemoteException { return new ClusterComputeResource(getServerConnection(), getVimService().createClusterEx(getMOR(), name, spec) ); } public Datacenter createDatacenter(String name) throws InvalidName, DuplicateName, RuntimeFault, RemoteException { return new Datacenter(getServerConnection(), getVimService().createDatacenter(getMOR(), name) ); } /** * @since 4.0 */ public Task createDVS_Task(DVSCreateSpec spec) throws DvsNotAuthorized, DvsFault, DuplicateName, InvalidName, NotFound, RuntimeFault, RemoteException { ManagedObjectReference taskMor = getVimService().createDVS_Task(getMOR(), spec); return new Task(getServerConnection(), taskMor); } public Folder createFolder(String name) throws InvalidName, DuplicateName, RuntimeFault, RemoteException { return new Folder(getServerConnection(), getVimService().createFolder(getMOR(), name) ); } /** * @since SDK5.0 */ public StoragePod createStoragePod(String name) throws DuplicateName, InvalidName, RuntimeFault, RemoteException { ManagedObjectReference mor = getVimService().createStoragePod(getMOR(), name); return new StoragePod(getServerConnection(), mor); } public Task createVM_Task(VirtualMachineConfigSpec config, ResourcePool pool, HostSystem host) throws InvalidName, VmConfigFault, DuplicateName, FileFault, OutOfBounds, InsufficientResourcesFault, InvalidDatastore, RuntimeFault, RemoteException { return new Task(getServerConnection(), getVimService().createVM_Task(getMOR(), config, pool.getMOR(), host==null? null : host.getMOR()) ); } public Task moveIntoFolder_Task(ManagedEntity[] entities) throws DuplicateName, InvalidState, InvalidFolder, RuntimeFault, RemoteException { if(entities==null) { throw new IllegalArgumentException("entities must not be null"); } return new Task( getServerConnection(), getVimService().moveIntoFolder_Task(getMOR(), MorUtil.createMORs(entities)) ); } public Task registerVM_Task(String path, String name, boolean asTemplate, ResourcePool pool, HostSystem host) throws VmConfigFault, InvalidName, DuplicateName, FileFault, OutOfBounds, InsufficientResourcesFault, InvalidDatastore, AlreadyExists, NotFound, RuntimeFault, RemoteException { return new Task( getServerConnection(), getVimService().registerVM_Task(getMOR(), path, name, asTemplate, pool==null? null : pool.getMOR(), host==null? null : host.getMOR()) ); } public Task unregisterAndDestroy_Task() throws InvalidState, ConcurrentAccess, RuntimeFault, RemoteException { return new Task( getServerConnection(), getVimService().unregisterAndDestroy_Task(getMOR()) ); } }
{ "content_hash": "ef631d78670123a7d0c10024310daddc", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 286, "avg_line_length": 37.13953488372093, "alnum_prop": 0.7687330411187644, "repo_name": "paksv/vijava", "id": "ec0d880c9ca682fed9b98b1809b59e106d80374a", "size": "6433", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/com/vmware/vim25/mo/Folder.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "7900718" } ], "symlink_target": "" }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.banana.banana.SplashActivity" > <ImageView android:id="@+id/img_mission1" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/splash" /> </LinearLayout>
{ "content_hash": "37b1aee5a09ad9c38624b1f7f88db54a", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 72, "avg_line_length": 36, "alnum_prop": 0.6981481481481482, "repo_name": "LeeYelim/wholeba_android", "id": "4527e967ac464000e472bcabf1fe743ccfcdfb9f", "size": "540", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "res/layout/activity_spalsh.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "387426" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <welcome-file-list><welcome-file> index.html </welcome-file></welcome-file-list> <context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> </context-param> </web-app>
{ "content_hash": "1db84e4e59cb67e9ca256f582b43f1e3", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 68, "avg_line_length": 36.43478260869565, "alnum_prop": 0.6730310262529833, "repo_name": "thescouser89/snippets", "id": "5039b755e8aa639fffc58b5834868bcbece57dbd", "size": "838", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jsf/javaee/ch13/resolver/web/WEB-INF/web.xml", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "426" }, { "name": "CSS", "bytes": "6738" }, { "name": "Java", "bytes": "240783" }, { "name": "JavaScript", "bytes": "12295" }, { "name": "Python", "bytes": "596" }, { "name": "Ruby", "bytes": "2346" }, { "name": "Shell", "bytes": "5499" } ], "symlink_target": "" }
 #include <aws/ds/model/CreateTrustRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::DirectoryService::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; CreateTrustRequest::CreateTrustRequest() : m_directoryIdHasBeenSet(false), m_remoteDomainNameHasBeenSet(false), m_trustPasswordHasBeenSet(false), m_trustDirectionHasBeenSet(false), m_trustTypeHasBeenSet(false), m_conditionalForwarderIpAddrsHasBeenSet(false) { } Aws::String CreateTrustRequest::SerializePayload() const { JsonValue payload; if(m_directoryIdHasBeenSet) { payload.WithString("DirectoryId", m_directoryId); } if(m_remoteDomainNameHasBeenSet) { payload.WithString("RemoteDomainName", m_remoteDomainName); } if(m_trustPasswordHasBeenSet) { payload.WithString("TrustPassword", m_trustPassword); } if(m_trustDirectionHasBeenSet) { payload.WithString("TrustDirection", TrustDirectionMapper::GetNameForTrustDirection(m_trustDirection)); } if(m_trustTypeHasBeenSet) { payload.WithString("TrustType", TrustTypeMapper::GetNameForTrustType(m_trustType)); } if(m_conditionalForwarderIpAddrsHasBeenSet) { Array<JsonValue> conditionalForwarderIpAddrsJsonList(m_conditionalForwarderIpAddrs.size()); for(unsigned conditionalForwarderIpAddrsIndex = 0; conditionalForwarderIpAddrsIndex < conditionalForwarderIpAddrsJsonList.GetLength(); ++conditionalForwarderIpAddrsIndex) { conditionalForwarderIpAddrsJsonList[conditionalForwarderIpAddrsIndex].AsString(m_conditionalForwarderIpAddrs[conditionalForwarderIpAddrsIndex]); } payload.WithArray("ConditionalForwarderIpAddrs", std::move(conditionalForwarderIpAddrsJsonList)); } return payload.WriteReadable(); } Aws::Http::HeaderValueCollection CreateTrustRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "DirectoryService_20150416.CreateTrust")); return headers; }
{ "content_hash": "1ae28412a7d1612444dfb9343f030399", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 173, "avg_line_length": 26.973684210526315, "alnum_prop": 0.7829268292682927, "repo_name": "ambasta/aws-sdk-cpp", "id": "ba615539cf72dd2d130e889b0dd06405bd48087f", "size": "2623", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-cpp-sdk-ds/source/model/CreateTrustRequest.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2305" }, { "name": "C++", "bytes": "74273816" }, { "name": "CMake", "bytes": "412257" }, { "name": "Java", "bytes": "229873" }, { "name": "Python", "bytes": "62933" } ], "symlink_target": "" }
'use strict' var ArrayTester = require('../tools/test/array-tester') var shallowEquals = require('../tools/test/shallow-equals') var makeIterable = require('../tools/test/make-iterable') var testNonIterables = require('../tools/test/test-non-iterables') require('../tools/test/describe')('Promise.all', function (Promise, expect) { var arrayTester = new ArrayTester(Promise) function expectToMatch(input, source) { return expect(Promise.all(input)).to.eventually.satisfy(shallowEquals(source)) } it('should be fulfilled given an empty array', function () { var array = [] return expectToMatch(array, array) }) it('should treat deleted keys as undefined', function () { var array = new Array(3) return expectToMatch(array, array) }) it('should treat strings as iterables, if ES6 iterables are supported', function () { var expectation = expect(Promise.all('hello')) if (typeof Symbol !== 'function' || !Symbol.iterator) { return expectation.to.be.rejectedWith(TypeError) } return expectation.to.eventually.satisfy(shallowEquals(['h', 'e', 'l', 'l', 'o'])) }) describe('should be rejected on invalid input', function () { testNonIterables(function (value) { return expect(Promise.all(value)).to.be.rejectedWith(TypeError) }) }) describe('should be fulfilled with an array of values', function () { var irrelevantPromise = Promise.reject(new Error('baz')).catchLater() arrayTester.test([[irrelevantPromise], 123], expectToMatch) }) describe('should not be affected by changing the input array after invocation', function () { arrayTester.test(['foo', ''], function (input, source) { var ret = Promise.all(input) input[0] = 'bar' delete input[1] input.length = 1 return expect(ret).to.eventually.satisfy(shallowEquals(['foo', ''])) }) }) describe('should not be affected by changing the input iterable after invocation', function () { arrayTester.test(['foo', ''], function (input, source) { var ret = Promise.all(makeIterable(input)) input[0] = 'bar' delete input[1] input.length = 1 return expect(ret).to.eventually.satisfy(shallowEquals(['foo', ''])) }) }) describe('should be rejected with the rejection reason of a rejected promise', function () { var err = new Error('baz') arrayTester.test([123, Promise.reject(err)], function (input, source) { return expect(Promise.all(input)).to.be.rejectedWith(err) }) }) describe('should be rejected by the earliest rejected promise', function () { var errors = [new Error('baz'), new Error('quux')] arrayTester.test([Promise.reject(errors[0]), Promise.reject(errors[1])], function (input, source, raceWinner) { return expect(Promise.all(input)).to.be.rejectedWith(errors[raceWinner]) }) }) })
{ "content_hash": "1c731d6abe649924bc9b2948398b4131", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 113, "avg_line_length": 41.60606060606061, "alnum_prop": 0.701019664967225, "repo_name": "JoshuaWise/jellypromise", "id": "a6de5d75e9c006cd2d47a46d4bcd91d1030c27ee", "size": "2746", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/32.all.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "155867" } ], "symlink_target": "" }
package com.vmware.vim25; /** @author Steve Jin (sjin@vmware.com) */ public class HostDiskPartitionLayout extends DynamicData { public HostDiskDimensionsLba total; public HostDiskPartitionBlockRange[] partition; public HostDiskDimensionsLba getTotal() { return this.total; } public HostDiskPartitionBlockRange[] getPartition() { return this.partition; } public void setTotal(HostDiskDimensionsLba total) { this.total=total; } public void setPartition(HostDiskPartitionBlockRange[] partition) { this.partition=partition; } }
{ "content_hash": "b4903e7f7211a93493992ea04053f55b", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 67, "avg_line_length": 17.424242424242426, "alnum_prop": 0.7408695652173913, "repo_name": "mikem2005/vijava", "id": "cb167e918f8c7fbc1fe1d8b6f15a6b6b78ce6e03", "size": "2217", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/vmware/vim25/HostDiskPartitionLayout.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "6585830" } ], "symlink_target": "" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>basic_raw_socket::connect</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../basic_raw_socket.html" title="basic_raw_socket"> <link rel="prev" href="close/overload2.html" title="basic_raw_socket::close (2 of 2 overloads)"> <link rel="next" href="connect/overload1.html" title="basic_raw_socket::connect (1 of 2 overloads)"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="close/overload2.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_raw_socket.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="connect/overload1.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="boost_asio.reference.basic_raw_socket.connect"></a><a class="link" href="connect.html" title="basic_raw_socket::connect">basic_raw_socket::connect</a> </h4></div></div></div> <p> <a class="indexterm" name="idp37023072"></a> Connect the socket to the specified endpoint. </p> <pre class="programlisting"><span class="keyword">void</span> <a class="link" href="connect/overload1.html" title="basic_raw_socket::connect (1 of 2 overloads)">connect</a><span class="special">(</span> <span class="keyword">const</span> <span class="identifier">endpoint_type</span> <span class="special">&amp;</span> <span class="identifier">peer_endpoint</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="connect/overload1.html" title="basic_raw_socket::connect (1 of 2 overloads)">more...</a></em></span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <a class="link" href="connect/overload2.html" title="basic_raw_socket::connect (2 of 2 overloads)">connect</a><span class="special">(</span> <span class="keyword">const</span> <span class="identifier">endpoint_type</span> <span class="special">&amp;</span> <span class="identifier">peer_endpoint</span><span class="special">,</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&amp;</span> <span class="identifier">ec</span><span class="special">);</span> <span class="emphasis"><em>&#187; <a class="link" href="connect/overload2.html" title="basic_raw_socket::connect (2 of 2 overloads)">more...</a></em></span> </pre> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2013 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="close/overload2.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../basic_raw_socket.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="connect/overload1.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{ "content_hash": "23eaa87bb4825ef31bb8cf8b8a601233", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 446, "avg_line_length": 82.76785714285714, "alnum_prop": 0.6507011866235167, "repo_name": "gnu3ra/SCC15HPCRepast", "id": "04de33812e243d798882c360a061f72a010d292a", "size": "4635", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "INSTALLATION/boost_1_54_0/doc/html/boost_asio/reference/basic_raw_socket/connect.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "166901" }, { "name": "Awk", "bytes": "4270" }, { "name": "Batchfile", "bytes": "59453" }, { "name": "C", "bytes": "89044644" }, { "name": "C#", "bytes": "171870" }, { "name": "C++", "bytes": "149286410" }, { "name": "CMake", "bytes": "1277735" }, { "name": "CSS", "bytes": "275497" }, { "name": "Cuda", "bytes": "26749" }, { "name": "DIGITAL Command Language", "bytes": "396318" }, { "name": "FORTRAN", "bytes": "5955918" }, { "name": "Groff", "bytes": "1536123" }, { "name": "HTML", "bytes": "152716955" }, { "name": "IDL", "bytes": "14" }, { "name": "Java", "bytes": "1703162" }, { "name": "JavaScript", "bytes": "132031" }, { "name": "Lex", "bytes": "44890" }, { "name": "LiveScript", "bytes": "299224" }, { "name": "Logos", "bytes": "17671" }, { "name": "Makefile", "bytes": "10089555" }, { "name": "Max", "bytes": "36857" }, { "name": "Objective-C", "bytes": "4756" }, { "name": "PHP", "bytes": "74480" }, { "name": "Perl", "bytes": "1444604" }, { "name": "Perl6", "bytes": "9917" }, { "name": "PostScript", "bytes": "4003" }, { "name": "Pure Data", "bytes": "1710" }, { "name": "Python", "bytes": "2280373" }, { "name": "QML", "bytes": "593" }, { "name": "Rebol", "bytes": "354" }, { "name": "Scilab", "bytes": "3012" }, { "name": "Shell", "bytes": "11997985" }, { "name": "Tcl", "bytes": "1172" }, { "name": "TeX", "bytes": "696679" }, { "name": "Visual Basic", "bytes": "11578" }, { "name": "XSLT", "bytes": "771726" }, { "name": "Yacc", "bytes": "140274" } ], "symlink_target": "" }
var get = Ember.get, set = Ember.set; /** Whether the browser supports HTML5 history. */ var supportsHistory = !!(window.history && window.history.pushState); /** Whether the browser supports the hashchange event. */ var supportsHashChange = ('onhashchange' in window) && (document.documentMode === undefined || document.documentMode > 7); /** @class Ember.RouteManager manages the browser location and changes states accordingly to the current location. The location can be programmatically set as follows: routeManager.set('location', 'notes/edit/4'); Ember.RouteManager also supports HTML5 history, which uses a '/' instead of a '#' in the URLs, so that all your website's URLs are consistent. */ Ember.RouteManager = Ember.StateManager.extend({ /** Set this property to true if you want to use HTML5 history, if available on the browser, instead of the location hash. HTML 5 history uses the history.pushState method and the window's popstate event. By default it is false, so your URLs will look like: http://domain.tld/my_app#notes/edit/4 If set to true and the browser supports pushState(), your URLs will look like: http://domain.tld/my_app/notes/edit/4 You will also need to make sure that baseURI is properly configured, as well as your server so that your routes are properly pointing to your Ember application. @see http://dev.w3.org/html5/spec/history.html#the-history-interface @property @type {Boolean} */ wantsHistory: false, /** A read-only boolean indicating whether or not HTML5 history is used. Based on the value of wantsHistory and the browser's support for pushState. @see wantsHistory @property @type {Boolean} */ usesHistory: null, /** The base URI used to resolve routes (which are relative URLs). Only used when usesHistory is equal to true. The build tools automatically configure this value if you have the html5_history option activated in the Buildfile: config :my_app, :html5_history => true Alternatively, it uses by default the value of the href attribute of the <base> tag of the HTML document. For example: <base href="http://domain.tld/my_app"> The value can also be customized before or during the exectution of the main() method. @see http://www.w3.org/TR/html5/semantics.html#the-base-element @property @type {String} */ baseURI: document.baseURI, /** @private A boolean value indicating whether or not the ping method has been called to setup the Ember.routes. @property @type {Boolean} */ _didSetup: false, /** @private Internal representation of the current location hash. @property @type {String} */ _location: null, /** @private Internal method used to extract and merge the parameters of a URL. @returns {Hash} */ _extractParametersAndRoute: function(obj) { var params = {}, route = obj.route || '', separator, parts, i, len, crumbs, key; separator = (route.indexOf('?') < 0 && route.indexOf('&') >= 0) ? '&' : '?'; parts = route.split(separator); route = parts[0]; if(parts.length === 1) { parts = []; } else if(parts.length === 2) { parts = parts[1].split('&'); } else if(parts.length > 2) { parts.shift(); } // extract the parameters from the route string len = parts.length; for( i = 0; i < len; ++i) { crumbs = parts[i].split('='); params[crumbs[0]] = crumbs[1]; } // overlay any parameter passed in obj for(key in obj) { if(obj.hasOwnProperty(key) && key !== 'route') { params[key] = '' + obj[key]; } } // build the route parts = []; for(key in params) { parts.push([key, params[key]].join('=')); } params.params = separator + parts.join('&'); params.route = route; return params; }, /** The current location hash. It is the part in the browser's location after the '#' mark. @property @type {String} */ location: Ember.computed(function(key, value) { this._skipRoute = false; return this._extractLocation(key, value); }).property(), _extractLocation: function(key, value) { var crumbs, encodedValue; if(value !== undefined) { if(value === null) { value = ''; } if( typeof (value) === 'object') { crumbs = this._extractParametersAndRoute(value); value = crumbs.route + crumbs.params; } if(!this._skipPush && (!Ember.empty(value) || (this._location && this._location !== value))) { encodedValue = encodeURI(value); if(this.usesHistory) { if(encodedValue.length > 0) { encodedValue = '/' + encodedValue; } window.history.pushState(null, null, get(this, 'baseURI') + encodedValue); } else if(encodedValue.length > 0 || window.location.hash.length > 0) { window.location.hash = encodedValue; } } this._location = value; } return this._location; }, updateLocation: function(loc) { this._skipRoute = true; return this._extractLocation('location', loc); }, /** Start this routemanager. Registers for the hashchange event if available. If not, it creates a timer that looks for location changes every 150ms. */ start: function() { if(!this._didSetup) { this._didSetup = true; var state; if(get(this, 'wantsHistory') && supportsHistory) { this.usesHistory = true; // Move any hash state to url state // TODO: Make sure we have a hash before adding slash state = window.location.hash.slice(1); if(state.length > 0) { state = '/' + state; window.history.replaceState(null, null, get(this, 'baseURI') + state); } this.popState(); this.popState = jQuery.proxy(this.popState, this); jQuery(window).bind('popstate', this.popState); } else { this.usesHistory = false; if(get(this, 'wantsHistory')) { // Move any url state to hash var base = get(this, 'baseURI'); var loc = (base.charAt(0) === '/') ? document.location.pathname : document.location.href.replace(document.location.hash, ''); state = loc.slice(base.length + 1); if(state.length > 0) { window.location.href = base + '#' + state; } } if(supportsHashChange) { this.hashChange(); this.hashChange = jQuery.proxy(this.hashChange, this); jQuery(window).bind('hashchange', this.hashChange); } else { // we don't use a Ember.Timer because we don't want // a run loop to be triggered at each ping var _this = this, invokeHashChange = function() { _this.hashChange(); _this._timerId = setTimeout(invokeHashChange, 100); }; invokeHashChange(); } } } }, /** Stop this routemanager */ stop: function() { if(this._didSetup) { if(get(this, 'wantsHistory') && supportsHistory) { jQuery(window).unbind('popstate', this.popState); } else { if(supportsHashChange) { jQuery(window).unbind('hashchange', this.hashChange); } else { clearTimeout(this._timerId); } } this._didSetup = false; } }, destroy: function() { this.stop(); this._super(); }, /** Observer of the 'location' property that calls the correct route handler when the location changes. */ locationDidChange: Ember.observer(function() { this.trigger(); }, 'location'), /** Triggers a route even if already in that route (does change the location, if it is not already changed, as well). If the location is not the same as the supplied location, this simply lets "location" handle it (which ends up coming back to here). */ trigger: function() { var location = get(this, 'location'), params, route; params = this._extractParametersAndRoute({ route: location }); location = params.route; delete params.route; delete params.params; var result = this.getState(location, params); if(result) { set(this, 'params', result.params); // We switch states in two phases. The point of this is to handle // parameter-only location changes. This will correspond to the same // state path in the manager, but states with parts with changed // parameters should be re-entered: // 1. We go to the earliest clean state. This prevents // unnecessary transitions. if(result.cleanStates.length > 0) { var cleanState = result.cleanStates.join('.'); this.goToState(cleanState); } // 2. We transition to the dirty state. This forces dirty // states to be transitioned. if(result.dirtyStates.length > 0) { var dirtyState = result.cleanStates.concat(result.dirtyStates).join('.'); // Special case for re-entering the root state on a parameter change if(this.currentState && dirtyState === this.currentState.get('path')) { this.goToState('__nullState'); } this.goToState(dirtyState); } } else { var states = get(this, 'states'); if(states && get(states, "404")) { this.goToState("404"); } } }, getState: function(route, params) { var parts = route.split('/'); parts = parts.filter(function(part) { return part !== ''; }); return this._findState(parts, this, [], [], params, false); }, /** @private Recursive helper that the state and the params if a match is found */ _findState: function(parts, state, cleanStates, dirtyStates, params) { parts = Ember.copy(parts); var hasChildren = false, name, states, childState; // sort desc based on priority states = []; for(name in state.states) { // 404 state is special and not matched childState = state.states[name]; if(name == "404" || !Ember.State.detect(childState) && !( childState instanceof Ember.State)) { continue; } states.push({ name: name, state: childState }); } states = states.sort(function(a, b) { return (b.state.get('priority') || 0) - (a.state.get('priority') || 0); }); for(var i = 0; i < states.length; i++) { name = states[i].name; childState = states[i].state; if(!( childState instanceof Ember.State)) { continue; } hasChildren = true; var result = this._matchState(parts, childState, params); if(!result) { continue; } var newParams = Ember.copy(params); jQuery.extend(newParams, result.params); var dirty = dirtyStates.length > 0 || result.dirty; var newCleanStates = cleanStates; var newDirtyStates = dirtyStates; if(dirty) { newDirtyStates = Ember.copy(newDirtyStates); newDirtyStates.push(name); } else { newCleanStates = Ember.copy(newCleanStates); newCleanStates.push(name); } result = this._findState(result.parts, childState, newCleanStates, newDirtyStates, newParams); if(result) { return result; } } if(!hasChildren && parts.length === 0) { return { state: state, params: params, cleanStates: cleanStates, dirtyStates: dirtyStates }; } return null; }, /** @private Check if a state accepts the parts with the params Returns the remaining parts as well as merged params if the state accepts. Will also set the dirty flag if the route is the same but the parameters have changed */ _matchState: function(parts, state, params) { parts = Ember.copy(parts); params = Ember.copy(params); var dirty = false; var route = get(state, 'route'); if(route) { var partDefinitions; // route could be either a string or regex if( typeof route == "string") { partDefinitions = route.split('/'); } else if( route instanceof RegExp) { partDefinitions = [route]; } else { ember_assert("route must be either a string or regexp", false); } for(var i = 0; i < partDefinitions.length; i++) { if(parts.length === 0) { return false; } var part = parts.shift(); var partDefinition = partDefinitions[i]; var partParams = this._matchPart(partDefinition, part, state); if(!partParams) { return false; } var oldParams = this.get('params') || {}; for(var param in partParams) { dirty = dirty || (oldParams[param] != partParams[param]); } jQuery.extend(params, partParams); } } var enabled = get(state, 'enabled'); if(enabled !== undefined && !enabled) { return false; } return { parts: parts, params: params, dirty: dirty }; }, /** @private Returns params if the part matches the partDefinition */ _matchPart: function(partDefinition, part, state) { var params = {}; // Handle string parts if( typeof partDefinition == "string") { switch (partDefinition.slice(0, 1)) { // 1. dynamic routes case ':': var name = partDefinition.slice(1, partDefinition.length); params[name] = part; return params; // 2. wildcard routes case '*': return {}; // 3. static routes default: if(partDefinition == part) return {}; break; } return false; } if (partDefinition instanceof RegExp) { // JS doesn't support named capture groups in Regexes so instead // we can define a list of 'captures' which maps to the matched groups var captures = get(state, 'captures'); var matches = partDefinition.exec(part); if (matches) { if (captures) { var len = captures.length, i; for(i = 0; i < len; ++i) { params[captures[i]] = matches[i+1]; } } return params; } else { return false; } } return false; }, /** Event handler for the hashchange event. Called automatically by the browser if it supports the hashchange event, or by our timer if not. */ hashChange: function(event) { var loc = window.location.hash; var routes = this; // Remove the '#' prefix loc = (loc && loc.length > 0) ? loc.slice(1, loc.length) : ''; if(!jQuery.browser.mozilla) { // because of bug https://bugzilla.mozilla.org/show_bug.cgi?id=483304 loc = decodeURI(loc); } if(get(routes, 'location') !== loc && !routes._skipRoute) { Ember.run.once(function() { routes._skipPush = true; set(routes, 'location', loc); routes._skipPush = false; }); } routes._skipRoute = false; }, popState: function(event) { var routes = this; var base = get(routes, 'baseURI'), loc = (base.charAt(0) === '/') ? document.location.pathname : document.location.href; if(loc.slice(0, base.length) === base) { // Remove the base prefix and the extra '/' loc = loc.slice(base.length + 1, loc.length); if(get(routes, 'location') !== loc && !routes._skipRoute) { Ember.run.once(function() { routes._skipPush = true; set(routes, 'location', loc); routes._skipPush = false; }); } } routes._skipRoute = false; }, // This is used to re-enter a dirty root state __nullState: Ember.State.create({enabled: false}) });
{ "content_hash": "87b3f2294cbab665006162644b6993b6", "timestamp": "", "source": "github", "line_count": 567, "max_line_length": 135, "avg_line_length": 27.894179894179896, "alnum_prop": 0.5978755690440061, "repo_name": "yadutaf/Weathermap-archive", "id": "ce322f636fa0785fe83750efef93c2457a057515", "size": "15816", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "static/js/libs/route_manager.js", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "43113" }, { "name": "JavaScript", "bytes": "638697" }, { "name": "Shell", "bytes": "7203" } ], "symlink_target": "" }
namespace OpenSubdiv { namespace OPENSUBDIV_VERSION { namespace Far { class TopologyRefiner; class Stencil; class StencilTables; class LimitStencil; class LimitStencilTables; /// \brief A specialized factory for StencilTables /// class StencilTablesFactory { public: enum Mode { INTERPOLATE_VERTEX=0, INTERPOLATE_VARYING }; struct Options { Options() : interpolationMode(INTERPOLATE_VERTEX), generateOffsets(false), generateControlVerts(false), generateIntermediateLevels(true), factorizeIntermediateLevels(true), maxLevel(10) { } unsigned int interpolationMode : 2, ///< interpolation mode generateOffsets : 1, ///< populate optional "_offsets" field generateControlVerts : 1, ///< generate stencils for control-vertices generateIntermediateLevels : 1, ///< vertices at all levels or highest only factorizeIntermediateLevels : 1, ///< accumulate stencil weights from control /// vertices or from the stencils of the /// previous level maxLevel : 4; ///< generate stencils up to 'maxLevel' }; /// \brief Instantiates StencilTables from TopologyRefiner that have been /// refined uniformly or adaptively. /// /// \note The factory only creates stencils for vertices that have already /// been refined in the TopologyRefiner. Use RefineUniform() or /// RefineAdaptive() before constructing the stencils. /// /// @param refiner The TopologyRefiner containing the topology /// /// @param options Options controlling the creation of the tables /// static StencilTables const * Create(TopologyRefiner const & refiner, Options options = Options()); /// \brief Instantiates StencilTables by concatenating an array of existing /// stencil tables. /// /// \note This factory checks that the stencil tables point to the same set /// of supporting control vertices - no re-indexing is done. /// GetNumControlVertices() *must* return the same value for all input /// tables. /// /// @param numTables Number of input StencilTables /// /// @param tables Array of input StencilTables /// static StencilTables const * Create(int numTables, StencilTables const ** tables); /// \brief Returns a KernelBatch applying all the stencil in the tables /// to primvar data. /// /// @param stencilTables The stencil tables to batch /// static KernelBatch Create(StencilTables const &stencilTables); private: // Generate stencils for the coarse control-vertices (single weight = 1.0f) static void generateControlVertStencils(int numControlVerts, Stencil & dst); }; /// \brief A specialized factory for LimitStencilTables /// /// The LimitStencilTablesFactory creates tables of limit stencils. Limit /// stencils can interpolate any arbitrary location on the limit surface. /// The stencils will be bilinear if the surface is refined uniformly, and /// bicubic if feature adaptive isolation is used instead. /// /// Surface locations are expressed as a combination of ptex face index and /// normalized (s,t) patch coordinates. The factory exposes the LocationArray /// struct as a container for these location descriptors. /// class LimitStencilTablesFactory { public: /// \brief Descriptor for limit surface locations struct LocationArray { LocationArray() : ptexIdx(-1), numLocations(0), s(0), t(0) { } int ptexIdx, ///< ptex face index numLocations; ///< number of (u,v) coordinates in the array float const * s, ///< array of u coordinates * t; ///< array of v coordinates }; typedef std::vector<LocationArray> LocationArrayVec; /// \brief Instantiates LimitStencilTables from a TopologyRefiner that has /// been refined either uniformly or adaptively. /// /// @param refiner The TopologyRefiner containing the topology /// /// @param locationArrays An array of surface location descriptors /// (see LocationArray) /// /// @param cvStencils A set of StencilTables generated from the /// TopologyRefiner (optional: prevents redundant /// instanciation of the tables if available) /// /// @param patchTables A set of PatchTables generated from the /// TopologyRefiner (optional: prevents redundant /// instanciation of the tables if available) /// static LimitStencilTables const * Create(TopologyRefiner const & refiner, LocationArrayVec const & locationArrays, StencilTables const * cvStencils=0, PatchTables const * patchTables=0); }; } // end namespace Far } // end namespace OPENSUBDIV_VERSION using namespace OPENSUBDIV_VERSION; } // end namespace OpenSubdiv #endif // FAR_STENCILTABLE_FACTORY_H
{ "content_hash": "e89c7b240c11dd1943d4b4cebc589e3a", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 98, "avg_line_length": 37.166666666666664, "alnum_prop": 0.6261210762331838, "repo_name": "jcowles/OpenSubdiv", "id": "a9a04bb0bc23597b2ed71ae954c9a58fd798f005", "size": "6647", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "opensubdiv/far/stencilTablesFactory.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "10751" }, { "name": "C++", "bytes": "4085738" }, { "name": "CMake", "bytes": "124781" }, { "name": "Cuda", "bytes": "10469" }, { "name": "GLSL", "bytes": "201807" }, { "name": "Makefile", "bytes": "1603" }, { "name": "Python", "bytes": "7424" } ], "symlink_target": "" }
import data_pipeline.sql.utils as sql_utils import data_pipeline.constants.const as const from .ddl_statement import DdlStatement class AlterStatement(DdlStatement): """Contains data necessary to produce a valid SQL ALTER statement""" def __init__(self, table_name): super(AlterStatement, self).__init__(table_name) self.statement_type = const.ALTER def add_entry(self, **kwargs): if const.ALTER_ENTRY in kwargs: self.entries.append(kwargs[const.ALTER_ENTRY]) else: alter_entry = { const.OPERATION: kwargs[const.OPERATION], const.FIELD_NAME: kwargs[const.FIELD_NAME], const.DATA_TYPE: kwargs[const.DATA_TYPE], const.PARAMS: kwargs[const.PARAMS], const.CONSTRAINTS: kwargs[const.CONSTRAINTS] } self.add_entry(alter_entry=alter_entry) def tosql(self, applier): return applier.build_alter_sql(self) def __str__(self): return sql_utils.build_alter_sql(self)
{ "content_hash": "be31095eea1997bdfb737c9056735a66", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 72, "avg_line_length": 34.096774193548384, "alnum_prop": 0.6263008514664143, "repo_name": "iagcl/data_pipeline", "id": "42bcc9088b3859d616807a94ccfe1fbf4b2cae9e", "size": "2095", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data_pipeline/sql/alter_statement.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "71156" }, { "name": "Makefile", "bytes": "3101" }, { "name": "Python", "bytes": "807620" } ], "symlink_target": "" }
import { combineReducers } from 'redux'; import {routerReducer} from 'react-router-redux'; import work from './workReducer'; const rootReducer = combineReducers({ routing: routerReducer, work: work }); export default rootReducer;
{ "content_hash": "002362551a0d1219c9cd676efaad996a", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 49, "avg_line_length": 21.363636363636363, "alnum_prop": 0.7531914893617021, "repo_name": "Bubblesphere/portfolio-deric", "id": "b4bb2e7d11496c140af1ec9533fe91af44f8c0f7", "size": "235", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/store/reducers/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "15976" }, { "name": "HTML", "bytes": "1522" }, { "name": "JavaScript", "bytes": "32769" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta charset='utf-8' /> <!-- Always force latest IE rendering engine (even in intranet) and Chrome Frame --> <meta content='IE=edge,chrome=1' http-equiv='X-UA-Compatible' /> <title>Swagger API Explorer</title> <link href='http://fonts.googleapis.com/css?family=Droid+Sans:400,700' rel='stylesheet' type='text/css' /> <link href='http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/smoothness/jquery-ui.css' media='screen' rel='stylesheet' type='text/css' /> <link href='stylesheets/screen.css' media='screen' rel='stylesheet' type='text/css' /> <script src='javascripts/app.js' type='text/javascript'></script> <script src='javascripts/swagger-service.js' type='text/javascript'></script> <script src='javascripts/swagger-ui.js' type='text/javascript'></script> </head> <body> <div id='header'> <a href="http://swagger.wordnik.com" id="logo">swagger</a> <form id='api_selector'> <div class='input'><input type="text" placeholder="http://example.com/api" name="baseUrl" id="input_baseUrl" /></div> <div class='input'><input type="text" placeholder="api_key" name="apiKey" id="input_apiKey" /></div> <div class='input'><a href="#" id="explore">Explore</a></div> </form> </div> <div class='container' id='resources_container'> <ul id='resources'></ul> </div> <script type="text/x-jquery-tmpl" id="resourceTemplate"><li class='resource' id='resource_${name}'> <div class='heading'> <h2> <a href='#!/${name}' onclick="Docs.toggleEndpointListForResource('${name}');">${path}</a> </h2> <ul class='options'> <li> <a href='#!/${name}' id='endpointListTogger_${name}' onclick="Docs.toggleEndpointListForResource('${name}');">Show/Hide</a> </li> <li> <a href='#' onclick="Docs.collapseOperationsForResource('${name}'); return false;"> List Operations </a> </li> <li> <a href='#' onclick="Docs.expandOperationsForResource('${name}'); return false;"> Expand Operations </a> </li> <li> <a href='${baseUrl}${path_json}'>Raw</a> </li> </ul> </div> <ul class='endpoints' id='${name}_endpoint_list' style='display:none'></ul> </li> </script> <script type="text/x-jquery-tmpl" id="apiTemplate"><li class='endpoint'> <ul class='operations' id='${name}_endpoint_operations'></ul> </li> </script> <script type="text/x-jquery-tmpl" id="operationTemplate"><li class='${httpMethodLowercase} operation' id='${apiName}_${nickname}_${httpMethod}'> <div class='heading'> <h3> <span class='http_method'> <a href='#!/${apiName}/${nickname}_${httpMethod}' onclick="Docs.toggleOperationContent('${apiName}_${nickname}_${httpMethod}_content');">${httpMethod}</a> </span> <span class='path'> <a href='#!/${apiName}/${nickname}_${httpMethod}' onclick="Docs.toggleOperationContent('${apiName}_${nickname}_${httpMethod}_content');">${path_json}</a> </span> </h3> <ul class='options'> <li> <a href='#!/${apiName}/${nickname}_${httpMethod}' onclick="Docs.toggleOperationContent('${apiName}_${nickname}_${httpMethod}_content');">${summary}</a> </li> </ul> </div> <div class='content' id='${apiName}_${nickname}_${httpMethod}_content' style='display:none'> {{if notes}} <h4>Implementation Notes</h4> <p>${notes}</p> {{/if}} <form accept-charset='UTF-8' action='#' class='sandbox' id='${apiName}_${nickname}_${httpMethod}_form' method='post'> <div style='margin:0;padding:0;display:inline'></div> <h4>Parameters</h4> <table class='fullwidth'> <thead> <tr> <th>Parameter</th> <th id='${apiName}_${nickname}_${httpMethod}_value_header'>Value</th> <th>Description</th> </tr> </thead> <tbody id='${apiName}_${nickname}_${httpMethod}_params'></tbody> </table> <div class='sandbox_header' id='${apiName}_${nickname}_${httpMethod}_content_sandbox_response_header'> <input class='submit' id='${apiName}_${nickname}_${httpMethod}_content_sandbox_response_button' name='commit' type='button' value='Try it out!' /> <a href='#' id='${apiName}_${nickname}_${httpMethod}_content_sandbox_response_hider' onclick="$('#${apiName}_${nickname}_${httpMethod}_content_sandbox_response').slideUp();$(this).fadeOut(); return false;" style='display:none'>Hide Response</a> <img alt='Throbber' id='${apiName}_${nickname}_${httpMethod}_content_sandbox_response_throbber' src='http://swagger.wordnik.com/images/throbber.gif' style='display:none' /> </div> </form> <div class='response' id='${apiName}_${nickname}_${httpMethod}_content_sandbox_response' style='display:none'> <h4>Request URL</h4> <div class='block request_url'></div> <h4>Response Body</h4> <div class='block response_body'></div> <h4>Response Code</h4> <div class='block response_code'></div> <h4>Response Headers</h4> <div class='block response_headers'></div> </div> </div> </li> </script> <script type="text/x-jquery-tmpl" id="paramTemplate"><tr> <td class='code'>${name}</td> <td> <input minlength='0' name='${name}' placeholder='' type='text' value='' /> </td> <td width='500'>${description}</td> </tr> </script> <script type="text/x-jquery-tmpl" id="paramTemplateSelect"><tr> <td class='code'>${name}</td> <td> <select name='${name}'> {{if required == false }} <option selected='selected' value=''></option> {{/if}} {{each allowableValues.values}} {{if $value == defaultValue && required == true }} <option selected='selected' value='${$value}'>${$value}</option> {{else}} <option value='${$value}'>${$value}</option> {{/if}} {{/each}} </select> </td> <td width='500'>${description}</td> </tr> </script> <script type="text/x-jquery-tmpl" id="paramTemplateRequired"><tr> <td class='code required'>${name}</td> <td> <input class='required' minlength='1' name='${name}' placeholder='(required)' type='text' value='' /> </td> <td width='500'> <strong>${description}</strong> </td> </tr> </script> <script type="text/x-jquery-tmpl" id="paramTemplateRequiredReadOnly"><tr> <td class='code required'>${name}</td> <td>-</td> <td width='500'>${description}</td> </tr> </script> <script type="text/x-jquery-tmpl" id="paramTemplateReadOnly"><tr> <td class='code'>${name}</td> <td>-</td> <td width='500'>${description}</td> </tr> </script> <div id='content_message'> Enter the base URL of the API that you wish to explore, or try <a onclick="$('#input_baseUrl').val('http://petstore.swagger.wordnik.com/api/resources.json'); apiSelectionController.showApi(); return false;" href="#">petstore.swagger.wordnik.com/api/resources.json</a> </div> <p id='colophon' style='display:none'> Sexy API documentation from <a href="http://swagger.wordnik.com">Swagger</a>. </p> </body> </html>
{ "content_hash": "733c3befe13687dba34f01e6de3ce216", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 256, "avg_line_length": 45.97041420118343, "alnum_prop": 0.5697000901016862, "repo_name": "schmurfy/grape_apidoc", "id": "46cd06b02ee95fef2fa27f4696d9d02a38f1d6af", "size": "7769", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vendor/swagger/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "9459" } ], "symlink_target": "" }
package Nov2020Leetcode; public class _0004MedianOfTwoSortedArrays { public static void main(String[] args) { System.out.println(findMedianSortedArrays(new int[] { 1, 3 }, new int[] { 2 })); System.out.println(findMedianSortedArrays(new int[] { 1, 2 }, new int[] { 3, 4 })); System.out.println(findMedianSortedArrays(new int[] { 0, 0 }, new int[] { 0, 0 })); System.out.println(findMedianSortedArrays(new int[] {}, new int[] { 1 })); System.out.println(findMedianSortedArrays(new int[] { 2 }, new int[] {})); } public static double findMedianSortedArrays(int[] nums1, int[] nums2) { int lengthSum = nums1.length + nums2.length; int leftIndex = 0, rightIndex = 0; boolean includeTwoElements = false; if ((lengthSum) % 2 == 0) { leftIndex = lengthSum / 2 - 1; rightIndex = lengthSum / 2; includeTwoElements = true; } else { rightIndex = lengthSum / 2; leftIndex = rightIndex; } int index = 0; int leftVal = 0; int rightVal = 0; int leftArrayIndex = 0, rightArrayIndex = 0; while (index <= rightIndex) { int val = 0; if (leftArrayIndex < nums1.length && rightArrayIndex < nums2.length) { if (nums1[leftArrayIndex] < nums2[rightArrayIndex]) { val = nums1[leftArrayIndex]; leftArrayIndex++; } else { val = nums2[rightArrayIndex]; rightArrayIndex++; } } else if (leftArrayIndex < nums1.length) { val = nums1[leftArrayIndex]; leftArrayIndex++; } else { val = nums2[rightArrayIndex]; rightArrayIndex++; } if (index == leftIndex) { leftVal = val; } else if (index == rightIndex) { rightVal = val; break; } index++; } return includeTwoElements ? (double) (leftVal + rightVal) / 2 : (double) leftVal; } }
{ "content_hash": "33a7e7a5424066ac32213453e6e463ae", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 85, "avg_line_length": 30.017241379310345, "alnum_prop": 0.6410109132682367, "repo_name": "darshanhs90/Java-InterviewPrep", "id": "30ba6c415ab3efc952effcca6288f959271d851e", "size": "1741", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Nov2020Leetcode/_0004MedianOfTwoSortedArrays.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1870066" } ], "symlink_target": "" }
<?xml version="1.0"?> <project name="@proyecto@" basedir="." default="desplegarWar"> <property name="project" value="@proyecto@" /> <property name="ox3" value="true" /> <property file="../openxava.properties"/> <!-- Compila todos los .java y .groovy No necesitas llamarla si trabajas dentro de Eclipse --> <target name="compilar"> <ant antfile="../OpenXava/build.xml" target="compile"/> </target> <!-- Construye y despliega la aplicación en formato .war --> <target name="desplegarWar"> <!-- En un directorio --> <ant antfile="../OpenXava/build.xml" target="deploy"/> <!-- En un archivo (no funciona muy bien en windows + tomcat) <ant antfile="../OpenXava/build.xml" target="deployWar"/> --> </target> <!-- Construye la aplicación en formato portlets. --> <target name="generarPortlets"> <ant antfile="../OpenXava/build.xml" target="generatePortlets"/> </target> <!-- Actualiza este proyecto con la versión de OpenXava presente en el workspace. Ha de llamarse después de actualizar la versión de OpenXava. --> <target name="actualizarOX"> <ant antfile="../OpenXava/build.xml" target="updateOX"/> </target> <!-- Se conecta a tu base de datos y actualiza el esquema para que conincida con el actual de tu aplicación. Recuerda dar valor a la propiedad schema.path. (También puedes usar directamente la tarea ant 'hibernatetool') --> <target name="actualizarEsquema"> <ant antfile="../OpenXava/build.xml" target="updateSchemaJPA"> <property name="persistence.unit" value="junit"/> <property name="schema.path" value="PON AQUÍ LA RUTA DEL CONTROLADOR JDBC"/> </ant> </target> </project>
{ "content_hash": "edf014312b7e0e4941cd48af5a0f82f8", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 79, "avg_line_length": 31.166666666666668, "alnum_prop": 0.6773618538324421, "repo_name": "jecuendet/maven4openxava", "id": "3fba08a3b15e38b736b0bd0b7f0f96da0160b18d", "size": "1691", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "dist/openxava/workspace/OpenXavaPlantilla/build.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1695359" }, { "name": "Groovy", "bytes": "105862" }, { "name": "Java", "bytes": "4269286" }, { "name": "JavaScript", "bytes": "4897092" }, { "name": "Shell", "bytes": "65963" }, { "name": "XSLT", "bytes": "3987" } ], "symlink_target": "" }
<?php /* Layout File, at least one main region must be added; */ $type = 'wide'; include __DIR__ . "/header.php"; include __DIR__ . "/index.php"; include __DIR__ . "/footer.php";
{ "content_hash": "f5df026f017ceca270a25643fe6cf2d0", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 52, "avg_line_length": 16.333333333333332, "alnum_prop": 0.5510204081632653, "repo_name": "sedici/wpmu-istec", "id": "a798e522e184cfe860be2672335d10c0898edb11", "size": "196", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wp-content/themes/upfront/layouts/index-wide.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "616" }, { "name": "Batchfile", "bytes": "166" }, { "name": "CSS", "bytes": "3940197" }, { "name": "HTML", "bytes": "282386" }, { "name": "JavaScript", "bytes": "5863354" }, { "name": "PHP", "bytes": "17942125" }, { "name": "Shell", "bytes": "3301" } ], "symlink_target": "" }
package org.lambda3.indra.filter; import java.util.LinkedList; import java.util.List; public class FilterChain implements Filter { private List<Filter> filters = new LinkedList<>(); private FilterChain() { } public static FilterChain get() { return new FilterChain(); } public FilterChain add(Filter filter) { filters.add(filter); return this; } @Override public boolean matches(String t1, String t2) { for (Filter f : filters) { if (f.matches(t1, t2)) { return true; } } return false; } }
{ "content_hash": "4e020d4aae36bfe4c6ee529ec3987274", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 54, "avg_line_length": 17.97142857142857, "alnum_prop": 0.5771065182829889, "repo_name": "Lambda-3/indra", "id": "b654bc019033de12bb9f94f5cde83a2cc910b7d2", "size": "2063", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "indra-essentials/src/main/java/org/lambda3/indra/filter/FilterChain.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "104464" }, { "name": "Shell", "bytes": "581" } ], "symlink_target": "" }
package org.apache.tinkerpop.gremlin.process.traversal.dsl.graph; import org.apache.tinkerpop.gremlin.process.computer.GraphComputer; import org.apache.tinkerpop.gremlin.process.traversal.TraversalEngine; import org.apache.tinkerpop.gremlin.process.traversal.TraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategies; import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategy; import org.apache.tinkerpop.gremlin.process.traversal.engine.ComputerTraversalEngine; import org.apache.tinkerpop.gremlin.process.traversal.engine.StandardTraversalEngine; import org.apache.tinkerpop.gremlin.process.traversal.step.map.AddVertexStartStep; import org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.GraphStep; import org.apache.tinkerpop.gremlin.process.traversal.step.util.PathIdentityStep; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Graph; import org.apache.tinkerpop.gremlin.structure.Transaction; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.structure.util.StringFactory; import org.apache.tinkerpop.gremlin.util.function.ConstantSupplier; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.BinaryOperator; import java.util.function.Supplier; import java.util.function.UnaryOperator; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public class GraphTraversalSource implements TraversalSource { public static Builder standard() { return GraphTraversalSource.build().engine(StandardTraversalEngine.build()); } public static Builder computer() { return GraphTraversalSource.build().engine(ComputerTraversalEngine.build()); } public static Builder computer(final Class<? extends GraphComputer> graphComputerClass) { return GraphTraversalSource.build().engine(ComputerTraversalEngine.build().computer(graphComputerClass)); } //// private final transient Graph graph; private final TraversalEngine.Builder engineBuilder; private final TraversalStrategies strategies; private final List<TraversalStrategy> withStrategies; private final List<Class<? extends TraversalStrategy>> withoutStrategies; private GraphTraversalSource(final Graph graph, final TraversalEngine.Builder engineBuilder, final List<TraversalStrategy> withStrategies, final List<Class<? extends TraversalStrategy>> withoutStrategies) { this.graph = graph; this.engineBuilder = engineBuilder; this.withStrategies = withStrategies; this.withoutStrategies = withoutStrategies; this.withStrategies.addAll(engineBuilder.getWithStrategies()); this.withoutStrategies.addAll(engineBuilder.getWithoutStrategies()); final TraversalStrategies tempStrategies = TraversalStrategies.GlobalCache.getStrategies(this.graph.getClass()); this.strategies = withStrategies.isEmpty() && withoutStrategies.isEmpty() ? tempStrategies : tempStrategies.clone() .addStrategies(withStrategies.toArray(new TraversalStrategy[withStrategies.size()])) .removeStrategies(withoutStrategies.toArray(new Class[withoutStrategies.size()])); } private <S> GraphTraversal.Admin<S, S> generateTraversal() { final GraphTraversal.Admin<S, S> traversal = new DefaultGraphTraversal<>(this.graph); final TraversalEngine engine = this.engineBuilder.create(this.graph); traversal.setEngine(engine); traversal.setStrategies(this.strategies); return traversal; } public <S> GraphTraversal<S, S> inject(S... starts) { return (GraphTraversal<S, S>) this.generateTraversal().inject(starts); } /** * @deprecated As of release 3.1.0, replaced by {@link #addV()} */ @Deprecated public GraphTraversal<Vertex, Vertex> addV(final Object... keyValues) { final GraphTraversal.Admin<Vertex, Vertex> traversal = this.generateTraversal(); traversal.addStep(new AddVertexStartStep(traversal, null)); ((AddVertexStartStep) traversal.getEndStep()).addPropertyMutations(keyValues); return traversal; } public GraphTraversal<Vertex, Vertex> addV(final String label) { final GraphTraversal.Admin<Vertex, Vertex> traversal = this.generateTraversal(); return traversal.addStep(new AddVertexStartStep(traversal, label)); } public GraphTraversal<Vertex, Vertex> addV() { final GraphTraversal.Admin<Vertex, Vertex> traversal = this.generateTraversal(); return traversal.addStep(new AddVertexStartStep(traversal, null)); } public GraphTraversal<Vertex, Vertex> V(final Object... vertexIds) { final GraphTraversal.Admin<Vertex, Vertex> traversal = this.generateTraversal(); return traversal.addStep(new GraphStep<>(traversal, Vertex.class, vertexIds)); } public GraphTraversal<Edge, Edge> E(final Object... edgesIds) { final GraphTraversal.Admin<Edge, Edge> traversal = this.generateTraversal(); return traversal.addStep(new GraphStep<>(traversal, Edge.class, edgesIds)); } //// UTILITIES public GraphTraversalSourceStub withSideEffect(final String key, final Supplier supplier) { final GraphTraversal.Admin traversal = this.generateTraversal(); traversal.getSideEffects().registerSupplier(key, supplier); return new GraphTraversalSourceStub(traversal, false); } public GraphTraversalSourceStub withSideEffect(final String key, final Object object) { final GraphTraversal.Admin traversal = this.generateTraversal(); traversal.getSideEffects().registerSupplier(key, new ConstantSupplier<>(object)); return new GraphTraversalSourceStub(traversal, false); } public <A> GraphTraversalSourceStub withSack(final A initialValue) { return this.withSack(initialValue, null, null); } public <A> GraphTraversalSourceStub withSack(final Supplier<A> initialValue) { final GraphTraversal.Admin traversal = this.generateTraversal(); traversal.getSideEffects().setSack(initialValue, null, null); return new GraphTraversalSourceStub(traversal, false); } public <A> GraphTraversalSourceStub withSack(final Supplier<A> initialValue, final UnaryOperator<A> splitOperator) { return this.withSack(initialValue, splitOperator, null); } public <A> GraphTraversalSourceStub withSack(final A initialValue, final UnaryOperator<A> splitOperator) { return this.withSack(initialValue, splitOperator, null); } public <A> GraphTraversalSourceStub withSack(final Supplier<A> initialValue, final BinaryOperator<A> mergeOperator) { return this.withSack(initialValue, null, mergeOperator); } public <A> GraphTraversalSourceStub withSack(final A initialValue, final BinaryOperator<A> mergeOperator) { return this.withSack(initialValue, null, mergeOperator); } public <A> GraphTraversalSourceStub withSack(final Supplier<A> initialValue, final UnaryOperator<A> splitOperator, final BinaryOperator<A> mergeOperator) { final GraphTraversal.Admin traversal = this.generateTraversal(); traversal.getSideEffects().setSack(initialValue, splitOperator, mergeOperator); return new GraphTraversalSourceStub(traversal, false); } public <A> GraphTraversalSourceStub withSack(final A initialValue, final UnaryOperator<A> splitOperator, final BinaryOperator<A> mergeOperator) { final GraphTraversal.Admin traversal = this.generateTraversal(); traversal.getSideEffects().setSack(new ConstantSupplier<>(initialValue), splitOperator, mergeOperator); return new GraphTraversalSourceStub(traversal, false); } public <S> GraphTraversalSourceStub withPath() { return new GraphTraversalSourceStub(this.generateTraversal(), true); } public Transaction tx() { return this.graph.tx(); } public static Builder build() { return new Builder(); } @Override public List<TraversalStrategy> getStrategies() { return Collections.unmodifiableList(this.strategies.toList()); } @Override public Optional<GraphComputer> getGraphComputer() { return this.engineBuilder.create(this.graph).getGraphComputer(); } @Override public Optional<Graph> getGraph() { return Optional.ofNullable(this.graph); } @Override public GraphTraversalSource.Builder asBuilder() { final GraphTraversalSource.Builder builder = GraphTraversalSource.build().engine(this.engineBuilder); this.withStrategies.forEach(builder::with); this.withoutStrategies.forEach(builder::without); return builder; } @Override public String toString() { return StringFactory.traversalSourceString(this); } ////// public final static class Builder implements TraversalSource.Builder<GraphTraversalSource> { private TraversalEngine.Builder engineBuilder = StandardTraversalEngine.build(); private List<TraversalStrategy> withStrategies = new ArrayList<>(); private List<Class<? extends TraversalStrategy>> withoutStrategies = new ArrayList<>(); private Builder() { } @Override public Builder engine(final TraversalEngine.Builder engineBuilder) { this.engineBuilder = engineBuilder; return this; } @Override public Builder with(final TraversalStrategy strategy) { this.withStrategies.add(strategy); return this; } @Override public TraversalSource.Builder without(final Class<? extends TraversalStrategy> strategyClass) { this.withoutStrategies.add(strategyClass); return this; } @Override public GraphTraversalSource create(final Graph graph) { return new GraphTraversalSource(graph, this.engineBuilder, this.withStrategies, this.withoutStrategies); } } public static class GraphTraversalSourceStub { private final GraphTraversal.Admin traversal; private boolean withPaths; public GraphTraversalSourceStub(final GraphTraversal.Admin traversal, final boolean withPaths) { this.traversal = traversal; this.withPaths = withPaths; } public <S> GraphTraversal<S, S> inject(S... starts) { this.traversal.inject(starts); return ((this.withPaths) ? this.traversal.addStep(new PathIdentityStep<>(this.traversal)) : this.traversal); } /** * @deprecated As of release 3.1.0, replaced by {@link #addV()} */ @Deprecated public GraphTraversal<Vertex, Vertex> addV(final Object... keyValues) { this.traversal.addStep(new AddVertexStartStep(this.traversal, null)); ((AddVertexStartStep) this.traversal.getEndStep()).addPropertyMutations(keyValues); return ((this.withPaths) ? this.traversal.addStep(new PathIdentityStep<>(this.traversal)) : this.traversal); } public GraphTraversal<Vertex, Vertex> addV(final String label) { this.traversal.addStep(new AddVertexStartStep(this.traversal, label)); return ((this.withPaths) ? this.traversal.addStep(new PathIdentityStep<>(this.traversal)) : this.traversal); } public GraphTraversal<Vertex, Vertex> addV() { this.traversal.addStep(new AddVertexStartStep(this.traversal, null)); return ((this.withPaths) ? this.traversal.addStep(new PathIdentityStep<>(this.traversal)) : this.traversal); } public GraphTraversal<Vertex, Vertex> V(final Object... vertexIds) { this.traversal.addStep(new GraphStep<>(this.traversal, Vertex.class, vertexIds)); return ((this.withPaths) ? this.traversal.addStep(new PathIdentityStep<>(this.traversal)) : this.traversal); } public GraphTraversal<Edge, Edge> E(final Object... edgesIds) { this.traversal.addStep(new GraphStep<>(this.traversal, Edge.class, edgesIds)); return ((this.withPaths) ? this.traversal.addStep(new PathIdentityStep<>(this.traversal)) : this.traversal); } //// UTILITIES public GraphTraversalSourceStub withSideEffect(final String key, final Supplier supplier) { this.traversal.getSideEffects().registerSupplier(key, supplier); return this; } public GraphTraversalSourceStub withSideEffect(final String key, final Object object) { this.traversal.getSideEffects().registerSupplier(key, new ConstantSupplier<>(object)); return this; } public <A> GraphTraversalSourceStub withSack(final A initialValue) { this.traversal.getSideEffects().setSack(new ConstantSupplier<>(initialValue), null, null); return this; } public <A> GraphTraversalSourceStub withSack(final Supplier<A> initialValue) { this.traversal.getSideEffects().setSack(initialValue, null, null); return this; } public <A> GraphTraversalSourceStub withSack(final Supplier<A> initialValue, final UnaryOperator<A> splitOperator) { this.traversal.getSideEffects().setSack(initialValue, splitOperator, null); return this; } public <A> GraphTraversalSourceStub withSack(final A initialValue, final UnaryOperator<A> splitOperator) { this.traversal.getSideEffects().setSack(new ConstantSupplier<>(initialValue), splitOperator, null); return this; } public <A> GraphTraversalSourceStub withSack(final Supplier<A> initialValue, final BinaryOperator<A> mergeOperator) { this.traversal.getSideEffects().setSack(initialValue, null, mergeOperator); return this; } public <A> GraphTraversalSourceStub withSack(final A initialValue, final BinaryOperator<A> mergeOperator) { this.traversal.getSideEffects().setSack(new ConstantSupplier<>(initialValue), null, mergeOperator); return this; } public <A> GraphTraversalSourceStub withSack(final Supplier<A> initialValue, final UnaryOperator<A> splitOperator, final BinaryOperator<A> mergeOperator) { this.traversal.getSideEffects().setSack(initialValue, splitOperator, mergeOperator); return this; } public <A> GraphTraversalSourceStub withSack(final A initialValue, final UnaryOperator<A> splitOperator, final BinaryOperator<A> mergeOperator) { this.traversal.getSideEffects().setSack(new ConstantSupplier<>(initialValue), splitOperator, mergeOperator); return this; } public GraphTraversalSourceStub withPath() { this.withPaths = true; return this; } } }
{ "content_hash": "b02854f0aa6dcc716f6d6eff4c0739f4", "timestamp": "", "source": "github", "line_count": 342, "max_line_length": 210, "avg_line_length": 44.12865497076023, "alnum_prop": 0.7085873310363107, "repo_name": "rmagen/incubator-tinkerpop", "id": "fe0694859d01f6e65f95e43ca436cc6bcb8a924b", "size": "15897", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/dsl/graph/GraphTraversalSource.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4544" }, { "name": "Groovy", "bytes": "317647" }, { "name": "Java", "bytes": "5590925" }, { "name": "Python", "bytes": "1481" }, { "name": "Shell", "bytes": "15070" } ], "symlink_target": "" }
set -e SCRIPT_LOCATION=$(cd "$(dirname "$0")"; pwd) . ${SCRIPT_LOCATION}/common.sh usage() { echo "Usage: $0 [-q only quick tests] [-l preload library path] \\" echo " [-c cache plugin binary] \\" echo " <unittests binary> <XML output location>" echo "This script runs the CernVM-FS unit tests" exit 1 } CVMFS_UNITTESTS_QUICK=0 CVMFS_LIBRARY_PATH= CVMFS_CACHE_PLUGIN= while getopts "ql:c:" option; do case $option in q) CVMFS_UNITTESTS_QUICK=1 ;; l) CVMFS_LIBRARY_PATH=$OPTARG ;; c) CVMFS_CACHE_PLUGIN=$OPTARG ;; ?) usage ;; esac done shift $(( $OPTIND - 1 )) if [ $# -lt 2 ]; then usage fi CVMFS_UNITTESTS_BINARY=$1 CVMFS_UNITTESTS_RESULT_LOCATION=$2 # configure manual library path if needed if [ ! -z $CVMFS_LIBRARY_PATH ]; then echo "using custom library path: '$CVMFS_LIBRARY_PATH'" if is_linux; then export LD_LIBRARY_PATH="$CVMFS_LIBRARY_PATH" elif is_macos; then export DYLD_LIBRARY_PATH="$CVMFS_LIBRARY_PATH" else die "who am i on? $(uname -a)" fi fi # check if only a quick subset of the unittests should be run test_filter='-' if [ $CVMFS_UNITTESTS_QUICK = 1 ]; then echo "running only quick tests (without suffix 'Slow')" test_filter='-*Slow' fi # run the cache plugin unittests if [ "x$CVMFS_CACHE_PLUGIN" != "x" ]; then CVMFS_CACHE_UNITTESTS="$(dirname $CVMFS_UNITTESTS_BINARY)/cvmfs_test_cache" CVMFS_CACHE_LOCATOR=tcp=127.0.0.1:4224 CVMFS_CACHE_CONFIG=$(mktemp /tmp/cvmfs-unittests-XXXXX) echo "CVMFS_CACHE_PLUGIN_LOCATOR=$CVMFS_CACHE_LOCATOR" > $CVMFS_CACHE_CONFIG echo "CVMFS_CACHE_PLUGIN_SIZE=1000" >> $CVMFS_CACHE_CONFIG echo "CVMFS_CACHE_PLUGIN_TEST=yes" >> $CVMFS_CACHE_CONFIG for plugin in $(echo $CVMFS_CACHE_PLUGIN | tr : " "); do if [ -x $plugin ]; then echo "running unit tests for cache plugin $plugin" # All our plugins take a configuration file as a parameter plugin_pid="$($plugin $CVMFS_CACHE_CONFIG)" echo "cache plugin started as PID $plugin_pid" $CVMFS_CACHE_UNITTESTS $CVMFS_CACHE_LOCATOR \ --gtest_output=xml:${CVMFS_UNITTESTS_RESULT_LOCATION}.$(basename $plugin) /bin/kill $plugin_pid else echo "Warning: plugin $plugin not found, skipping" fi done rm -f $CVMFS_CACHE_CONFIG fi # run the unit tests echo "running unit tests (with XML output $CVMFS_UNITTESTS_RESULT_LOCATION)..." $CVMFS_UNITTESTS_BINARY --gtest_shuffle \ --gtest_output=xml:$CVMFS_UNITTESTS_RESULT_LOCATION \ --gtest_filter=$test_filter
{ "content_hash": "03d5047c2ce8636abc8b88a66b48c595", "timestamp": "", "source": "github", "line_count": 90, "max_line_length": 81, "avg_line_length": 29.233333333333334, "alnum_prop": 0.6446218167996959, "repo_name": "djw8605/cvmfs", "id": "c6ae13e7b7ab312f6890f6f2466ead0e0f838b91", "size": "2699", "binary": false, "copies": "1", "ref": "refs/heads/devel", "path": "ci/run_unittests.sh", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "7840734" }, { "name": "C++", "bytes": "4137332" }, { "name": "CMake", "bytes": "114971" }, { "name": "Makefile", "bytes": "7689" }, { "name": "Perl", "bytes": "422055" }, { "name": "Python", "bytes": "92070" }, { "name": "Shell", "bytes": "830751" } ], "symlink_target": "" }
%% %% Qt5xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 5 %% %% Copyright (C) 2020 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com> %% $project=Qt5xHb $module=QtCore $header $includes $beginSlotsClass $signal=|aboutToBlock() $signal=|awake() $endSlotsClass
{ "content_hash": "3d369b029ab950b8dcc0547757640c62", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 79, "avg_line_length": 16.823529411764707, "alnum_prop": 0.7482517482517482, "repo_name": "marcosgambeta/Qt5xHb", "id": "0e129c6210e5be608b05760c28b95183b90aa0b9", "size": "286", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "codegen/QtCore/QAbstractEventDispatcherSlots.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "32864" }, { "name": "C", "bytes": "450079" }, { "name": "C++", "bytes": "2140920" }, { "name": "Charity", "bytes": "8108" }, { "name": "Makefile", "bytes": "250157" }, { "name": "QML", "bytes": "894" }, { "name": "xBase", "bytes": "18166801" } ], "symlink_target": "" }
<?php namespace Application\Migrations; use Doctrine\DBAL\Migrations\AbstractMigration, Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your need! */ class Version20120731121452 extends AbstractMigration { public function up(Schema $schema) { // this up() migration is autogenerated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql"); } public function down(Schema $schema) { // this down() migration is autogenerated, please modify it to your needs $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql"); } }
{ "content_hash": "c9e4a41f1e5cb3698403f3abd2323a43", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 87, "avg_line_length": 27.23076923076923, "alnum_prop": 0.6709039548022598, "repo_name": "forsaken17/uni", "id": "1ba85c996a49794659bc5b822ac798cc9f69cce4", "size": "708", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/DoctrineMigrations/Version20120731121452.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "309" }, { "name": "PHP", "bytes": "141610" } ], "symlink_target": "" }
package de.knightsoftnet.mtwidgets.client.ui.widget.helper; import com.google.gwt.i18n.client.DateTimeFormat; import com.google.gwt.text.shared.Parser; import org.apache.commons.lang3.StringUtils; import java.text.ParseException; import java.util.Date; import java.util.Objects; /** * parse text to date value. * * @author Manfred Tremmel */ public class TimeParser implements Parser<Date> { private static volatile TimeParser instanceParser = null; private final DateTimeFormat dateTimeFormat; /** * returns the instance. * * @return Parser */ public static final Parser<Date> instance() { // NOPMD it's thread save! if (TimeParser.instanceParser == null) { synchronized (TimeParser.class) { if (TimeParser.instanceParser == null) { TimeParser.instanceParser = new TimeParser("HH:mm:ss"); } } } return TimeParser.instanceParser; } public TimeParser(final String pformat) { super(); this.dateTimeFormat = DateTimeFormat.getFormat(pformat); } @Override public final Date parse(final CharSequence pobject) throws ParseException { if (StringUtils.isEmpty(Objects.toString(pobject))) { return null; } try { if (StringUtils.countMatches(pobject, ':') == 2) { return this.dateTimeFormat.parse(Objects.toString(pobject)); } return this.dateTimeFormat.parse(Objects.toString(pobject) + ":00"); // NOPMD } catch (final IllegalArgumentException e) { throw new ParseException(e.getMessage(), 0); // NOPMD, we needn't a stack trace } } }
{ "content_hash": "e9fd926c0dc7d786be40cfdbb8b52df2", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 85, "avg_line_length": 26.483333333333334, "alnum_prop": 0.6884833228445564, "repo_name": "ManfredTremmel/gwt-mt-widgets", "id": "56498c2060ff22243436703f164c8e6a1862afa6", "size": "2378", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/de/knightsoftnet/mtwidgets/client/ui/widget/helper/TimeParser.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "390480" } ], "symlink_target": "" }
package io.subutai.core.peer.api; /** * Peer action listener interface */ public interface PeerActionListener { public String getName(); public PeerActionResponse onPeerAction( PeerAction peerAction ); }
{ "content_hash": "fd5f7187c25b0c4c6efbcc0b029d6155", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 68, "avg_line_length": 18.083333333333332, "alnum_prop": 0.7465437788018433, "repo_name": "subutai-io/base", "id": "399cb80966f033635781ffc75b27ccb6db1d8f9c", "size": "217", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "management/server/core/peer-manager/peer-manager-api/src/main/java/io/subutai/core/peer/api/PeerActionListener.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "171335" }, { "name": "HTML", "bytes": "208876" }, { "name": "Java", "bytes": "3733788" }, { "name": "JavaScript", "bytes": "699472" }, { "name": "Shell", "bytes": "30183" } ], "symlink_target": "" }
/** * @file CompTree.js * @brief tree manager for component * @license MIT */ const Tree = require("./Tree.js"); const comutl = mofron.util.common; const cmputl = mofron.util.component; module.exports = class extends Tree { addChild (chd, idx) { try { if (true === Array.isArray(chd)) { /* parameter check */ for (let cidx in chd) { this.addChild(chd[cidx], idx); } return; } /* set parent-child relation in dom layer */ let rdom = chd.rootDom(); if (undefined === idx) { this.target().childDom().child(rdom); } else { let tgt_tree = this.target().childDom().getTree(); let t_idx = tgt_tree.getIndex(this.target().child()[idx].rootDom()[0]); tgt_tree.addChild(rdom, t_idx); } /* set parent-child relation in component layer */ super.addChild(chd, idx); /* check render */ if (true === this.target().isExists()) { let lo = chd.layout(); /* layout */ for(let lidx in lo) { lo[lidx].execute(); } /* parent layout */ lo = this.target().layout(); for(let lidx2 in lo) { lo[lidx2].execute(); } /* theme */ cmputl.theme(chd, this.target().theme()); cmputl.theme(chd, cmputl.follow_theme(this.target())); /* render child */ cmputl.render(chd); } } catch (e) { console.error(e.stack); throw e; } } replace (o_chd, n_chd) { try { if (this.target().childDom().id() === o_chd.childDom().id()) { /* old child is dom target, replace dom target */ this.target().childDom(n_chd.childDom()); } /* set parent-child relation in component layer */ this.getChild().splice(this.getIndex(o_chd), 0 , n_chd) n_chd.parent(this.target()); /* set parent-child relation in dom layer */ let tgt_tree = o_chd.rootDom()[0].parent().getTree(); let rep_idx = tgt_tree.getIndex(o_chd.rootDom()[0]); let n_rdom = n_chd.rootDom(); for (let ridx in n_rdom) { tgt_tree.getChild().splice(rep_idx+(parseInt(ridx)), 0, n_rdom[ridx]); n_rdom[ridx].parent(this.target().childDom()); } if (true === o_chd.isExists()) { cmputl.render(n_chd); } o_chd.destroy() } catch (e) { console.error(e.stack); throw e; } } delChild (chd) { try { /* release relational in dom layer */ let rdom = chd.rootDom(); for (let ridx in rdom) { if (null !== rdom[ridx].parent()) { rdom[ridx].parent().getTree().delChild(rdom[ridx]); } } /* delete child component */ super.delChild(chd); } catch (e) { console.error(e.stack); throw e; } } } /* end of file */
{ "content_hash": "c82c3358392919cbc1bda6e62c516208", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 90, "avg_line_length": 28.77570093457944, "alnum_prop": 0.487820721013316, "repo_name": "mofron/mofron", "id": "dc33ddbfc15f6ec4b59beda8bdedcd7cbb09c0e4", "size": "3079", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/core/tree/CompTree.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "126758" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.renesansz.androidtoolbar"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:uiOptions="splitActionBarWhenNarrow" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
{ "content_hash": "94ebe6a63caafe676427a3d18f793bf6", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 76, "avg_line_length": 34.714285714285715, "alnum_prop": 0.6310013717421125, "repo_name": "renesansz/VogellaExercises", "id": "2f2c08c0705102c5594654a4ec6c0cebead3c1d1", "size": "729", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AndroidToolbar/app/src/main/AndroidManifest.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "89406" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using Bridge.Html5; using System.Runtime.CompilerServices; using System.Text; namespace Granular.Host { public static class ElementExtensions { [Bridge.Template("{element}.setSelectionRange({index}, {index})")] public static extern void SetCaretIndex(this HTMLElement element, int index); [Bridge.Template("{element}.selectionStart")] public static extern int GetSelectionStart(this HTMLElement element); [Bridge.Template("{element}.selectionStart = {value}")] public static extern void SetSelectionStart(this HTMLElement element, int value); [Bridge.Template("{element}.selectionEnd")] public static extern int GetSelectionEnd(this HTMLElement element); [Bridge.Template("{element}.selectionEnd = {value}")] public static extern void SetSelectionEnd(this HTMLElement element, int value); [Bridge.Template("{element}.value")] public static extern string GetValue(this HTMLElement element); [Bridge.Template("{element}.value = {value}")] public static extern void SetValue(this HTMLElement element, string value); } }
{ "content_hash": "9db3506e74d4cc8199c9a13f27aca942", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 89, "avg_line_length": 38.40625, "alnum_prop": 0.6891781936533767, "repo_name": "yuvaltz/Granular", "id": "0476ac49dd4458c971c8df34589e206f590c543e", "size": "1231", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Granular.Host.Web/ElementExtensions.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "792" }, { "name": "C#", "bytes": "2090742" }, { "name": "HTML", "bytes": "1337" }, { "name": "PowerShell", "bytes": "5334" } ], "symlink_target": "" }
<ion-navbar *navbar> <ion-buttons start> <button menuToggle> <ion-icon name="menu"></ion-icon> </button> </ion-buttons> <ion-title>Projects</ion-title> <ion-buttons end> <button (click)="toggleSearchActive()"> <ion-icon name="search"></ion-icon> </button> </ion-buttons> </ion-navbar> <ion-content> <ion-pane> <ion-searchbar *ngIf="searchActive" [(ngModel)]="projectQuery"></ion-searchbar> <project-list [projects]="projects | projectSort:projectQuery" *ngIf="projects.length > 0"></project-list> <button fab fab-right fab-bottom (click)="createProject($event)"> <ion-icon name="add"></ion-icon> </button> </ion-pane> </ion-content>
{ "content_hash": "b08a6ef3e6662263a682cf83b0080250", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 110, "avg_line_length": 31.681818181818183, "alnum_prop": 0.642754662840746, "repo_name": "CompassSoftware/xpsp", "id": "4f1d5289f1985f840d55cf5bc79466f5d43e92ea", "size": "697", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/pages/projects/projects.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "5978" }, { "name": "HTML", "bytes": "10116" }, { "name": "JavaScript", "bytes": "9271" }, { "name": "TypeScript", "bytes": "39017" } ], "symlink_target": "" }
{% extends 'base.html' %}{% load mptt_tags %}{% load compress %}{% load cache %} {% block content %} <div class="page-header"> <h1>{{ game.name }}</h1> </div> <div> <h2>Rules</h2> <p class="text-primary"> By participating in this game, you certify that you have have read and agree to the <a href="{{ game.rules.url }}">game rules</a>, <a href="{{ STATIC_URL }}WAIVER.pdf">player waiver</a>, and <a href="{% url 'terms' %}">Terms and Conditions</a> before playing. </p> {% if game.status == 'in_progress' %} <p>The objective of zombies is to tag humans. The objective of humans is to survive. If you are a human and you are tagged by a zombie, give them the feed code on your bandanna. The zombie will then enter your feed code on the website. You will then turn into a zombie. If you shoot a zombie or hit them with a sock before they tag you, they will be stunned for five minutes. Academic buildings and most dorms are safe. Please scream into the abyss if you need tactical support or friendship. </p> {% endif %} </div> <div class="row"> <div class="col-lg-4"> <h2>Important Dates</h2> <dl class="dl-horizontal"> <dt>Registration starts</dt> <dd>{{ game.registration_date }}</dd> <dt>Game starts</dt> <dd>{{ game.start_date }}</dd> <dt>Game ends</dt> <dd>{{ game.end_date }}</dd> </dl> </div> <div class="col-lg-4"> <h2>Game Status</h2> {% if game.status == "registration" %} <h4 class="text-success">Open for registration</h4> {% if not player %} <p><a class="btn btn-primary" href="{% url 'game|register' pk=game.pk %}">Register</a></p> {% else %} <p class="text-success">You have already registered for this game. Sit tight!</p> {% endif %} {% elif game.status == "in_progress" %} <h4 class="text-success">LIVE</h4> <p><b>{{ game.end_date|timeuntil }}</b> until it all ends.</p> {% if user.is_authenticated and not player %} <p class="text-info">Interested in joining this game? Please contact a moderator.</p> {% elif player and not player.active %} <p class="text-danger">You registered for this game but have not been activated. Please contact a moderator for assistance.</p> {% endif %} {% elif game.status == "finished" %} <h4 class="text-info">Finished</h4> {% elif game.status == "future" %} <h4 class="text-warning">Future game</h4> {% endif %} </div> <div class="col-lg-4"> <h2>Players</h2> <dl class="dl-horizontal"> {% if game.status == "registration" or game.status == "future" %} <dt>Registered players</dt> <dd>{{ game.get_registered_players.count }}</dd> <dt>Registered squads</dt> <dd>{{ game.squads.count|add:game.new_squads.count }}</dd> {% else %} <dt>Total players</dt> <dd>{{ game.get_active_players.count }}</dd> <dt>Humans</dt> <dd>{{ game.get_humans.count }} ({{ humans_percent }}%)</dd> <dt>Zombies</dt> <dd>{{ game.get_zombies.count }} ({{ zombies_percent }}%)</dd> <dt>Squads</dt> <dd>{{ game.squads.count|add:game.new_squads.count }}</dd> {% endif %} </dl> </div> </div> {% if player %} <hr> <div class="row"> {% if player.active and game.status == 'in_progress' %} <div class="center" style="font-size: 16pt;"> {% if player.user.profile.subscribe_chatter_listhost %} <p><a href="mailto:chatter@lists.bgundead.info" target="_blank">Chatter listhost (all players): chatter@lists.bgundead.info</a></p> {% if player.human %} <p><a href="mailto:{{ game.humans_listhost_address }}" target="_blank">Humans-only chatter listhost (anonymized): {{ game.humans_listhost_address }}</a></p> {% else %} <p><a href="mailto:{{ game.zombies_listhost_address }}" target="_blank">Zombies-only chatter listhost (anonymized): {{ game.zombies_listhost_address }}</a></p> {% endif %} {% endif %} </div> <a class="btn btn-block bigger btn-{% if player.human %}success{% else %}danger{% endif %}" href="{% url 'game|chat' pk=game.pk %}" target="_blank"> {% if player.human %}Get on the radio{% else %}ENTER FEEDING AREA{% endif %} </a> {% endif %} <div class="col-lg-4"> <h2>I am a...</h2> {% if player.human %} <h3 class="bold text-success">HUMAN</h3> {% else %} <h3 class="bold text-danger">ZOMBIE</h3> {% if player.kill_object %} <p><a href="{{ player.kill_object.get_absolute_url }}">Killed by {{ player.kill_object.killer.user.get_full_name }} on {{ player.kill_object.date }}</a></p> {% endif %} {% endif %} {% if player.active %} {% if game.status == 'registration' or game.status == 'in_progress' %} <h3>My feed code</h3> <h4 id="bite_code" style="font-weight: bold;">{{ player.bite_code }}</h4> {% if player.human %} <input type="button" value="Hide feed code" class="btn btn-danger" onclick="$('#bite_code').hide()"> <input type="button" value="Show feed code" class="btn btn-success" onclick="$('#bite_code').show()"> <p class="text-danger">Keep your feed code safe from prying eyes! Don't share it with other humans, don't send it over the public chatter listhost, etc. (unless you have a death wish, of course.)</p> {% endif %} {% endif %} {% if not player.human %} {% if player.unannotated_kills.count %} <div class="well"> <p class="text-warning">You still need to add geotags and/or notes to the kills below:</p> <ul class="list-unstyled"> {% for kill in player.unannotated_kills %} <li><a href="{% url 'kill|annotate' pk=kill.id %}">{{ kill.victim.user.get_full_name}} ({{ kill.victim.bite_code }})</a></li> {% endfor %} </ul> </div> {% endif %} {% if player.lead_zombie %} <h2>Lead Zombie Message Service</h2> <form class="form-inline" role="form" action="{% url 'game|lz_text' pk=game.pk %}" method="post"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" name="message" placeholder="Your message to the horde" required> </div> <div class="form-group"> <button class="btn btn-danger" type="submit">Send</button> </div> </form> {% endif %}<br> <a class="btn btn-danger btn-block" href="{% url 'game|bite' pk=game.pk %}">Log a kill...</a> <p class="bold text-info"> ***Kills are timestamped at the time of submission, so enter your feed codes while they're still fresh!*** </p> {% endif %} <h2>Enter Mission Code</h2> <form class="form-inline" role="form" action="{% url 'game|code' pk=game.pk %}" method="post"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" name="code" placeholder="two words" required> </div> <div class="form-group"> <button class="btn btn-{% if player.human %}success{% else %}danger{% endif %}" type="submit">Submit</button> </div> </form> <p class="text-default">* Standard text messaging rates apply.</p> {% endif %} </div> <div class="col-lg-4"> <h2>My Info</h2> <dl class="dl-horizontal"> {% if squad_count %} <dt>Your squad</dt> <dd>{% if player.squad %}<a href="{{ player.squad.get_absolute_url }}">{{ player.squad.name }}</a>{% else %}(None){% endif %}</dd> {% endif %} {% if player.new_squad %} <dt>Your squad</dt> <dd>{{ player.new_squad.name }} {% endif %} <dt>Your dorm</dt> <dd>{{ player.dorm }}</dd> <!-- <dt>Your major</dt> <dd>{{ player.major }}</dd> --> {% if game.status == 'registration' %} <dt>Blaster rental requested</dt> <dd>{{ player.gun_requested|yesno:"Yes,No,N/A" }}</dd> {% else %} <dt>Renting Blaster</dt> <dd>{{ player.renting_gun|yesno:"Yes,No,N/A" }}</dd> {% if game.status == 'finished' and player.renting_gun %} <dt>Gun returned</dt> <dd>{{ player.gun_returned|yesno:"Yes,No,N/A" }}</dd> {% endif %} {% endif %} </dl> {% if game.status == "finished" and player.renting_gun and not player.gun_returned %} <p class="text-danger">Please return your blaster as soon as possible!</p> {% endif %} {% if player.active and game.status == 'in_progress' %} {% if player.user.profile.phone_number %} {% if player.user.profile.subscribe_death_notifications %} <p class="text-success">We'll send death notifications to you via text message. You can disable these in your <a href="{% url 'users|account' %}">profile</a>. </p> {% else %} <p class="text-danger"> You have elected not to received death notifications. </p> {% endif %} {% else %} <p class="text-warning">We don't have a phone number on file for you! Add it to your <a href="{% url 'users|account' %}">profile</a> and check the appropriate box if you want to receive death notifications via text message.* </p> <p class="text-default">* Standard text messaging rates apply.</p> {% endif %} {% endif %} </div> {% if game.status == 'registration' or game.status == 'in_progress' %} <div class="col-lg-4"> <h2>Squads are back!</h2> <a href="{% url 'game|choose_squad' pk=game.id %}">Register a new squad or join an existing one here.</a> </div> {% endif %} <div class="col-lg-4"> <h2>My Score</h2> {% if game.status == 'in_progress' or game.status == 'finished' %} {% if player.active %} <h4 class="point-marker"><span class="text-success">{{ player.human_points }} human points</span></h4> {% if not player.human %}<h4 class="point-marker"><span class="text-danger">{{ player.zombie_points }} zombie points</span></h4>{% endif %} <p>You are ranked <b>#{{ player_rank.0 }}</b> of {{ player_rank.1 }} {% if player.human %}humans{% else %}zombies{% endif %}. Visit your player page for more details and point breakdowns.</p> </p> <a class="btn btn-primary" href="{{ player.get_absolute_url }}">My Player Page</a> {% if player.squad %}<a class="btn btn-primary" href="{{ player.squad.get_absolute_url }}">My Squad Page</a>{% endif %} {% endif %} {% else %} <p>Scores are not available at this time.</p> {% endif %} </div> {% if game.picture %} <div class="col-lg-4"> <img src={{ game.picture.url }} alt="relic site"> </div> {% endif %} </div> {% endif %} {% if game.status == "in_progress" or game.status == "finished" %} <hr> <div class="center"> <h2>Average Kills per Hour</h2> <p class="lead text-danger">{{ kills_per_hour|floatformat:2 }}</p> {% if kills_in_last_hour and game.status == "in_progress" %} <h2>Kills in the Last Hour</h2> <p class="lead text-danger">{{ kills_in_last_hour|floatformat:0 }}</p> {% endif %} {% if game.status == 'in_progress' %}<p>All data below is updated in real time.</p>{% endif %} </div> <ul class="nav nav-tabs nav-justified"> <li class="active"><a href="#analytics" data-toggle="tab"><span class="glyphicon glyphicon-stats"></span> Analytics</a></li> <li><a href="#leaderboards-individual" data-toggle="tab"><span class="glyphicon glyphicon-list"></span> Individual Leaderboards</a></li> {% if game.squads.count %}<li><a href="#leaderboards-squad" data-toggle="tab"><span class="glyphicon glyphicon-th-list"></span> Squad Leaderboards</a></li>{% endif %} {% if game.new_squads.count %}<li><a href="#leaderboards-new-squad" data-toggle="tab"><span class="glyphicon glyphicon-th-list"></span> Squads</a></li>{% endif %} {% if game.flavor %}<li><a href="#flavor" data-toggle="tab"><span class="glyphicon glyphicon-pencil"></span> Flavor</a></li>{% endif %}{% if game.missions %}<li><a href="#missions" data-toggle="tab"><span class="glyphicon glyphicon-flag"></span> Missions</a></li>{% endif %} </ul> <div class="tab-content"> <div id="analytics" class="tab-pane active"> <div class="row"> <div class="col-md-6"> <h2>Survival by Dorm</h2> <table class="table table-bordered table-striped"> <thead> <tr> <th>Dorm</th> <th>Humans Alive</th> </tr> </thead> <tbody> {% for e in survival_by_dorm %} <tr> <td>{{ e.dorm }}</td> <td>{{ e.alive }}/{{ e.original }} ({{e.percent|floatformat}}%)</td> </tr> {% endfor %} </tbody> </table> <h2>Human Survival</h2> <div id="hphChart"></div> <button class="btn btn-success" id="hphcheckAll">Show All</button> <button class="btn btn-success" id="hphuncheckAll">Hide All</button> <h2>Most Courageous Dorms</h2> <p>Where courageousness = (total human points earned by dorm / # players in dorm) * 100</p> <table class="table table-bordered table-striped"> <thead> <tr> <th>Dorm</th> <th>Courageousness</th> </tr> </thead> <tbody> {% for e in most_courageous_dorms %} <tr> <td>{{ e.dorm }}</td> <td>{{ e.points|floatformat }}</td> </tr> {% endfor %} </tbody> </table> <h2>Humans by Major</h2> <div id="hMajorsChart"></div> </div> <div class="col-md-6"> <h2>Kills by Location <small>geotagged kills only</small></h2> <div id="killMap" style="height: 350px;"></div> <div class="center"> <div id="mapTimeFilters" class="btn-group" data-toggle="buttons"> <label class="btn btn-danger"> <input type="radio" name="mapTime" value="all" checked="checked"> all </label> {% if player and not player.human %} <label class="btn btn-danger"> <input type="radio" name="mapTime" value="my-kills"> my kills </label> {% endif %} <label class="btn btn-danger"> <input type="radio" name="mapTime" value="1"> last hour </label> <label class="btn btn-danger"> <input type="radio" name="mapTime" value="6"> last 6 hours </label> <label class="btn btn-danger"> <input type="radio" name="mapTime" value="12"> last 12 hours </label> <label class="btn btn-danger"> <input type="radio" name="mapTime" value="24"> last 24 hours </label> </div> </div> <h2>Most Infectious Dorms</h2> <p>Where infectivity = (total zombie points earned by dorm / # players in dorm) * 100</p> <table class="table table-bordered table-striped"> <thead> <tr> <th>Dorm</th> <th>Infectivity</th> </tr> </thead> <tbody> {% for e in most_infectious_dorms %} <tr> <td>{{ e.dorm }}</td> <td>{{ e.points|floatformat }}</td> </tr> {% endfor %} </tbody> </table> <h2>Kills by Time of Day</h2> <div id="todChart"></div> <h2>Zombies by Major</h2> <div id="zMajorsChart"></div> </div> </div> </div> <div id="leaderboards-individual" class="tab-pane"> <div class="row"> {% if game.status == "in_progress" %} <p class="center" style="margin-top: 1em;">The names of surviving humans have been obfuscated in the interest of national human security.</p> {% endif %} <div class="col-md-6"> <h2><span class="bold text-success">Top Humans</span></h2> <table class="table table-bordered table-striped"> <thead> <tr> <th>Name</th> <th>Human Points</th> </tr> </thead> <tbody> {% for p in top_humans %} <tr> <td> <a href="{{ p.url }}">{{ p.display_name }}</a> {% if not p.human %}<span class="text-danger">(killed in action)</span>{% endif %} </td> <td>{{ p.human_points }}</td> </tr> {% endfor %} </tbody> </table> </div> <div class="col-md-6"> <h2><span class="bold text-danger">Top Zombies</span></h2> <table class="table table-bordered table-striped"> <thead> <tr> <th>Name</th> <th>Kills</th> <th>Zombie Points</th> </tr> </thead> <tbody> {% for p in top_zombies %} <tr> <td><a href="{{ p.url }}">{{ p.display_name }}</a></td> <td>{{ p.kills }}</td> <td>{{ p.zombie_points }}</td> </tr> {% endfor %} </tbody> </table> </div> </div> <h3 class="center"><a href="{% url 'game|leaderboard' pk=game.id %}">View full leaderboards</a></h3> </div> {% if game.squads.count %} <div id="leaderboards-squad" class="tab-pane"> <p class="center" style="margin-top: 1em;">Where squad points = (total human or zombie points / # of squad members) * 10<br> Squads must have &ge;2 casualties to qualify as a zombie squad. </p> <div class="row"> <div class="col-md-6"> <h2><span class="bold text-success">Human Squads</span></h2> <table class="table table-bordered table-striped"> <thead> <tr> <th>Name</th> <th># Alive</th> <th>Human Squad Points</th> </tr> </thead> <tbody> {% for s in top_human_squads %} <tr> <td><a href="{{ s.url }}">{{ s.name }}</a>{% if s.num_humans == 0 %} <span class="text-danger">(killed in action)</span>{% endif %}</td> <td style="width:80px">{{ s.num_humans }} of {{ s.size }}</td> <td>{{ s.human_points }}</td> </tr> {% endfor %} </tbody> </table> </div> <div class="col-md-6"> <h2><span class="bold text-danger">Zombie Squads</span></h2> {% if top_zombie_squads %} <table class="table table-bordered table-striped"> <thead> <tr> <th>Name</th> <th style="width:80px"># Undead</th> <th>Zombie Squad Points</th> </tr> </thead> <tbody> {% for s in top_zombie_squads %} <tr> <td><a href="{{ s.url }}">{{ s.name }}</a></td> <td>{{ s.num_zombies }} of {{ s.size }}</td> <td>{{ s.zombie_points }}</td> </tr> {% endfor %} </tbody> </table> {% else %} <p>There are no zombie squads...yet.</p> {% endif %} </div> </div> {% endif %} {% if game.new_squads.count %} <div id="leaderboards-new-squad" class="tab-pane"> <div class="row"> <div class="col-md-6"> <h2><span class="bold">Squads</span></h2> <table class="table table-bordered table-striped"> <thead> <tr> <th>Name</th> <th># Alive</th> <th># Players</th> </tr> </thead> <tbody> {% for s in game.new_squads.all %} {% if s.get_active_players %} <tr> <td><a href="{{ s.get_absolute_url }}">{{ s.name }}</a>{% if s.num_humans == 0 %} <span class="text-danger">(killed in action)</span>{% endif %}</td> <td style="width:80px">{{ s.num_humans }} of {{ s.size }}</td> <td>{{ s.size }}</td> </tr> {% endif %} {% endfor %} </tbody> </table> </div> </div> </div> {% endif %} {% if game.flavor %} <div id="flavor" class="tab-pane"> <div class="row"> <p class="left" style="margin-top: 1em;">{{ game.flavor|urlize|linebreaksbr }}</p> </div> </div> {% endif %} {% if game.missions %} <div id="missions" class="tab-pane"> {% for mission in missions %} <h2>{{ mission.name }} {% if mission.zombies_win %} <small><span class="text-danger"> Zombies Win</span></small> {% else %} <small><span class="text-success"> Humans Win</span></small> {% endif %}</h2> <p>{{ mission.description }} <a href="{% url 'mission|show' pk=mission.id %}">More info</a></p> {% endfor %} </div> {% endif %} </div> {% endif %} {% if game.status == 'finished' %} <hr> <h2>Global Kill Tree</h2> <ul> {% cache 3600 kt game.id %} {% recursetree game.get_kills %} <li> <a href="{{ node.victim.get_absolute_url }}"><b>{{ node.victim.display_name }}</b></a> - killed on <a href="{{ node.get_absolute_url }}">{{ node.date }}</a> {% if node.geotagged %}<span class="glyphicon glyphicon-globe"></span>{% endif %} {% if node.notes %}<span class="glyphicon glyphicon-pencil"></span>{% endif %} {% if not node.is_leaf_node %} <ul> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} {% endcache %} </ul> {% endif %} {% endblock %} {% block script %} {% if game.status == "in_progress" or game.status == "finished" %} {% include 'includes/google-maps.html' %} {% include 'includes/moment.html' %} {% include 'includes/highcharts.html' %} <script> {% if player %} var PLAYER_NAME = '{{ player.display_name }}'; {% else %} var PLAYER_NAME = null; {% endif %} $(document).ready(function(){ $('#bite_code').hide(); }); </script> {% compress js %} <script type="text/coffeescript"> swPoint = new google.maps.LatLng(GAME_SW_BOUND[0], GAME_SW_BOUND[1]) nePoint = new google.maps.LatLng(GAME_NE_BOUND[0], GAME_NE_BOUND[1]) bounds = new google.maps.LatLngBounds(swPoint, nePoint) mapOptions = { center: new google.maps.LatLng(GAME_CENTER[0], GAME_CENTER[1]), zoom: 15 } map = new google.maps.Map($('#killMap').get(0), mapOptions) lvc = map.getCenter() google.maps.event.addListener map, 'center_changed', (e) -> nc = map.getCenter() if bounds.contains(nc) lvc = nc else map.panTo(lvc) $.get("data/kills/") .done (data) -> infoWin = new google.maps.InfoWindow() markers = [] for k in data k.date = new Date(k.date) if k.location != null marker = new google.maps.Marker { map: map, icon: '{{ STATIC_URL }}img/skull.png', position: new google.maps.LatLng(k.location[0], k.location[1]) } killDT = moment(k.date).format('M/D/YY h:mm:ss A') content = $( "<ul style='color:black'> <li><b>Killer:</b> #{k.killer}</li> <li><b>Victim:</b> #{k.victim}</li> <li><b>Date:</b> #{killDT}</li> <li><a href=\"/kill/#{ k.id }/\" target='_blank' style='font-weight: bold; color:black;'>Details</a></li> </ul>" ) content.css('width', '300px') markers.push([marker, k]) google.maps.event.addListener marker, 'click', ((marker, content) -> return -> infoWin.setContent(content) infoWin.open(map, marker) )(marker, content.get(0)) $('#mapTimeFilters label').click (e) -> inp = $(this).children('input') if inp.val() == 'all' markers.forEach (o) -> o[0].setVisible true return else if inp.val() == 'my-kills' markers.forEach (o) -> if o[1].killer == PLAYER_NAME o[0].setVisible true else o[0].setVisible false else hours = parseInt inp.val() now = Date.now() markers.forEach (o) -> m = o[0] k = o[1] if now - k.date.getTime() <= hours * 3600 * 1000 m.setVisible true else m.setVisible false whiteStyle = {color: "white"} $.get("data/humans-per-hour/") .done (data) -> $("#hphChart").highcharts { chart: { type: 'line', backgroundColor: '#333', zoomType: 'xy', }, colors: ['#7cb5ec', '#4369FF', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#FF85e8', '#8d4653', '#91e8e1', '#2397fe', '#FF115a', '#102bBF'], credits: { enabled: false }, legend: { backgroundColor: 'white'; }, title: { text: null, }, plotOptions: { series: { marker: { enabled: false } } }, xAxis: { tickInterval: null, title: { text: 'Hours into game', style: whiteStyle }, labels: { style: whiteStyle } }, yAxis: { title: { text: '# humans', style: whiteStyle, }, tickInterval: null, labels: { style: whiteStyle } }, series: data } $('#hphcheckAll').click (e) -> chart = $('#hphChart').highcharts() box.show() for box in chart.series $('#hphuncheckAll').click (e) -> chart = $('#hphChart').highcharts() box.hide() for box in chart.series $.get("data/kills-by-tod/") .done (data) -> $("#todChart").highcharts { chart: { type: 'column', backgroundColor: '#333', }, credits: { enabled: false }, title: { text: null, }, legend: { enabled: false }, xAxis: { tickInterval: 1, title: { text: 'Time of Day', style: whiteStyle }, labels: { style: whiteStyle }, categories: [ '12a', '1a', '2a', '3a', '4a', '5a', '6a', '7a', '8a', '9a', '10a', '11a', '12p', '1p', '2p', '3p', '4p', '5p', '6p', '7p', '8p', '9p', '10p', '11p' ] }, yAxis: { title: { text: 'cumulative # of kills', style: whiteStyle }, tickInterval: 1, labels: { style: whiteStyle } }, series: [ { data: data, color: '#800000', name: 'Kills' } ] } $.get("data/humans-by-major/") .done (data) -> $("#hMajorsChart").highcharts { chart: { type: 'scatter', backgroundColor: '#333', zoomType: 'xy', }, credits: { enabled: false }, colors: ['#7cb5ec', '#4369FF', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#FF85e8', '#8d4653', '#91e8e1', '#2397fe', '#FF115a', '#102bBF'], title: { text: null, }, legend: { enabled: false }, xAxis: { title: { text: 'Average lifespan (hours)', style: whiteStyle }, labels: { style: whiteStyle } }, yAxis: { title: { text: 'Average human points/player', style: whiteStyle }, labels: { style: whiteStyle } }, series: data, tooltip: { formatter: -> return "#{this.series.name}<br><b>Players:</b> #{this.point.name}<br><b>Hours:</b> #{this.point.x}<br><b>Points:</b> #{this.point.y}" } } $.get("data/zombies-by-major/") .done (data) -> $("#zMajorsChart").highcharts { chart: { type: 'scatter', backgroundColor: '#333', zoomType: 'xy', }, credits: { enabled: false }, colors: ['#7cb5ec', '#4369FF', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#FF85e8', '#8d4653', '#91e8e1', '#2397fe', '#FF115a', '#102bBF'], title: { text: null, }, legend: { enabled: false }, xAxis: { title: { text: 'Average time spent as zombie (hours)', style: whiteStyle }, labels: { style: whiteStyle } }, yAxis: { title: { text: 'Average zombie points/player', style: whiteStyle }, labels: { style: whiteStyle } }, series: data, tooltip: { formatter: -> return "#{this.series.name}<br><b>Players:</b> #{this.point.name}<br><b>Hours:</b> #{this.point.x}<br><b>Points:</b> #{this.point.y}" } } </script> {% endcompress %} {% endif %} {% endblock %}
{ "content_hash": "b9a0a779e94cf2ce6cc7eb23b1913c25", "timestamp": "", "source": "github", "line_count": 834, "max_line_length": 275, "avg_line_length": 31.109112709832136, "alnum_prop": 0.5778762767392561, "repo_name": "Pitkid/bgundead", "id": "6b5eaa6485499a7ce58c6b1f7b7381e595592c44", "size": "25945", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bgundead/templates/game/show.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "16554" }, { "name": "HTML", "bytes": "537341" }, { "name": "JavaScript", "bytes": "1" }, { "name": "Python", "bytes": "118547" } ], "symlink_target": "" }
package bookshop2.supplier.incoming.queryBooks; import javax.ejb.SessionContext; import javax.xml.rpc.handler.MessageContext; import org.aries.Assert; import org.aries.tx.message.MessageUtil; import org.aries.validate.util.Check; import bookshop2.OrderRequestMessage; public class QueryBooksValidator { public QueryBooksValidator() { } public void validateCorrelationId(String correlationId) { Assert.notNull(correlationId, "CorrelationId null"); Assert.notEmpty(correlationId, "CorrelationId empty"); } public void validateTransactionId(String transactionId) { Assert.notNull(transactionId, "TransactionId null"); Assert.notEmpty(transactionId, "TransactionId empty"); } public void validate(MessageContext messageContext) { String correlationId = (String) messageContext.getProperty(MessageUtil.PROPERTY_CORRELATION_ID); String transactionId = (String) messageContext.getProperty(MessageUtil.PROPERTY_TRANSACTION_ID); validateCorrelationId(correlationId); validateTransactionId(transactionId); } public void validate(SessionContext sessionContext) { validate(sessionContext.getMessageContext()); } public void validate(OrderRequestMessage orderRequestMessage) { Check.isValid("orderRequestMessage", orderRequestMessage); } }
{ "content_hash": "c9a22c376d683efb793f653cea8efa50", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 98, "avg_line_length": 28.42222222222222, "alnum_prop": 0.8029710711493354, "repo_name": "tfisher1226/ARIES", "id": "9260e964df02f76e86e9aef11fba8f2dd69e389c", "size": "1279", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bookshop2/bookshop2-supplier/bookshop2-supplier-service/src/main/java/bookshop2/supplier/incoming/queryBooks/QueryBooksValidator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1606" }, { "name": "CSS", "bytes": "660469" }, { "name": "Common Lisp", "bytes": "91717" }, { "name": "Emacs Lisp", "bytes": "12403" }, { "name": "GAP", "bytes": "86009" }, { "name": "HTML", "bytes": "9381408" }, { "name": "Java", "bytes": "25671734" }, { "name": "JavaScript", "bytes": "304513" }, { "name": "Shell", "bytes": "51942" } ], "symlink_target": "" }
<div> <div class="row"> <div class="col-md-12"> <upload-directive target-url="'rest/v1/plugins'" drag-and-drop-message="'PLUGINS.DRAG_DROP_UPLOAD'" button-message="'PLUGINS.UPLOAD'" upload-success-callback='search()' /> </div> </div> <div class="row grp-margin"> <div class="col-md-3 pull-left "> <form role="search" ng-submit="search()"> <div class="input-group"> <input type="text" class="form-control" placeholder="..." ng-model="query"> <span class="input-group-btn"> <button type="submit" class="btn btn-default" data-loading-text="Loading..."> <i class="fa fa-search"></i> </button> </span> </div> </form> </div> </div> <div class="row grp-margin"> <div class="col-md-12"> <div class="table-resopnsive large-data-container" id="plugins-table"> <table class="table table-hover"> <thead> <tr> <!-- <th></th> --> <th>{{ 'COMMON.ID' | translate}}</th> <th>{{ 'COMMON.VERSION' | translate}}</th> <th>{{ 'COMMON.NAME' | translate}}</th> <th>{{ 'PLUGINS.BEANS' | translate}}</th> <th></th> <th></th> </tr> </thead> <tbody> <tr ng-repeat="plugin in data.data" id='plugin_{{plugin.id}}'> <!-- <td><i class="fa fa-circle fa-2x" ng-class="{'text-success': plugin.enabled,'text-danger': !plugin.enabled}" uib-tooltip="{{'COMMON.ENABLED_' + plugin.enabled | translate }}"></i></td> --> <td>{{plugin.descriptor.id}}</td> <td>{{plugin.descriptor.version}}</td> <td>{{plugin.descriptor.name}}</td> <td> <div ng-repeat="component in plugin.descriptor.componentDescriptors"> <i class="fa fa-cloud-upload" ng-if="component.type === 'IPaaSProvider'"></i> {{component.name}} </div> </td> <td style="vertical-align: middle"> <div class="pull-right"> <button ng-disabled="!plugin.enabled" id='plugin_{{plugin.id}}_configure' ng-click="openConfiguration(plugin.id)" ng-if="plugin.configurable" class="btn btn-default btn-xs" uib-tooltip="{{ 'PLUGINS.CONFIGURE' | translate}}" tooltip-append-to-body="true"> <i class="fa fa-cog"></i> </button> <div id="srv-state" class="switch vertical-center" ng-click="toggleState(plugin)"> <div class="pending-switch-slider" ng-class="{'disabled' : !plugin.enabled , 'enabled': plugin.enabled, 'pending': plugin.pending, 'loaded': !plugin.pending}"></div> </div> <!-- Remove a plugin --> <delete-confirm id="delete-plugin_{{plugin.id}}" func="remove(plugin.id)" position="left" bssize="btn-xs" fastyle="fa-trash-o"> </delete-confirm> </div> </td> <td style="vertical-align: middle; text-align: right"> <info content="plugin.descriptor.description" size="sm"></info> </td> </tr> </tbody> </table> <!-- pagination bar --> <pagination-directive pagination-info="searchService.pagination" /> </div> </div> </div> </div>
{ "content_hash": "4ed75b4f83113356c759858ea832ffb6", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 190, "avg_line_length": 43.924050632911396, "alnum_prop": 0.5103746397694524, "repo_name": "san-tak/alien4cloud", "id": "434149fa8e2ca5111dc33656c9e7f390ac2ab3e4", "size": "3470", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "alien4cloud-ui/src/main/webapp/views/plugins/plugin_list.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "526" }, { "name": "CSS", "bytes": "84072" }, { "name": "Gherkin", "bytes": "1085723" }, { "name": "Groovy", "bytes": "108257" }, { "name": "HTML", "bytes": "581403" }, { "name": "Java", "bytes": "5422624" }, { "name": "JavaScript", "bytes": "1119103" }, { "name": "Shell", "bytes": "41439" } ], "symlink_target": "" }
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ro_RO" version="2.0"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About GoobyCoin</source> <translation>Despre GoobyCoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;GoobyCoin&lt;/b&gt; version</source> <translation>&lt;b&gt;GoobyCoin&lt;/b&gt; versiunea</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Drepturi de autor</translation> </message> <message> <location line="+0"/> <source>The GoobyCoin developers</source> <translation>Dezvoltatorii GoobyCoin</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Listă de adrese</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Dublu-click pentru a edita adresa sau eticheta</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Creaţi o adresă nouă</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copiați adresa selectată în clipboard</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Adresă nouă</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your GoobyCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Acestea sunt adresele dumneavoastră GoobyCoin pentru a primi plăţi. Dacă doriţi, puteți da o adresa diferită fiecărui expeditor, pentru a putea ţine evidenţa plăţilor.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Copiază adresa</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Arata codul QR</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a GoobyCoin address</source> <translation>Semneaza mesajul pentru a dovedi ca detii aceasta adresa Bitocin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Semneaza mesajul</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Sterge adresele curent selectate din lista</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified GoobyCoin address</source> <translation>Verifica mesajul pentru a te asigura ca a fost insemnat cu o adresa goobycoin specifica</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation> Verifica mesajele</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Șterge</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your GoobyCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Copiază &amp;eticheta</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Editează</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+265"/> <source>Export Address Book Data</source> <translation>Exportă Lista de adrese</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Fisier csv: valori separate prin virgulă (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Eroare la exportare.</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Eroare la scrierea în fişerul %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Etichetă</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresă</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(fără etichetă)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Introduceți fraza de acces.</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Frază de acces nouă </translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Repetaţi noua frază de acces</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Introduceţi noua parolă a portofelului electronic.&lt;br/&gt;Vă rugăm să folosiţi &lt;b&gt;minimum 10 caractere aleatoare&lt;/b&gt;, sau &lt;b&gt;minimum 8 cuvinte&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Criptează portofelul</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Aceasta operație are nevoie de un portofel deblocat.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Deblochează portofelul</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Această operaţiune necesită parola pentru decriptarea portofelului electronic.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Decriptează portofelul.</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Schimbă fraza de acces</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Introduceţi vechea parola a portofelului eletronic şi apoi pe cea nouă.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Confirmă criptarea portofelului.</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR BITCOINS&lt;/b&gt;!</source> <translation>Atenție: Dacă pierdeţi parola portofelului electronic dupa criptare, &lt;b&gt;VEŢI PIERDE ÎNTREAGA SUMĂ DE BITCOIN ACUMULATĂ&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Sunteţi sigur că doriţi să criptaţi portofelul electronic?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Atentie! Caps Lock este pornit</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Portofel criptat </translation> </message> <message> <location line="-56"/> <source>GoobyCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your goobycoins from being stolen by malware infecting your computer.</source> <translation>GoobyCoin se va închide acum pentru a termina procesul de criptare. Amintiți-vă că criptarea portofelului dumneavoastră nu poate proteja în totalitate goobycoins dvs. de a fi furate de intentii rele.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Criptarea portofelului a eșuat.</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Criptarea portofelului a eșuat din cauza unei erori interne. Portofelul tău nu a fost criptat.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Fraza de acces introdusă nu se potrivește.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Deblocarea portofelului electronic a eşuat.</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Parola introdusă pentru decriptarea portofelului electronic a fost incorectă.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Decriptarea portofelului electronic a eşuat.</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Parola portofelului electronic a fost schimbată.</translation> </message> </context> <context> <name>GoobyCoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+254"/> <source>Sign &amp;message...</source> <translation>Semneaza &amp;mesaj...</translation> </message> <message> <location line="+246"/> <source>Synchronizing with network...</source> <translation>Se sincronizează cu reţeaua...</translation> </message> <message> <location line="-321"/> <source>&amp;Overview</source> <translation>&amp;Detalii</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Afişează detalii despre portofelul electronic</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Tranzacţii</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Istoricul tranzacţiilor</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Editaţi lista de adrese şi etichete.</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Lista de adrese pentru recepţionarea plăţilor</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>Ieșire</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Părăsiţi aplicaţia</translation> </message> <message> <location line="+7"/> <source>Show information about GoobyCoin</source> <translation>Informaţii despre GoobyCoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Despre &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Informaţii despre Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Setări...</translation> </message> <message> <location line="+9"/> <source>&amp;Encrypt Wallet...</source> <translation>Criptează portofelul electronic...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup portofelul electronic...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Schimbă parola...</translation> </message> <message> <location line="+251"/> <source>Importing blocks from disk...</source> <translation>Importare blocks de pe disk...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-319"/> <source>Send coins to a GoobyCoin address</source> <translation>&amp;Trimiteţi GoobyCoin către o anumită adresă</translation> </message> <message> <location line="+52"/> <source>Modify configuration options for GoobyCoin</source> <translation>Modifică setările pentru GoobyCoin</translation> </message> <message> <location line="+12"/> <source>Backup wallet to another location</source> <translation>Creaza copie de rezerva a portofelului intr-o locatie diferita</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>&amp;Schimbă parola folosită pentru criptarea portofelului electronic</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp; Fereastra debug</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Deschide consola de debug si diagnosticare</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>Verifica mesajul</translation> </message> <message> <location line="-183"/> <location line="+6"/> <location line="+508"/> <source>GoobyCoin</source> <translation>GoobyCoin</translation> </message> <message> <location line="-514"/> <location line="+6"/> <source>Wallet</source> <translation>Portofelul</translation> </message> <message> <location line="+107"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <location line="+2"/> <source>&amp;About GoobyCoin</source> <translation>&amp;Despre GoobyCoin</translation> </message> <message> <location line="+10"/> <location line="+2"/> <source>&amp;Show / Hide</source> <translation>Arata/Ascunde</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Criptează cheile private ale portofelului tău</translation> </message> <message> <location line="+7"/> <source>Sign messages with your GoobyCoin addresses to prove you own them</source> <translation>Semnează mesaje cu adresa ta GoobyCoin pentru a dovedi că îți aparțin</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified GoobyCoin addresses</source> <translation>Verifică mesaje pentru a te asigura că au fost semnate cu adresa GoobyCoin specificată</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Fişier</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Setări</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Ajutor</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Bara de ferestre de lucru</translation> </message> <message> <location line="-228"/> <location line="+288"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> <message> <location line="-5"/> <location line="+5"/> <source>GoobyCoin client</source> <translation>Client GoobyCoin</translation> </message> <message numerus="yes"> <location line="+121"/> <source>%n active connection(s) to GoobyCoin network</source> <translation><numerusform>%n active connections to GoobyCoin network</numerusform><numerusform>%n active connections to GoobyCoin network</numerusform><numerusform>%n active connections to GoobyCoin network</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>S-au procesat %1 blocuri din istoricul tranzacțiilor.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n oră</numerusform><numerusform>%n ore</numerusform><numerusform>%n ore</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n zi</numerusform><numerusform>%n zile</numerusform><numerusform>%n zile</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation>Eroare</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Avertizare</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informație</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Actualizat</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Se actualizează...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Confirma taxa tranzactiei</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Tranzacţie expediată</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Tranzacţie recepţionată</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1⏎ Suma: %2⏎ Tipul: %3⏎ Addresa: %4⏎</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid GoobyCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Portofelul electronic este &lt;b&gt;criptat&lt;/b&gt; iar in momentul de faţă este &lt;b&gt;deblocat&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Portofelul electronic este &lt;b&gt;criptat&lt;/b&gt; iar in momentul de faţă este &lt;b&gt;blocat&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+110"/> <source>A fatal error occurred. GoobyCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+105"/> <source>Network Alert</source> <translation>Alerta retea</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Editează adresa</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Eticheta</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Eticheta asociată cu această înregistrare în Lista de adrese</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adresă</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Adresa asociată cu această înregistrare în Lista de adrese. Aceasta poate fi modificată doar pentru expediere.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Noua adresă de primire</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Noua adresă de trimitere</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Editează adresa de primire</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Editează adresa de trimitere</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Adresa introdusă &quot;%1&quot; se află deja în Lista de adrese.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid GoobyCoin address.</source> <translation>Adresa introdusă &quot;%1&quot; nu este o adresă goobycoin valabilă.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Portofelul electronic nu a putut fi deblocat .</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>New key generation failed.</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <location filename="../intro.cpp" line="+61"/> <source>A new data directory will be created.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>name</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Directory already exists. Add %1 if you intend to create a new directory here.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Path already exists, and is not a directory.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Cannot create data directory here.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+517"/> <location line="+13"/> <source>GoobyCoin-Qt</source> <translation>GoobyCoin-Qt</translation> </message> <message> <location line="-13"/> <source>version</source> <translation>versiunea</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Uz:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>command-line setări</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>UI setări</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Seteaza limba, de exemplu: &quot;de_DE&quot; (initialt: system locale)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Incepe miniaturizare</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Afișează pe ecran splash la pornire (implicit: 1)</translation> </message> <message> <location line="+1"/> <source>Choose data directory on startup (default: 0)</source> <translation type="unfinished"/> </message> </context> <context> <name>Intro</name> <message> <location filename="../forms/intro.ui" line="+14"/> <source>Welcome</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Welcome to GoobyCoin-Qt.</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>As this is the first time the program is launched, you can choose where GoobyCoin-Qt will store its data.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>GoobyCoin-Qt will download and store a copy of the GoobyCoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Use the default data directory</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use a custom data directory:</source> <translation type="unfinished"/> </message> <message> <location filename="../intro.cpp" line="+100"/> <source>Error</source> <translation>Eroare</translation> </message> <message> <location line="+9"/> <source>GB of free space available</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>(of %1GB needed)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Setări</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Principal</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Plăteşte comision pentru tranzacţie &amp;f</translation> </message> <message> <location line="+31"/> <source>Automatically start GoobyCoin after logging in to the system.</source> <translation>Porneşte automat programul GoobyCoin la pornirea computerului.</translation> </message> <message> <location line="+3"/> <source>&amp;Start GoobyCoin on system login</source> <translation>&amp;S Porneşte GoobyCoin la pornirea sistemului</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Retea</translation> </message> <message> <location line="+6"/> <source>Automatically open the GoobyCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Deschide automat în router portul aferent clientului GoobyCoin. Funcţionează doar în cazul în care routerul e compatibil UPnP şi opţiunea e activată.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mapeaza portul folosind &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the GoobyCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Conectare la reţeaua GoobyCoin folosind un proxy SOCKS (de exemplu, când conexiunea se stabileşte prin reţeaua Tor)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Conectează prin proxy SOCKS:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Proxy &amp;IP:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Adresa de IP a proxy serverului (de exemplu: 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Port:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Portul pe care se concetează proxy serverul (de exemplu: 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;Versiune:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Versiunea SOCKS a proxiului (ex. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Fereastra</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Afişează doar un icon in tray la ascunderea ferestrei</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;M Ascunde în tray în loc de taskbar</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Ascunde fereastra în locul părăsirii programului în momentul închiderii ferestrei. Când acestă opţiune e activă, aplicaţia se va opri doar în momentul selectării comenzii Quit din menu.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>&amp;i Ascunde fereastra în locul închiderii programului</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Afişare</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Interfata &amp; limba userului</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting GoobyCoin.</source> <translation>Limba interfeței utilizatorului poate fi setat aici. Această setare va avea efect după repornirea GoobyCoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unitatea de măsură pentru afişarea sumelor:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Alege subdiviziunea folosită la afişarea interfeţei şi la trimiterea de goobycoin.</translation> </message> <message> <location line="+9"/> <source>Whether to show GoobyCoin addresses in the transaction list or not.</source> <translation>Vezi dacă adresele GoobyCoin sunt în lista de tranzacție sau nu</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Afişează adresele în lista de tranzacţii</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp; OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp; Renunta</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>Aplica</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+54"/> <source>default</source> <translation>Initial</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Vrei să continui?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Atentie!</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting GoobyCoin.</source> <translation>Această setare va avea efect după repornirea GoobyCoin.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Adresa goobycoin pe care a-ti specificat-o este invalida</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Form</translation> </message> <message> <location line="+50"/> <location line="+202"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the GoobyCoin network after a connection is established, but this process has not completed yet.</source> <translation>Informațiile afișate pot fi expirate. Portofelul tău se sincronizează automat cu rețeaua GoobyCoin după ce o conexiune este stabilita, dar acest proces nu a fost finalizat încă.</translation> </message> <message> <location line="-131"/> <source>Unconfirmed:</source> <translation>Neconfirmat:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Portofelul</translation> </message> <message> <location line="+49"/> <source>Confirmed:</source> <translation>Confirmat:</translation> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Immature:</source> <translation>Nematurizat:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>Balanta minata care nu s-a maturizat inca</translation> </message> <message> <location line="+13"/> <source>Total:</source> <translation>Total:</translation> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Ultimele tranzacţii&lt;/b&gt;</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>Nu este sincronizat</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+108"/> <source>Cannot start goobycoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QObject</name> <message> <location filename="../bitcoin.cpp" line="+92"/> <location filename="../intro.cpp" line="-32"/> <source>GoobyCoin</source> <translation>GoobyCoin</translation> </message> <message> <location line="+1"/> <source>Error: Specified data directory &quot;%1&quot; does not exist.</source> <translation type="unfinished"/> </message> <message> <location filename="../intro.cpp" line="+1"/> <source>Error: Specified data directory &quot;%1&quot; can not be created.</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Dialogul codului QR</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Cerere de plata</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Sumă:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Etichetă:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Mesaj:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>Salvare ca...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+64"/> <source>Error encoding URI into QR Code.</source> <translation>Eroare la incercarea codarii URl-ului in cod QR</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Suma introdusa nu este valida, verifica suma.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>Rezultat UDI prea lung, incearca sa reduci textul pentru eticheta/mesaj</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Salveaza codul QR</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>Imagini de tip PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Numaele clientului</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+345"/> <source>N/A</source> <translation>N/A</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Versiunea clientului</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp; Informatie</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Foloseste versiunea OpenSSL</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Data pornirii</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Retea</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Numarul de conexiuni</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Pe testnet</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Lant bloc</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Numarul curent de blockuri</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Estimarea totala a blocks</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Ultimul block a fost gasit la:</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Deschide</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Command-line setări</translation> </message> <message> <location line="+7"/> <source>Show the GoobyCoin-Qt help message to get a list with possible GoobyCoin command-line options.</source> <translation>Arata mesajul de ajutor GoobyCoin-QT pentru a obtine o lista cu posibilele optiuni ale comenzilor GoobyCoin</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp; Arata</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Consola</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Construit la data:</translation> </message> <message> <location line="-104"/> <source>GoobyCoin - Debug window</source> <translation>GoobyCoin-Fereastra pentru debug</translation> </message> <message> <location line="+25"/> <source>GoobyCoin Core</source> <translation>GoobyCoin Core</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Loguri debug</translation> </message> <message> <location line="+7"/> <source>Open the GoobyCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Deschide logurile debug din directorul curent. Aceasta poate dura cateva secunde pentru fisierele mai mari</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Curata consola</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the GoobyCoin RPC console.</source> <translation>Bun venit la consola goobycoin RPC</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Foloseste sagetile sus si jos pentru a naviga in istoric si &lt;b&gt;Ctrl-L&lt;/b&gt; pentru a curata.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Scrie &lt;b&gt;help&lt;/b&gt; pentru a vedea comenzile disponibile</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+128"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Trimite GoobyCoin</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Trimite simultan către mai mulţi destinatari</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;Adaugă destinatar</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Sterge toate spatiile de tranzactie</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Şterge &amp;tot</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Balanţă:</translation> </message> <message> <location line="+10"/> <source>123.456 ABC</source> <translation>123.456 ABC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Confirmă operaţiunea de trimitere</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;S Trimite</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-62"/> <location line="+2"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; la %2 (%3)</translation> </message> <message> <location line="+6"/> <source>Confirm send coins</source> <translation>Confirmaţi trimiterea de goobycoin</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Sunteţi sigur că doriţi să trimiteţi %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> şi </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Adresa destinatarului nu este validă, vă rugăm să o verificaţi.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Suma de plată trebuie să fie mai mare decât 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Suma depăşeşte soldul contului.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Total depăşeşte soldul contului in cazul plăţii comisionului de %1.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>S-a descoperit o adresă care figurează de două ori. Expedierea se poate realiza către fiecare adresă doar o singură dată pe operaţiune.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Eroare: Tranyacţia a fost respinsă. Acesta poate fi rezultatul cheltuirii prealabile a unei sume de goobycoin din portofelul electronic, ca în cazul folosirii unei copii a fisierului wallet.dat, în care s-au efectuat tranzacţii neînregistrate în fisierul curent.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Form</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Su&amp;mă :</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Plăteşte Că&amp;tre:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Adresa către care se va face plata (de exemplu: 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Adaugă o etichetă acestei adrese pentru a o trece în Lista de adrese</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>&amp;L Etichetă:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Alegeţi adresa din Listă</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Lipiţi adresa copiată in clipboard.</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Şterge destinatarul</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a GoobyCoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Introduceţi o adresă GoobyCoin (de exemplu: 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Semnatura- Semneaza/verifica un mesaj</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>Semneaza Mesajul</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Introduceţi o adresă GoobyCoin (de exemplu: 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Alegeţi adresa din Listă</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Lipiţi adresa copiată in clipboard.</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Introduce mesajul pe care vrei sa il semnezi, aici.</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Semnătură</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Copiaza semnatura curenta in clipboard-ul sistemului</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this GoobyCoin address</source> <translation>Semneaza mesajul pentru a dovedi ca detii acesta adresa GoobyCoin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Semnează &amp;Message</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Reseteaza toate spatiile mesajelor semnate.</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Şterge &amp;tot</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>Verifica mesajul</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Introduceţi o adresă GoobyCoin (de exemplu: 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified GoobyCoin address</source> <translation>Verifica mesajul pentru a fi sigur ca a fost semnat cu adresa GoobyCoin specifica</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Verifică &amp;Message</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Reseteaza toate spatiile mesajelor semnate.</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a GoobyCoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source> <translation>Introduceţi o adresă GoobyCoin (de exemplu: 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Click &quot;Semneaza msajul&quot; pentru a genera semnatura</translation> </message> <message> <location line="+3"/> <source>Enter GoobyCoin signature</source> <translation>Introduce semnatura bitocin</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Adresa introdusa nu este valida</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Te rugam verifica adresa si introduce-o din nou</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>Adresa introdusa nu se refera la o cheie.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Blocarea portofelului a fost intrerupta</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>Cheia privata pentru adresa introdusa nu este valida.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Semnarea mesajului a esuat</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Mesaj Semnat!</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Aceasta semnatura nu a putut fi decodata</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Verifica semnatura si incearca din nou</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Semnatura nu seamana!</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Verificarea mesajului a esuat</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Mesaj verificat</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The GoobyCoin developers</source> <translation>Dezvoltatorii GoobyCoin</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testnet]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Deschis până la %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/neconfirmat</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 confirmări</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Stare</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Sursa</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Generat</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>De la</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Către</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>Adresa posedata</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>etichetă</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Credit</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>nu este acceptat</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debit</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Comisionul tranzacţiei</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Suma netă</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Mesaj</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Comentarii</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID-ul tranzactiei</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 10 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Monedele goobycoin generate se pot cheltui dupa parcurgerea a 10 de blocuri. După ce a fost generat, s-a propagat în reţea, urmând să fie adăugat lanţului de blocuri. Dacă nu poate fi inclus in lanţ, starea sa va deveni &quot;neacceptat&quot; si nu va putea fi folosit la tranzacţii. Acest fenomen se întâmplă atunci cand un alt nod a generat un bloc la o diferenţa de câteva secunde.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informatii pentru debug</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Tranzacţie</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Intrari</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Sumă</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>Adevarat!</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>Fals!</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, nu s-a propagat încă</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>necunoscut</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Detaliile tranzacţiei</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Afişează detalii despre tranzacţie</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipul</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresa</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Cantitate</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Deschis până la %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Neconectat (%1 confirmări)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Neconfirmat (%1 din %2 confirmări)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Confirmat (%1 confirmări)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Blocul nu a fost recepţionat de niciun alt nod şi e probabil că nu va fi acceptat.</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Generat, dar neacceptat</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Recepţionat cu</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Primit de la:</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Trimis către</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Plată către un cont propriu</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Produs</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/a)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Starea tranzacţiei. Treceţi cu mouse-ul peste acest câmp pentru afişarea numărului de confirmări.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Data şi ora la care a fost recepţionată tranzacţia.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipul tranzacţiei.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Adresa de destinaţie a tranzacţiei.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Suma extrasă sau adăugată la sold.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Toate</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Astăzi</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Săptămâna aceasta</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Luna aceasta</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Luna trecută</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Anul acesta</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Între...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Recepţionat cu...</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Trimis către</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Către propriul cont</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Produs</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Altele</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Introduceţi adresa sau eticheta pentru căutare</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Cantitatea produsă</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copiază adresa</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copiază eticheta</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copiază sumă</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Editează eticheta</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Arata detaliile tranzactiei</translation> </message> <message> <location line="+143"/> <source>Export Transaction Data</source> <translation>Exportă tranzacţiile</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Fişier text cu valori separate prin virgulă (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confirmat</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipul</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Etichetă</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adresă</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Sumă</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Eroare în timpul exportului</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Fisierul %1 nu a putut fi accesat pentru scriere.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Interval:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>către</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Trimite GoobyCoin</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+46"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+197"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Date portofel (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Copia de rezerva a esuat</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>A apărut o eroare la încercarea de a salva datele din portofel intr-o noua locație.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+98"/> <source>GoobyCoin version</source> <translation>versiunea GoobyCoin</translation> </message> <message> <location line="+104"/> <source>Usage:</source> <translation>Uz:</translation> </message> <message> <location line="-30"/> <source>Send command to -server or goobycoind</source> <translation>Trimite comanda la -server sau goobycoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Listă de comenzi</translation> </message> <message> <location line="-13"/> <source>Get help for a command</source> <translation>Ajutor pentru o comandă</translation> </message> <message> <location line="+25"/> <source>Options:</source> <translation>Setări:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: goobycoin.conf)</source> <translation>Specifica-ți configurația fisierului (in mod normal: goobycoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: goobycoind.pid)</source> <translation>Specifica fisierul pid (normal: goobycoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Specifica datele directorului</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Seteaza marimea cache a bazei de date in MB (initial: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 10221 or testnet: 20221)</source> <translation>Lista a conectiunile in &lt;port&gt; (initial: 10221 sau testnet: 20221)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Se menține la cele mai multe conexiuni &lt;n&gt; cu colegii (implicit: 125)</translation> </message> <message> <location line="-49"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Conecteaza-te la nod pentru a optine adresa peer, si deconecteaza-te</translation> </message> <message> <location line="+84"/> <source>Specify your own public address</source> <translation>Specifica adresa ta publica</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Prag pentru deconectarea colegii funcționează corect (implicit: 100)</translation> </message> <message> <location line="-136"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Numărul de secunde pentru a păstra colegii funcționează corect la reconectare (implicit: 86400)</translation> </message> <message> <location line="-33"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 10222 or testnet: 20222)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Se accepta command line si comenzi JSON-RPC</translation> </message> <message> <location line="+77"/> <source>Run in the background as a daemon and accept commands</source> <translation>Ruleaza în background ca un demon și accepta comenzi.</translation> </message> <message> <location line="+38"/> <source>Use the test network</source> <translation>Utilizeaza test de retea</translation> </message> <message> <location line="-114"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Accepta conexiuni de la straini (initial: 1 if no -proxy or -connect) </translation> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=goobycoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;GoobyCoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. GoobyCoin is probably already running.</source> <translation>Nu se poate obține o blocare a directorului de date %s. GoobyCoin probabil rulează deja.</translation> </message> <message> <location line="+3"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Seteaza marimea maxima a tranzactie mare/mica in bytes (initial:27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong GoobyCoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Optiuni creare block</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Conecteaza-te doar la nod(urile) specifice</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Descopera propria ta adresa IP (intial: 1)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Eroare: Spațiu pe disc redus!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Eroare: Portofel blocat, nu se poate crea o tranzacție!</translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Incorrect or no genesis block found. Wrong datadir for network?</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet %s resides outside data directory %s</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>You need to rebuild the database using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+78"/> <source>Information</source> <translation>Informație</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Copie de ieșire de depanare cu timestamp</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the GoobyCoin Wiki for SSL setup instructions)</source> <translation>Optiuni SSl (vezi GoobyCoin wiki pentru intructiunile de instalare)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Selecteaza versiunea socks-ului pe care vrei sa il folosesti (4-5, initial: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Trimite urmări / debug info la consola loc de debug.log fișier</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Trimite urmări / debug info la depanatorul</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Foloseste UPnP pentru a vedea porturile (initial: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Foloseste UPnP pentru a vedea porturile (initial: 1 cand listezi)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Username pentru conectiunile JSON-RPC</translation> </message> <message> <location line="+5"/> <source>Warning</source> <translation>Avertizare</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corupt, recuperare eșuată</translation> </message> <message> <location line="-52"/> <source>Password for JSON-RPC connections</source> <translation>Parola pentru conectiunile JSON-RPC</translation> </message> <message> <location line="-68"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Permiteti conectiunile JSON-RPC de la o adresa IP specifica.</translation> </message> <message> <location line="+77"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Trimite comenzi la nod, ruland pe ip-ul (initial: 127.0.0.1)</translation> </message> <message> <location line="-121"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Executa comanda cand cel mai bun block se schimba (%s in cmd se inlocuieste cu block hash)</translation> </message> <message> <location line="+149"/> <source>Upgrade wallet to latest format</source> <translation>Actualizeaza portofelul la ultimul format</translation> </message> <message> <location line="-22"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Setarea marimii cheii bezinului la &lt;n&gt;(initial 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Rescanare lanțul de bloc pentru tranzacțiile portofel lipsă</translation> </message> <message> <location line="+36"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Foloseste Open SSL(https) pentru coneciunile JSON-RPC</translation> </message> <message> <location line="-27"/> <source>Server certificate file (default: server.cert)</source> <translation>Certificatul serverulu (initial: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Cheia privata a serverului ( initial: server.pem)</translation> </message> <message> <location line="-156"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Accepta cifruri (initial: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+171"/> <source>This help message</source> <translation>Acest mesaj de ajutor.</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Nu se poate lega %s cu acest calculator (retunare eroare legatura %d, %s) </translation> </message> <message> <location line="-93"/> <source>Connect through socks proxy</source> <translation>Conectează prin proxy SOCKS</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Permite DNS-ului sa se uite dupa -addnode, -seednode si -connect</translation> </message> <message> <location line="+56"/> <source>Loading addresses...</source> <translation>Încarc adrese...</translation> </message> <message> <location line="-36"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Eroare incarcand wallet.dat: Portofel corupt</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of GoobyCoin</source> <translation>Eroare incarcare wallet.dat: Portofelul are nevoie de o versiune GoobyCoin mai noua</translation> </message> <message> <location line="+96"/> <source>Wallet needed to be rewritten: restart GoobyCoin to complete</source> <translation>Portofelul trebuie rescris: restarteaza aplicatia goobycoin pentru a face asta.</translation> </message> <message> <location line="-98"/> <source>Error loading wallet.dat</source> <translation>Eroare incarcand wallet.dat</translation> </message> <message> <location line="+29"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Adresa proxy invalida: &apos;%s&apos;</translation> </message> <message> <location line="+57"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Retea specificata necunoscuta -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Necunoscut -socks proxy version requested: %i</translation> </message> <message> <location line="-98"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Nu se poate rezolca -bind address: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Nu se poate rezolva -externalip address: &apos;%s&apos;</translation> </message> <message> <location line="+45"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Suma invalida pentru -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Suma invalida</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Fonduri insuficiente</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Încarc indice bloc...</translation> </message> <message> <location line="-58"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Add a node to connect to and attempt to keep the connection open details suggestions history </translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. GoobyCoin is probably already running.</source> <translation>Imposibilitatea de a lega la% s pe acest computer. GoobyCoin este, probabil, deja în execuție.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Taxa pe kb pentru a adauga tranzactii trimise</translation> </message> <message> <location line="+20"/> <source>Loading wallet...</source> <translation>Încarc portofel...</translation> </message> <message> <location line="-53"/> <source>Cannot downgrade wallet</source> <translation>Nu se poate face downgrade la portofel</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Nu se poate scrie adresa initiala</translation> </message> <message> <location line="+65"/> <source>Rescanning...</source> <translation>Rescanez...</translation> </message> <message> <location line="-58"/> <source>Done loading</source> <translation>Încărcare terminată</translation> </message> <message> <location line="+84"/> <source>To use the %s option</source> <translation>Pentru a folosii optiunea %s</translation> </message> <message> <location line="-76"/> <source>Error</source> <translation>Eroare</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Trebuie sa setezi rpzpassword=&lt;password&gt; in fisierul de configuratie:⏎ %s⏎ Daca fisierul nu exista, creazal cu permisiunea fisierului proprietar-doar-citire </translation> </message> </context> </TS>
{ "content_hash": "48edcf69a7b921cbe689230c735ff0da", "timestamp": "", "source": "github", "line_count": 3059, "max_line_length": 422, "avg_line_length": 37.598888525661984, "alnum_prop": 0.6204147285136721, "repo_name": "GoobyCoin/GoobyCoin", "id": "19aae65dfaffc080d2910ffa8b80314c11a387ee", "size": "115463", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/qt/locale/bitcoin_ro_RO.ts", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "30534" }, { "name": "C++", "bytes": "2556851" }, { "name": "CSS", "bytes": "1127" }, { "name": "Groff", "bytes": "18289" }, { "name": "HTML", "bytes": "50615" }, { "name": "Makefile", "bytes": "5190" }, { "name": "NSIS", "bytes": "5908" }, { "name": "Objective-C", "bytes": "858" }, { "name": "Objective-C++", "bytes": "5711" }, { "name": "Python", "bytes": "69711" }, { "name": "QMake", "bytes": "14317" }, { "name": "Shell", "bytes": "17896" } ], "symlink_target": "" }
(function ($) { var _ajax = $.ajax, mockHandlers = [], CALLBACK_REGEX = /=\?(&|$)/, jsc = (new Date()).getTime(); // Parse the given XML string. function parseXML(xml) { if (window['DOMParser'] == undefined && window.ActiveXObject) { DOMParser = function () { }; DOMParser.prototype.parseFromString = function (xmlString) { var doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(xmlString); return doc; }; } try { var xmlDoc = ( new DOMParser() ).parseFromString(xml, 'text/xml'); if ($.isXMLDoc(xmlDoc)) { var err = $('parsererror', xmlDoc); if (err.length == 1) { throw('Error: ' + $(xmlDoc).text() ); } } else { throw('Unable to parse XML'); } } catch (e) { var msg = ( e.name == undefined ? e : e.name + ': ' + e.message ); $(document).trigger('xmlParseError', [ msg ]); return undefined; } return xmlDoc; } // Trigger a jQuery event function trigger(s, type, args) { (s.context ? jQuery(s.context) : jQuery.event).trigger(type, args); } // Check if the data field on the mock handler and the request match. This // can be used to restrict a mock handler to being used only when a certain // set of data is passed to it. function isMockDataEqual(mock, live) { var identical = false; // Test for situations where the data is a querystring (not an object) if (typeof live === 'string') { // Querystring may be a regex return $.isFunction(mock.test) ? mock.test(live) : mock == live; } $.each(mock, function (k, v) { if (live[k] === undefined) { identical = false; return identical; } else { identical = true; if (typeof live[k] == 'object') { return isMockDataEqual(mock[k], live[k]); } else { if ($.isFunction(mock[k].test)) { identical = mock[k].test(live[k]); } else { identical = ( mock[k] == live[k] ); } return identical; } } }); return identical; } // Check the given handler should mock the given request function getMockForRequest(handler, requestSettings) { // If the mock was registered with a function, let the function decide if we // want to mock this request if ($.isFunction(handler)) { return handler(requestSettings); } // Inspect the URL of the request and check if the mock handler's url // matches the url for this ajax request if ($.isFunction(handler.url.test)) { // The user provided a regex for the url, test it if (!handler.url.test(requestSettings.url)) { return null; } } else { // Look for a simple wildcard '*' or a direct URL match var star = handler.url.indexOf('*'); if (handler.url !== requestSettings.url && star === -1 || !new RegExp(handler.url.replace(/[-[\]{}()+?.,\\^$|#\s]/g, "\\$&").replace('*', '.+')).test(requestSettings.url)) { return null; } } // Inspect the data submitted in the request (either POST body or GET query string) if (handler.data && requestSettings.data) { if (!isMockDataEqual(handler.data, requestSettings.data)) { // They're not identical, do not mock this request return null; } } // Inspect the request type if (handler && handler.type && handler.type.toLowerCase() != requestSettings.type.toLowerCase()) { // The request type doesn't match (GET vs. POST) return null; } return handler; } // If logging is enabled, log the mock to the console function logMock(mockHandler, requestSettings) { var c = $.extend({}, $.mockjaxSettings, mockHandler); if (c.log && $.isFunction(c.log)) { c.log('MOCK ' + requestSettings.type.toUpperCase() + ': ' + requestSettings.url, $.extend({}, requestSettings)); } } // Process the xhr objects send operation function _xhrSend(mockHandler, requestSettings, origSettings) { // This is a substitute for < 1.4 which lacks $.proxy var process = (function (that) { return function () { return (function () { // The request has returned this.status = mockHandler.status; this.statusText = mockHandler.statusText; this.readyState = 4; // We have an executable function, call it to give // the mock handler a chance to update it's data if ($.isFunction(mockHandler.response)) { mockHandler.response(origSettings); } // Copy over our mock to our xhr object before passing control back to // jQuery's onreadystatechange callback if (requestSettings.dataType == 'json' && ( typeof mockHandler.responseText == 'object' )) { this.responseText = JSON.stringify(mockHandler.responseText); } else if (requestSettings.dataType == 'xml') { if (typeof mockHandler.responseXML == 'string') { this.responseXML = parseXML(mockHandler.responseXML); } else { this.responseXML = mockHandler.responseXML; } } else { this.responseText = mockHandler.responseText; } if (typeof mockHandler.status == 'number' || typeof mockHandler.status == 'string') { this.status = mockHandler.status; } if (typeof mockHandler.statusText === "string") { this.statusText = mockHandler.statusText; } // jQuery < 1.4 doesn't have onreadystate change for xhr if ($.isFunction(this.onreadystatechange)) { if (mockHandler.isTimeout) { this.status = -1; } this.onreadystatechange(mockHandler.isTimeout ? 'timeout' : undefined); } else if (mockHandler.isTimeout) { // Fix for 1.3.2 timeout to keep success from firing. this.status = -1; } }).apply(that); }; })(this); if (mockHandler.proxy) { // We're proxying this request and loading in an external file instead _ajax({ global: false, url: mockHandler.proxy, type: mockHandler.proxyType, data: mockHandler.data, dataType: requestSettings.dataType === "script" ? "text/plain" : requestSettings.dataType, complete: function (xhr, txt) { mockHandler.responseXML = xhr.responseXML; mockHandler.responseText = xhr.responseText; mockHandler.status = xhr.status; mockHandler.statusText = xhr.statusText; this.responseTimer = setTimeout(process, mockHandler.responseTime || 0); } }); } else { // type == 'POST' || 'GET' || 'DELETE' if (requestSettings.async === false) { // TODO: Blocking delay process(); } else { this.responseTimer = setTimeout(process, mockHandler.responseTime || 50); } } } // Construct a mocked XHR Object function xhr(mockHandler, requestSettings, origSettings, origHandler) { // Extend with our default mockjax settings mockHandler = $.extend({}, $.mockjaxSettings, mockHandler); if (typeof mockHandler.headers === 'undefined') { mockHandler.headers = {}; } if (mockHandler.contentType) { mockHandler.headers['content-type'] = mockHandler.contentType; } return { status: mockHandler.status, statusText: mockHandler.statusText, readyState: 1, open: function () { }, send: function () { origHandler.fired = true; _xhrSend.call(this, mockHandler, requestSettings, origSettings); }, abort: function () { clearTimeout(this.responseTimer); }, setRequestHeader: function (header, value) { mockHandler.headers[header] = value; }, getResponseHeader: function (header) { // 'Last-modified', 'Etag', 'content-type' are all checked by jQuery if (mockHandler.headers && mockHandler.headers[header]) { // Return arbitrary headers return mockHandler.headers[header]; } else if (header.toLowerCase() == 'last-modified') { return mockHandler.lastModified || (new Date()).toString(); } else if (header.toLowerCase() == 'etag') { return mockHandler.etag || ''; } else if (header.toLowerCase() == 'content-type') { return mockHandler.contentType || 'text/plain'; } }, getAllResponseHeaders: function () { var headers = ''; $.each(mockHandler.headers, function (k, v) { headers += k + ': ' + v + "\n"; }); return headers; } }; } // Process a JSONP mock request. function processJsonpMock(requestSettings, mockHandler, origSettings) { // Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here // because there isn't an easy hook for the cross domain script tag of jsonp processJsonpUrl(requestSettings); requestSettings.dataType = "json"; if (requestSettings.data && CALLBACK_REGEX.test(requestSettings.data) || CALLBACK_REGEX.test(requestSettings.url)) { createJsonpCallback(requestSettings, mockHandler); // We need to make sure // that a JSONP style response is executed properly var rurl = /^(\w+:)?\/\/([^\/?#]+)/, parts = rurl.exec(requestSettings.url), remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host); requestSettings.dataType = "script"; if (requestSettings.type.toUpperCase() === "GET" && remote) { var newMockReturn = processJsonpRequest(requestSettings, mockHandler, origSettings); // Check if we are supposed to return a Deferred back to the mock call, or just // signal success if (newMockReturn) { return newMockReturn; } else { return true; } } } return null; } // Append the required callback parameter to the end of the request URL, for a JSONP request function processJsonpUrl(requestSettings) { if (requestSettings.type.toUpperCase() === "GET") { if (!CALLBACK_REGEX.test(requestSettings.url)) { requestSettings.url += (/\?/.test(requestSettings.url) ? "&" : "?") + (requestSettings.jsonp || "callback") + "=?"; } } else if (!requestSettings.data || !CALLBACK_REGEX.test(requestSettings.data)) { requestSettings.data = (requestSettings.data ? requestSettings.data + "&" : "") + (requestSettings.jsonp || "callback") + "=?"; } } // Process a JSONP request by evaluating the mocked response text function processJsonpRequest(requestSettings, mockHandler, origSettings) { // Synthesize the mock request for adding a script tag var callbackContext = origSettings && origSettings.context || requestSettings, newMock = null; // If the response handler on the moock is a function, call it if (mockHandler.response && $.isFunction(mockHandler.response)) { mockHandler.response(origSettings); } else { // Evaluate the responseText javascript in a global context if (typeof mockHandler.responseText === 'object') { $.globalEval('(' + JSON.stringify(mockHandler.responseText) + ')'); } else { $.globalEval('(' + mockHandler.responseText + ')'); } } // Successful response jsonpSuccess(requestSettings, mockHandler); jsonpComplete(requestSettings, mockHandler); // If we are running under jQuery 1.5+, return a deferred object if (jQuery.Deferred) { newMock = new jQuery.Deferred(); if (typeof mockHandler.responseText == "object") { newMock.resolve(mockHandler.responseText); } else { newMock.resolve(jQuery.parseJSON(mockHandler.responseText)); } } return newMock; } // Create the required JSONP callback function for the request function createJsonpCallback(requestSettings, mockHandler) { jsonp = requestSettings.jsonpCallback || ("jsonp" + jsc++); // Replace the =? sequence both in the query string and the data if (requestSettings.data) { requestSettings.data = (requestSettings.data + "").replace(CALLBACK_REGEX, "=" + jsonp + "$1"); } requestSettings.url = requestSettings.url.replace(CALLBACK_REGEX, "=" + jsonp + "$1"); // Handle JSONP-style loading window[ jsonp ] = window[ jsonp ] || function (tmp) { data = tmp; jsonpSuccess(requestSettings, mockHandler); jsonpComplete(requestSettings, mockHandler); // Garbage collect window[ jsonp ] = undefined; try { delete window[ jsonp ]; } catch (e) { } if (head) { head.removeChild(script); } }; } // The JSONP request was successful function jsonpSuccess(requestSettings, mockHandler) { // If a local callback was specified, fire it and pass it the data if (requestSettings.success) { requestSettings.success.call(callbackContext, ( mockHandler.response ? mockHandler.response.toString() : mockHandler.responseText || ''), status, {}); } // Fire the global callback if (requestSettings.global) { trigger(requestSettings, "ajaxSuccess", [ {}, requestSettings ]); } } // The JSONP request was completed function jsonpComplete(requestSettings, mockHandler) { // Process result if (requestSettings.complete) { requestSettings.complete.call(callbackContext, {}, status); } // The request was completed if (requestSettings.global) { trigger("ajaxComplete", [ {}, requestSettings ]); } // Handle the global AJAX counter if (requestSettings.global && !--jQuery.active) { jQuery.event.trigger("ajaxStop"); } } // The core $.ajax replacement. function handleAjax(url, origSettings) { var mockRequest, requestSettings, mockHandler; // If url is an object, simulate pre-1.5 signature if (typeof url === "object") { origSettings = url; url = undefined; } else { // work around to support 1.5 signature origSettings.url = url; } // Extend the original settings for the request requestSettings = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings); // Iterate over our mock handlers (in registration order) until we find // one that is willing to intercept the request for (var k = 0; k < mockHandlers.length; k++) { if (!mockHandlers[k]) { continue; } mockHandler = getMockForRequest(mockHandlers[k], requestSettings); if (!mockHandler) { // No valid mock found for this request continue; } // Handle console logging logMock(mockHandler, requestSettings); if (requestSettings.dataType === "jsonp") { if ((mockRequest = processJsonpMock(requestSettings, mockHandler, origSettings))) { // This mock will handle the JSONP request return mockRequest; } } // Removed to fix #54 - keep the mocking data object intact //mockHandler.data = requestSettings.data; mockHandler.cache = requestSettings.cache; mockHandler.timeout = requestSettings.timeout; mockHandler.global = requestSettings.global; (function (mockHandler, requestSettings, origSettings, origHandler) { mockRequest = _ajax.call($, $.extend(true, {}, origSettings, { // Mock the XHR object xhr: function () { return xhr(mockHandler, requestSettings, origSettings, origHandler) } })); })(mockHandler, requestSettings, origSettings, mockHandlers[k]); return mockRequest; } // We don't have a mock request, trigger a normal request return _ajax.apply($, [origSettings]); } // Public $.extend({ ajax: handleAjax }); $.mockjaxSettings = { //url: null, //type: 'GET', log: function (msg) { window['console'] && window.console.log && window.console.log(msg); }, status: 200, statusText: "OK", responseTime: 500, isTimeout: false, contentType: 'text/plain', response: '', responseText: '', responseXML: '', proxy: '', proxyType: 'GET', lastModified: null, etag: '', headers: { etag: 'IJF@H#@923uf8023hFO@I#H#', 'content-type': 'text/plain' } }; $.mockjax = function (settings) { var i = mockHandlers.length; mockHandlers[i] = settings; return i; }; $.mockjaxClear = function (i) { if (arguments.length == 1) { mockHandlers[i] = null; } else { mockHandlers = []; } }; $.mockjax.handler = function (i) { if (arguments.length == 1) { return mockHandlers[i]; } }; })(jQuery);
{ "content_hash": "b1699de72422deab27c538bdbf6bc966", "timestamp": "", "source": "github", "line_count": 519, "max_line_length": 185, "avg_line_length": 37.872832369942195, "alnum_prop": 0.5232498982498982, "repo_name": "ShahidulHasan/pms", "id": "66291dacc7938da06a4123e07df9d3f24c162535", "size": "20004", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/Resources/assets/plugins/jquery.mockjax.js", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "390443" }, { "name": "JavaScript", "bytes": "2714454" }, { "name": "PHP", "bytes": "366124" }, { "name": "Perl", "bytes": "2687" } ], "symlink_target": "" }
/** * Created: Nov 20, 2013 4:48:56 PM */ package com.livescribe.web.registration.mock; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import com.livescribe.framework.orm.vectordb.Warranty; import com.livescribe.web.registration.TestConstants; /** * <p></p> * * @author <a href="mailto:kmurdoff@livescribe.com">Kevin F. Murdoff</a> * @version 1.0 */ public class MockWarrantyFactory implements TestConstants { private Logger logger = Logger.getLogger(this.getClass().getName()); /** * <p>Default class constructor.</p> * */ public MockWarrantyFactory() { } /** * <p>Returns a <code>Warranty</code> object corresponding to the data * loaded from the <code>warranty.xml</code> file.</p> * * @return a single <code>Warranty</code> object. */ public static Warranty create() { Warranty warranty = new Warranty(); warranty.setAppId("RegistrationClientTest"); warranty.setDisplayId(XML_LOADED_WARRANTY_DISPLAY_ID_1); warranty.setEdition(0); warranty.setEmail(XML_LOADED_WARRANTY_EMAIL_1); warranty.setFirstName(XML_LOADED_WARRANTY_FIRST_NAME_1); warranty.setLastName(XML_LOADED_WARRANTY_LAST_NAME_1); warranty.setLocale(XML_LOADED_WARRANTY_LOCALE_1); warranty.setPenName(XML_LOADED_WARRANTY_PEN_NAME_1); warranty.setPenSerial(XML_LOADED_WARRANTY_PEN_SERIAL_1); return warranty; } /** * <p>Returns a <code>List</code> of <code>count</code> number of * <code>Warranty</code> objects</p> * * @param count The number of <code>Warranty</code> objects to create. * * @return a list of warranty objects. */ public static List<Warranty> create(int count) { ArrayList<Warranty> list = new ArrayList<Warranty>(); for (int i = 0; i < count; i++) { MockWarranty mockWarranty = new MockWarranty(); list.add(mockWarranty); } return list; } }
{ "content_hash": "1118066e1b679d2b8313709cd73ccb6a", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 72, "avg_line_length": 26.65714285714286, "alnum_prop": 0.7020364415862809, "repo_name": "jackstraw66/web", "id": "1cfa6ac8cbfc0bd8b4450f66d9724937649f8dfb", "size": "1866", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "livescribe/lsregistration/src/test/java/com/livescribe/web/registration/mock/MockWarrantyFactory.java", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "CSS", "bytes": "12519" }, { "name": "FreeMarker", "bytes": "586195" }, { "name": "HTML", "bytes": "8445" }, { "name": "Java", "bytes": "3072798" }, { "name": "JavaScript", "bytes": "6722" }, { "name": "Shell", "bytes": "16332" } ], "symlink_target": "" }
package mvc.apps.horo; import java.io.ByteArrayInputStream; import org.apache.http.Header; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.hardware.Camera; import android.hardware.Camera.PictureCallback; import android.hardware.Camera.ShutterCallback; import android.os.Bundle; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; @SuppressWarnings("deprecation") public class VideoServer extends Activity implements SurfaceHolder.Callback{ TextView testView; Camera camera; SurfaceView surfaceView; SurfaceHolder surfaceHolder; PictureCallback rawCallback; ShutterCallback shutterCallback; PictureCallback jpegCallback; private final String tag = "VideoServer"; private boolean cameraWorking = false; Button start, stop, capture; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); start = (Button)findViewById(R.id.btn_start); //stop = (Button)findViewById(R.id.btn_stop); capture = (Button) findViewById(R.id.capture); start.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View arg0) { start_camera(); } }); /* stop.setOnClickListener(new Button.OnClickListener(){ public void onClick(View arg0) { stop_camera(); } }); */ capture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { captureImage(); } }); surfaceView = (SurfaceView) findViewById(R.id.camera_preview); surfaceHolder = surfaceView.getHolder(); surfaceHolder.addCallback(this); surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); rawCallback = new PictureCallback() { @Override public void onPictureTaken(byte[] data, android.hardware.Camera camera) { Log.d("Log", "onPictureTaken - raw"); } }; /** Handles data for jpeg picture */ shutterCallback = new ShutterCallback() { public void onShutter() { Log.i("Log", "onShutter'd"); } }; jpegCallback = new PictureCallback() { @Override public void onPictureTaken(byte[] data, android.hardware.Camera camera) { upload(data); stop_camera(); } }; } private void captureImage() { if(cameraWorking){ camera.takePicture(shutterCallback, rawCallback, jpegCallback); } } private void start_camera(){ if(!cameraWorking){ SurfaceView cameraPreview = (SurfaceView) findViewById(R.id.camera_preview); cameraPreview.setBackgroundResource(0); try{ camera = Camera.open(); }catch(RuntimeException e){ Log.e(tag, "init_camera: " + e); return; } Camera.Parameters param; camera.setDisplayOrientation(90); param = camera.getParameters(); param.setPreviewFrameRate(20); param.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); param.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_AUTO); param.setSceneMode(Camera.Parameters.SCENE_MODE_AUTO); param.setPictureSize(866, 650); camera.setParameters(param); try { camera.setPreviewDisplay(surfaceHolder); camera.startPreview(); cameraWorking = true; } catch (Exception e) { Log.e(tag, "init_camera: " + e); return; } } } private void stop_camera(){ if(cameraWorking){ camera.stopPreview(); camera.release(); cameraWorking = false; } } private void upload(byte[] data){ String domain = "http://192.168.16.2"; String url = domain + "/horo.php"; AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.put("uploaded_file", new ByteArrayInputStream(data), "img.jpg"); client.setTimeout(10000000); client.post(url, params, new AsyncHttpResponseHandler() { Context context = getApplicationContext(); @Override public void onStart() { // called before request is started Toast.makeText(context, "Uploading...", Toast.LENGTH_LONG).show(); Log.i("UPLOAD", "START"); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) { Toast.makeText(context, "Success!", Toast.LENGTH_LONG).show(); Log.i("UPLOAD", "SUCCESS"); Intent intent = new Intent(getApplication(), BrowserActivity.class); String message = new String(response); Log.i("RESPONSE", message); intent.putExtra("DOMAIN", "http://192.168.16.2"); intent.putExtra("FILENAME", message); startActivity(intent); Log.i("UPLOAD", "Start New Activity"); } @Override public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) { Log.e("UPLOAD", "FAILURE"); Toast.makeText(context, "Failed, Please try again.", Toast.LENGTH_LONG).show(); } @Override public void onRetry(int retryNo) { Log.i("UPLOAD", "RETRY"); Toast.makeText(context, "Retrying...", Toast.LENGTH_LONG).show(); } }); } @Override public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void surfaceCreated(SurfaceHolder arg0) { // TODO Auto-generated method stub } @Override public void surfaceDestroyed(SurfaceHolder arg0) { // TODO Auto-generated method stub } }
{ "content_hash": "e053220908ff888b9e859a3f82bcdf9a", "timestamp": "", "source": "github", "line_count": 207, "max_line_length": 101, "avg_line_length": 31.019323671497585, "alnum_prop": 0.6220214919794425, "repo_name": "withlovee/Horo", "id": "3a27864980f80f25080a4b191750f8c5f41c19fa", "size": "6421", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/mvc/apps/horo/VideoServer.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "7184" } ], "symlink_target": "" }
from setuptools import setup, find_packages version = '0.3.2' setup( name="alerta-hipchat", version=version, description='Alerta plugin for HipChat', url='https://github.com/alerta/alerta-contrib', license='Apache License 2.0', author='Nick Satterly', author_email='nick.satterly@theguardian.com', packages=find_packages(), py_modules=['alerta_hipchat'], install_requires=[ 'requests', 'jinja2' ], include_package_data=True, zip_safe=True, entry_points={ 'alerta.plugins': [ 'hipchat = alerta_hipchat:SendRoomNotification' ] } )
{ "content_hash": "8cec5c44f8179a7556e85ba900c61452", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 59, "avg_line_length": 24.423076923076923, "alnum_prop": 0.6251968503937008, "repo_name": "msupino/alerta-contrib", "id": "f9e9d60eb8439038d907792be290d469e1e5d537", "size": "636", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plugins/hipchat/setup.py", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "7739" }, { "name": "Python", "bytes": "115391" } ], "symlink_target": "" }
<?xml version='1.0' encoding='UTF-8'?> <flow-definition> <actions/> <description>Demonstrates Demo App Pipeline Using Docker Images and Plugin</description> <keepDependencies>false</keepDependencies> <properties> <hudson.model.ParametersDefinitionProperty> <parameterDefinitions> <hudson.model.StringParameterDefinition> <name>APP_VERSION</name> <description>This parameter is to simulate the event of an update being pushed to the source repository, triggering Jenkins to run this build script. Source updates are represented by different versions of the demo app (Docker files): Docker_v1.0, Docker_v2.0, Docker_v2.1, Docker_v3.0</description> <defaultValue>1.0</defaultValue> </hudson.model.StringParameterDefinition> </parameterDefinitions> </hudson.model.ParametersDefinitionProperty> </properties> <definition class="org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition"> <scm class="hudson.plugins.git.GitSCM"> <configVersion>2</configVersion> <userRemoteConfigs> <hudson.plugins.git.UserRemoteConfig> <url>/tmp/repo</url> </hudson.plugins.git.UserRemoteConfig> </userRemoteConfigs> <branches> <hudson.plugins.git.BranchSpec> <name>*/master</name> </hudson.plugins.git.BranchSpec> </branches> <doGenerateSubmoduleConfigurations>false</doGenerateSubmoduleConfigurations> <submoduleCfg class="list"/> <extensions/> </scm> <scriptPath>Jenkinsfile</scriptPath> </definition> </flow-definition>
{ "content_hash": "47efac43866615c4f6b5df5d0d84d6c0", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 159, "avg_line_length": 41.921052631578945, "alnum_prop": 0.7062146892655368, "repo_name": "warmi01/docker-workflow-plugin", "id": "984f5cd1db95b65cacc6b068609334654f5ac565", "size": "1593", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "demo/JENKINS_HOME/jobs/demoapp-workflow/config.xml", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "266" }, { "name": "Groff", "bytes": "537" }, { "name": "Groovy", "bytes": "30658" }, { "name": "HTML", "bytes": "3948" }, { "name": "Java", "bytes": "238063" }, { "name": "JavaScript", "bytes": "4424" }, { "name": "Makefile", "bytes": "2991" }, { "name": "Shell", "bytes": "12455" } ], "symlink_target": "" }
var gulp = require("gulp"); var print = require("gulp-print"); var componentStream = require("./"); gulp.task('default', function() { return gulp.src('component.json') .pipe(componentStream.custom({ fields: ['scripts', 'json'] })) .pipe(print()); })
{ "content_hash": "39145291c7beb1f7d60d15a50f0e6b60", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 64, "avg_line_length": 28.333333333333332, "alnum_prop": 0.6549019607843137, "repo_name": "frankwallis/gulp-component-resolver", "id": "3c0aa971f9c22ae93236689865f69c4dc6ad3750", "size": "255", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gulpfile.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2721" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.4.2_05) on Thu Sep 30 22:15:55 GMT+01:00 2004 --> <TITLE> Uses of Package org.springframework.ejb.access (Spring Framework) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Package org.springframework.ejb.access (Spring Framework)"; } </SCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Package<br>org.springframework.ejb.access</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> Packages that use <A HREF="../../../../org/springframework/ejb/access/package-summary.html">org.springframework.ejb.access</A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.springframework.ejb.access"><B>org.springframework.ejb.access</B></A></TD> <TD>This package contains classes that allow easy access to EJBs. &nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.springframework.ejb.access"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> Classes in <A HREF="../../../../org/springframework/ejb/access/package-summary.html">org.springframework.ejb.access</A> used by <A HREF="../../../../org/springframework/ejb/access/package-summary.html">org.springframework.ejb.access</A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../org/springframework/ejb/access/class-use/AbstractRemoteSlsbInvokerInterceptor.html#org.springframework.ejb.access"><B>AbstractRemoteSlsbInvokerInterceptor</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Superclass for interceptors proxying remote Stateless Session Beans. </TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../org/springframework/ejb/access/class-use/AbstractSlsbInvokerInterceptor.html#org.springframework.ejb.access"><B>AbstractSlsbInvokerInterceptor</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Superclass for AOP interceptors invoking local or remote Stateless Session Beans. </TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../org/springframework/ejb/access/class-use/LocalSlsbInvokerInterceptor.html#org.springframework.ejb.access"><B>LocalSlsbInvokerInterceptor</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Invoker for a local Stateless Session Bean. </TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../org/springframework/ejb/access/class-use/SimpleRemoteSlsbInvokerInterceptor.html#org.springframework.ejb.access"><B>SimpleRemoteSlsbInvokerInterceptor</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Basic invoker for a remote Stateless Session Bean. </TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=3 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright (C) 2003-2004 The Spring Framework Project.</i> </BODY> </HTML>
{ "content_hash": "3a6ce4fced5fff007ad6686ec322bf71", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 248, "avg_line_length": 42.19251336898396, "alnum_prop": 0.6466413181242079, "repo_name": "dachengxi/spring1.1.1_source", "id": "7d4180fb48838fd46f3d74c59711c0f0ceffb7c4", "size": "7890", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/api/org/springframework/ejb/access/package-use.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "163" }, { "name": "FreeMarker", "bytes": "8024" }, { "name": "HTML", "bytes": "34675" }, { "name": "Java", "bytes": "5934573" } ], "symlink_target": "" }
from django.shortcuts import render_to_response from django.template import RequestContext from django.core.paginator import Paginator from django.conf import settings from quizzardous.utils import get_current_month_datetime from .models import ScoreCounter def rankings(request, template_name='rankings/rankings.html'): rankings = ScoreCounter.objects.filter( when=get_current_month_datetime()).select_related( 'user').order_by('-score') paginator = Paginator(rankings, settings.USERS_PER_PAGE) # TODO: Allow rankings other than the top "N" to be seen? context = dict(rankings=paginator.page(1)) return render_to_response(template_name, context, RequestContext(request))
{ "content_hash": "3798e437eaf0ce8a89aabf0845d6dcb2", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 62, "avg_line_length": 36.05, "alnum_prop": 0.753120665742025, "repo_name": "aviraldg/quizzardous", "id": "f152339846aea5a32742bc51f17f465fdc79cc08", "size": "721", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rankings/views.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "4681" }, { "name": "HTML", "bytes": "16996" }, { "name": "JavaScript", "bytes": "4656" }, { "name": "Python", "bytes": "28717" } ], "symlink_target": "" }
<!-- Licensed to Apereo under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Apereo licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at the following location: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <permission-set script="classpath://org/jasig/portal/io/import-permission_set_v3-1.crn"> <owner>SSP</owner> <principal-type>org.jasig.portal.groups.IEntityGroup</principal-type> <principal> <group>SSP_ADMINISTRATOR</group> </principal> <activity>PERSON_WATCHLIST_WRITE</activity> <target permission-type="GRANT"> <literal>ALL</literal> </target> </permission-set>
{ "content_hash": "7abe8ebc5c753dbc4076ec22c46105ed", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 88, "avg_line_length": 38.774193548387096, "alnum_prop": 0.7354409317803661, "repo_name": "Jasig/SSP-Platform", "id": "01d12e219a80d615023c698eb94176721d76693b", "size": "1202", "binary": false, "copies": "1", "ref": "refs/heads/ssp-master", "path": "uportal-war/src/main/data/ssp_entities/patches-SSP-2-6-0/SSP-770/permission_set/SSP_ADMINISTRATOR__PERSON_WATCHLIST_WRITE__SSP.permission-set.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "907" }, { "name": "CSS", "bytes": "858870" }, { "name": "Groovy", "bytes": "18089" }, { "name": "HTML", "bytes": "263115" }, { "name": "Java", "bytes": "7788834" }, { "name": "JavaScript", "bytes": "211384" }, { "name": "Perl", "bytes": "1769" }, { "name": "Shell", "bytes": "4936" }, { "name": "XSLT", "bytes": "301203" } ], "symlink_target": "" }
package com.twitter.chill import scala.collection.immutable.{ BitSet, HashSet, ListSet, NumericRange, Range, SortedSet, SortedMap, ListMap, HashMap, Queue } import scala.collection.mutable.{ WrappedArray, BitSet => MBitSet, Map => MMap, HashMap => MHashMap, Set => MSet, HashSet => MHashSet, ListBuffer, Queue => MQueue, Buffer } import scala.util.matching.Regex import com.twitter.chill.java.PackageRegistrar import _root_.java.io.Serializable import scala.collection.JavaConverters._ /** * This class has a no-arg constructor, suitable for use with reflection instantiation * It has no registered serializers, just the standard Kryo configured for Kryo. */ class EmptyScalaKryoInstantiator extends KryoInstantiator { override def newKryo = { val k = new KryoBase k.setRegistrationRequired(false) k.setInstantiatorStrategy(new org.objenesis.strategy.StdInstantiatorStrategy) k } } object ScalaKryoInstantiator extends Serializable { private val mutex = new AnyRef with Serializable // some serializable object @transient private var kpool: KryoPool = null /** * Return a KryoPool that uses the ScalaKryoInstantiator */ def defaultPool: KryoPool = mutex.synchronized { if (null == kpool) { kpool = KryoPool.withByteArrayOutputStream(guessThreads, new ScalaKryoInstantiator) } kpool } private def guessThreads: Int = { val cores = Runtime.getRuntime.availableProcessors val GUESS_THREADS_PER_CORE = 4 GUESS_THREADS_PER_CORE * cores } } /** Makes an empty instantiator then registers everything */ class ScalaKryoInstantiator extends EmptyScalaKryoInstantiator { override def newKryo = { val k = super.newKryo val reg = new AllScalaRegistrar reg(k) k } } class ScalaCollectionsRegistrar extends IKryoRegistrar { def apply(newK: Kryo) { // for binary compat this is here, but could be moved to RichKryo def useField[T](cls: Class[T]) { val fs = new com.esotericsoftware.kryo.serializers.FieldSerializer(newK, cls) fs.setIgnoreSyntheticFields(false) // scala generates a lot of these attributes newK.register(cls, fs) } // The wrappers are private classes: useField(List(1, 2, 3).asJava.getClass) useField(List(1, 2, 3).iterator.asJava.getClass) useField(Map(1 -> 2, 4 -> 3).asJava.getClass) useField(new _root_.java.util.ArrayList().asScala.getClass) useField(new _root_.java.util.HashMap().asScala.getClass) /* * Note that subclass-based use: addDefaultSerializers, else: register * You should go from MOST specific, to least to specific when using * default serializers. The FIRST one found is the one used */ newK // wrapper array is abstract .forSubclass[WrappedArray[Any]](new WrappedArraySerializer[Any]) .forSubclass[BitSet](new BitSetSerializer) .forSubclass[SortedSet[Any]](new SortedSetSerializer) .forClass[Some[Any]](new SomeSerializer[Any]) .forClass[Left[Any, Any]](new LeftSerializer[Any, Any]) .forClass[Right[Any, Any]](new RightSerializer[Any, Any]) .forTraversableSubclass(Queue.empty[Any]) // List is a sealed class, so there are only two subclasses: .forTraversableSubclass(List.empty[Any]) // Add ListBuffer subclass before Buffer to prevent the more general case taking precedence .forTraversableSubclass(ListBuffer.empty[Any], isImmutable = false) // add mutable Buffer before Vector, otherwise Vector is used .forTraversableSubclass(Buffer.empty[Any], isImmutable = false) // Vector is a final class .forTraversableClass(Vector.empty[Any]) .forTraversableSubclass(ListSet.empty[Any]) // specifically register small sets since Scala represents them differently .forConcreteTraversableClass(Set[Any]('a)) .forConcreteTraversableClass(Set[Any]('a, 'b)) .forConcreteTraversableClass(Set[Any]('a, 'b, 'c)) .forConcreteTraversableClass(Set[Any]('a, 'b, 'c, 'd)) // default set implementation .forConcreteTraversableClass(HashSet[Any]('a, 'b, 'c, 'd, 'e)) // specifically register small maps since Scala represents them differently .forConcreteTraversableClass(Map[Any, Any]('a -> 'a)) .forConcreteTraversableClass(Map[Any, Any]('a -> 'a, 'b -> 'b)) .forConcreteTraversableClass(Map[Any, Any]('a -> 'a, 'b -> 'b, 'c -> 'c)) .forConcreteTraversableClass(Map[Any, Any]('a -> 'a, 'b -> 'b, 'c -> 'c, 'd -> 'd)) // default map implementation .forConcreteTraversableClass(HashMap[Any, Any]('a -> 'a, 'b -> 'b, 'c -> 'c, 'd -> 'd, 'e -> 'e)) // The normal fields serializer works for ranges .registerClasses(Seq(classOf[Range.Inclusive], classOf[NumericRange.Inclusive[_]], classOf[NumericRange.Exclusive[_]])) // Add some maps .forSubclass[SortedMap[Any, Any]](new SortedMapSerializer) .forTraversableSubclass(ListMap.empty[Any, Any]) .forTraversableSubclass(HashMap.empty[Any, Any]) // The above ListMap/HashMap must appear before this: .forTraversableSubclass(Map.empty[Any, Any]) // here are the mutable ones: .forTraversableClass(MBitSet.empty, isImmutable = false) .forTraversableClass(MHashMap.empty[Any, Any], isImmutable = false) .forTraversableClass(MHashSet.empty[Any], isImmutable = false) .forTraversableSubclass(MQueue.empty[Any], isImmutable = false) .forTraversableSubclass(MMap.empty[Any, Any], isImmutable = false) .forTraversableSubclass(MSet.empty[Any], isImmutable = false) } } class JavaWrapperCollectionRegistrar extends IKryoRegistrar { def apply(newK: Kryo) { newK.register(JavaIterableWrapperSerializer.wrapperClass, new JavaIterableWrapperSerializer) } } /** Registers all the scala (and java) serializers we have */ class AllScalaRegistrar extends IKryoRegistrar { def apply(k: Kryo) { val col = new ScalaCollectionsRegistrar col(k) val jcol = new JavaWrapperCollectionRegistrar jcol(k) // Register all 22 tuple serializers and specialized serializers ScalaTupleSerialization.register(k) k.forClass[Symbol](new KSerializer[Symbol] { override def isImmutable = true def write(k: Kryo, out: Output, obj: Symbol) { out.writeString(obj.name) } def read(k: Kryo, in: Input, cls: Class[Symbol]) = Symbol(in.readString) }) .forSubclass[Regex](new RegexSerializer) .forClass[ClassManifest[Any]](new ClassManifestSerializer[Any]) .forSubclass[Manifest[Any]](new ManifestSerializer[Any]) .forSubclass[scala.Enumeration#Value](new EnumerationSerializer) // use the singleton serializer for boxed Unit val boxedUnit = scala.Unit.box(()) k.register(boxedUnit.getClass, new SingletonSerializer(boxedUnit)) PackageRegistrar.all()(k) } }
{ "content_hash": "7340688654db9cd3e240ed1c06ee01ef", "timestamp": "", "source": "github", "line_count": 185, "max_line_length": 103, "avg_line_length": 37.23783783783784, "alnum_prop": 0.7043112207867614, "repo_name": "steveloughran/chill", "id": "fe8e4295295a20d82d51393a54f37c2b61a9c050", "size": "7444", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "chill-scala/src/main/scala/com/twitter/chill/ScalaKryoInstantiator.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "180369" }, { "name": "Protocol Buffer", "bytes": "256" }, { "name": "Scala", "bytes": "200885" }, { "name": "Shell", "bytes": "16015" } ], "symlink_target": "" }
@interface EaseMarkdownTextView () @property (strong, nonatomic) MBProgressHUD *HUD; @property (strong, nonatomic) NSString *uploadingPhotoName; @end @implementation EaseMarkdownTextView - (id)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { self.inputAccessoryView = [RFKeyboardToolbar toolbarWithButtons:[self buttons]]; //监听-上传文件成功 [[[[NSNotificationCenter defaultCenter] rac_addObserverForName:kNotificationUploadCompled object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification *aNotification) { //{NSURLResponse: response, NSError: error, ProjectFile: data} NSDictionary* userInfo = [aNotification userInfo]; [self completionUploadWithResult:[userInfo objectForKey:@"data"] error:[userInfo objectForKey:@"error"]]; }]; } return self; } -(BOOL)canPerformAction:(SEL)action withSender:(id)sender{ NSString *actionName = NSStringFromSelector(action); if ([actionName isEqualToString:@"_addShortcut:"]) { return NO; }else{ return [super canPerformAction:action withSender:sender]; } } - (NSArray *)buttons { return @[ [self createButtonWithTitle:@"@" andEventHandler:^{ [self doAT]; }], [self createButtonWithTitle:@"#" andEventHandler:^{ [self insertText:@"#"]; }], [self createButtonWithTitle:@"*" andEventHandler:^{ [self insertText:@"*"]; }], [self createButtonWithTitle:@"`" andEventHandler:^{ [self insertText:@"`"]; }], [self createButtonWithTitle:@"-" andEventHandler:^{ [self insertText:@"-"]; }], [self createButtonWithTitle:@"照片" andEventHandler:^{ [self doPhoto]; }], [self createButtonWithTitle:@"标题" andEventHandler:^{ [self doTitle]; }], [self createButtonWithTitle:@"粗体" andEventHandler:^{ [self doBold]; }], [self createButtonWithTitle:@"斜体" andEventHandler:^{ [self doItalic]; }], [self createButtonWithTitle:@"代码" andEventHandler:^{ [self doCode]; }], [self createButtonWithTitle:@"引用" andEventHandler:^{ [self doQuote]; }], [self createButtonWithTitle:@"列表" andEventHandler:^{ [self doList]; }], [self createButtonWithTitle:@"链接" andEventHandler:^{ NSString *tipStr = @"在此输入链接地址"; NSRange selectionRange = self.selectedRange; selectionRange.location += 5; selectionRange.length = tipStr.length; [self insertText:[NSString stringWithFormat:@"[链接](%@)", tipStr]]; [self setSelectionRange:selectionRange]; }], [self createButtonWithTitle:@"图片链接" andEventHandler:^{ NSString *tipStr = @"在此输入图片地址"; NSRange selectionRange = self.selectedRange; selectionRange.location += 6; selectionRange.length = tipStr.length; [self insertText:[NSString stringWithFormat:@"![图片](%@)", tipStr]]; [self setSelectionRange:selectionRange]; }], [self createButtonWithTitle:@"分割线" andEventHandler:^{ NSRange selectionRange = self.selectedRange; NSString *insertStr = [self needPreNewLine]? @"\n\n------\n": @"\n------\n"; selectionRange.location += insertStr.length; selectionRange.length = 0; [self insertText:insertStr]; [self setSelectionRange:selectionRange]; }], [self createButtonWithTitle:@"_" andEventHandler:^{ [self insertText:@"_"]; }], [self createButtonWithTitle:@"+" andEventHandler:^{ [self insertText:@"+"]; }], [self createButtonWithTitle:@"~" andEventHandler:^{ [self insertText:@"~"]; }], [self createButtonWithTitle:@"=" andEventHandler:^{ [self insertText:@"="]; }], [self createButtonWithTitle:@"[" andEventHandler:^{ [self insertText:@"["]; }], [self createButtonWithTitle:@"]" andEventHandler:^{ [self insertText:@"]"]; }], [self createButtonWithTitle:@"<" andEventHandler:^{ [self insertText:@"<"]; }], [self createButtonWithTitle:@">" andEventHandler:^{ [self insertText:@">"]; }] ]; } - (BOOL)needPreNewLine{ NSString *preStr = [self.text substringToIndex:self.selectedRange.location]; return !(preStr.length == 0 || [preStr isMatchedByRegex:@"[\\n\\r]+[\\t\\f]*$"]); } - (RFToolbarButton *)createButtonWithTitle:(NSString*)title andEventHandler:(void(^)())handler { return [RFToolbarButton buttonWithTitle:title andEventHandler:handler forControlEvents:UIControlEventTouchUpInside]; } - (void)setSelectionRange:(NSRange)range { UIColor *previousTint = self.tintColor; self.tintColor = UIColor.clearColor; self.selectedRange = range; self.tintColor = previousTint; } #pragma mark md_Method - (void)doTitle{ [self doMDWithLeftStr:@"## " rightStr:@" ##" tipStr:@"在此输入标题" doNeedPreNewLine:YES]; } - (void)doBold{ [self doMDWithLeftStr:@"**" rightStr:@"**" tipStr:@"在此输入粗体文字" doNeedPreNewLine:NO]; } - (void)doItalic{ [self doMDWithLeftStr:@"*" rightStr:@"*" tipStr:@"在此输入斜体文字" doNeedPreNewLine:NO]; } - (void)doCode{ [self doMDWithLeftStr:@"```\n" rightStr:@"\n```" tipStr:@"在此输入代码片段" doNeedPreNewLine:YES]; } - (void)doQuote{ [self doMDWithLeftStr:@"> " rightStr:@"" tipStr:@"在此输入引用文字" doNeedPreNewLine:YES]; } - (void)doList{ [self doMDWithLeftStr:@"- " rightStr:@"" tipStr:@"在此输入列表项" doNeedPreNewLine:YES]; } - (void)doMDWithLeftStr:(NSString *)leftStr rightStr:(NSString *)rightStr tipStr:(NSString *)tipStr doNeedPreNewLine:(BOOL)doNeedPreNewLine{ BOOL needPreNewLine = doNeedPreNewLine? [self needPreNewLine]: NO; if (!leftStr || !rightStr || !tipStr) { return; } NSRange selectionRange = self.selectedRange; NSString *insertStr = [self.text substringWithRange:selectionRange]; if (selectionRange.length > 0) {//已有选中文字 //撤销 if (selectionRange.location >= leftStr.length && selectionRange.location + selectionRange.length + rightStr.length <= self.text.length) { NSRange expandRange = NSMakeRange(selectionRange.location- leftStr.length, selectionRange.length +leftStr.length +rightStr.length); expandRange = [self.text rangeOfString:[NSString stringWithFormat:@"%@%@%@", leftStr, insertStr, rightStr] options:NSLiteralSearch range:expandRange]; if (expandRange.location != NSNotFound) { selectionRange.location -= leftStr.length; selectionRange.length = insertStr.length; [self setSelectionRange:expandRange]; [self insertText:insertStr]; [self setSelectionRange:selectionRange]; return; } } //添加 selectionRange.location += needPreNewLine? leftStr.length +1: leftStr.length; insertStr = [NSString stringWithFormat:needPreNewLine? @"\n%@%@%@": @"%@%@%@", leftStr, insertStr, rightStr]; }else{//未选中任何文字 //添加 selectionRange.location += needPreNewLine? leftStr.length +1: leftStr.length; selectionRange.length = tipStr.length; insertStr = [NSString stringWithFormat:needPreNewLine? @"\n%@%@%@": @"%@%@%@", leftStr, tipStr, rightStr]; } [self insertText:insertStr]; [self setSelectionRange:selectionRange]; } #pragma mark AT - (void)doAT{ __weak typeof(self) weakSelf = self; if (self.curProject) { //@项目成员 [ProjectMemberListViewController showATSomeoneWithBlock:^(User *curUser) { [weakSelf atSomeUser:curUser andRange:self.selectedRange]; } withProject:self.curProject]; }else{ //@好友 [UsersViewController showATSomeoneWithBlock:^(User *curUser) { [weakSelf atSomeUser:curUser andRange:self.selectedRange]; }]; } } - (void)atSomeUser:(User *)curUser andRange:(NSRange)range{ if (curUser) { NSString *appendingStr = [NSString stringWithFormat:@"@%@ ", curUser.name]; [self insertText:appendingStr]; [self becomeFirstResponder]; } } #pragma mark Photo - (void)doPhoto{ // [[UIActionSheet bk_actionSheetCustomWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] destructiveTitle:nil cancelTitle:@"取消" andDidDismissBlock:^(UIActionSheet *sheet, NSInteger index) { [self presentPhotoVCWithIndex:index]; }] showInView:self]; } - (void)presentPhotoVCWithIndex:(NSInteger)index{ if (index == 2) { return; } UIImagePickerController *picker = [[UIImagePickerController alloc] init]; picker.delegate = self; if (index == 0) { // 拍照 if (![Helper checkCameraAuthorizationStatus]) { return; } picker.sourceType = UIImagePickerControllerSourceTypeCamera; }else if (index == 1){ // 相册 if (![Helper checkPhotoLibraryAuthorizationStatus]) { return; } picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; } [[BaseViewController presentingVC] presentViewController:picker animated:YES completion:nil];//进入照相界面 } #pragma mark UIImagePickerControllerDelegate - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage]; // 保存原图片到相册中 if (picker.sourceType == UIImagePickerControllerSourceTypeCamera && originalImage) { UIImageWriteToSavedPhotosAlbum(originalImage, self, nil, NULL); } //上传照片 [picker dismissViewControllerAnimated:YES completion:^{ if (originalImage) { [self doUploadPhoto:originalImage]; } }]; } - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{ [picker dismissViewControllerAnimated:YES completion:nil]; } - (void)doUploadPhoto:(UIImage *)image{ if (_isForProjectTweet || !_curProject) { [self hudTipWillShow:YES]; __weak typeof(self) weakSelf = self; [[Coding_NetAPIManager sharedManager] uploadTweetImage:image doneBlock:^(NSString *imagePath, NSError *error) { [weakSelf hudTipWillShow:NO]; if (imagePath) { //插入文字 NSString *photoLinkStr = [NSString stringWithFormat:[self needPreNewLine]? @"\n![图片](%@)\n": @"![图片](%@)\n", imagePath]; [weakSelf insertText:photoLinkStr]; [weakSelf becomeFirstResponder]; }else{ [NSObject showError:error]; } } progerssBlock:^(CGFloat progressValue) { dispatch_async(dispatch_get_main_queue(), ^{ if (weakSelf.HUD) { weakSelf.HUD.progress = MAX(0, progressValue-0.05) ; } }); }]; }else{ //保存到app内 NSString *dateMarkStr = [[NSDate date] stringWithFormat:@"yyyyMMdd_HHmmss"]; NSString *originalFileName = [NSString stringWithFormat:@"%@.jpg", dateMarkStr]; NSString *fileName = [NSString stringWithFormat:@"%@|||%@|||%@", self.curProject.id.stringValue, @"0", originalFileName]; if ([Coding_FileManager writeUploadDataWithName:fileName andImage:image]) { [self hudTipWillShow:YES]; self.uploadingPhotoName = originalFileName; Coding_UploadTask *uploadTask =[[Coding_FileManager sharedManager] addUploadTaskWithFileName:fileName projectIsPublic:_curProject.is_public.boolValue]; @weakify(self) [RACObserve(uploadTask, progress.fractionCompleted) subscribeNext:^(NSNumber *fractionCompleted) { @strongify(self); dispatch_async(dispatch_get_main_queue(), ^{ if (self.HUD) { self.HUD.progress = MAX(0, fractionCompleted.floatValue-0.05) ; } }); }]; }else{ [NSObject showHudTipStr:[NSString stringWithFormat:@"%@ 文件处理失败", originalFileName]]; } } } - (void)completionUploadWithResult:(id)responseObject error:(NSError *)error{ [self hudTipWillShow:NO]; //移除文件(共有项目不能自动移除) NSString *diskFileName = [NSString stringWithFormat:@"%@|||%@|||%@", self.curProject.id.stringValue, @"0", self.uploadingPhotoName]; [Coding_FileManager deleteUploadDataWithName:diskFileName]; if (!responseObject) { return; } NSString *fileName = nil, *fileUrlStr = @""; if ([responseObject isKindOfClass:[NSString class]]) { fileUrlStr = responseObject; }else if ([responseObject isKindOfClass:[ProjectFile class]]){ ProjectFile *curFile = responseObject; fileName = curFile.name; fileUrlStr = curFile.owner_preview; } if (!fileName || [fileName isEqualToString:self.uploadingPhotoName]) { //插入文字 NSString *photoLinkStr = [NSString stringWithFormat:[self needPreNewLine]? @"\n![图片](%@)\n": @"![图片](%@)\n", fileUrlStr]; [self insertText:photoLinkStr]; [self becomeFirstResponder]; } } - (void)hudTipWillShow:(BOOL)willShow{ if (willShow) { [self resignFirstResponder]; if (!_HUD) { _HUD = [MBProgressHUD showHUDAddedTo:kKeyWindow animated:YES]; _HUD.mode = MBProgressHUDModeDeterminateHorizontalBar; _HUD.labelText = @"正在上传图片..."; _HUD.removeFromSuperViewOnHide = YES; }else{ _HUD.progress = 0; [kKeyWindow addSubview:_HUD]; [_HUD show:YES]; } }else{ [_HUD hide:YES]; } } @end
{ "content_hash": "cf913aa559e7bd733d3d6b760d3e6f10", "timestamp": "", "source": "github", "line_count": 339, "max_line_length": 196, "avg_line_length": 41.200589970501476, "alnum_prop": 0.6196033507553519, "repo_name": "fatjyc/Coding-iOS", "id": "cab6979291943a96d8802e0e295cbe09502d75ae", "size": "14903", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Coding_iOS/Views/EaseMarkdownTextView.m", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "73177" }, { "name": "HTML", "bytes": "298816" }, { "name": "Objective-C", "bytes": "3446925" }, { "name": "Ruby", "bytes": "973" }, { "name": "Shell", "bytes": "227" } ], "symlink_target": "" }
import PuzzleSolver.puzzle_solver PuzzleSolver.puzzle_solver.main() print "\nBye bye!"
{ "content_hash": "1415d0f673da6c6970b3ef3ffe4692a3", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 33, "avg_line_length": 17.8, "alnum_prop": 0.7865168539325843, "repo_name": "marienfressinaud/AI_Puzzle-Solver", "id": "2f90196c510639cd0834d3b8385fea362f8322fe", "size": "133", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "puzzle-solver.py", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "31382" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns:msxsl="urn:schemas-microsoft-com:xslt"> <head> <meta content="en-us" http-equiv="Content-Language" /> <meta content="text/html; charset=utf-16" http-equiv="Content-Type" /> <title _locid="PortabilityAnalysis0">.NET Portability Report</title> <style> /* Body style, for the entire document */ body { background: #F3F3F4; color: #1E1E1F; font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 0; margin: 0; } /* Header1 style, used for the main title */ h1 { padding: 10px 0px 10px 10px; font-size: 21pt; background-color: #E2E2E2; border-bottom: 1px #C1C1C2 solid; color: #201F20; margin: 0; font-weight: normal; } /* Header2 style, used for "Overview" and other sections */ h2 { font-size: 18pt; font-weight: normal; padding: 15px 0 5px 0; margin: 0; } /* Header3 style, used for sub-sections, such as project name */ h3 { font-weight: normal; font-size: 15pt; margin: 0; padding: 15px 0 5px 0; background-color: transparent; } h4 { font-weight: normal; font-size: 12pt; margin: 0; padding: 0 0 0 0; background-color: transparent; } /* Color all hyperlinks one color */ a { color: #1382CE; } /* Paragraph text (for longer informational messages) */ p { font-size: 10pt; } /* Table styles */ table { border-spacing: 0 0; border-collapse: collapse; font-size: 10pt; } table th { background: #E7E7E8; text-align: left; text-decoration: none; font-weight: normal; padding: 3px 6px 3px 6px; } table td { vertical-align: top; padding: 3px 6px 5px 5px; margin: 0px; border: 1px solid #E7E7E8; background: #F7F7F8; } .NoBreakingChanges { color: darkgreen; font-weight:bold; } .FewBreakingChanges { color: orange; font-weight:bold; } .ManyBreakingChanges { color: red; font-weight:bold; } .BreakDetails { margin-left: 30px; } .CompatMessage { font-style: italic; font-size: 10pt; } .GoodMessage { color: darkgreen; } /* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */ .localLink { color: #1E1E1F; background: #EEEEED; text-decoration: none; } .localLink:hover { color: #1382CE; background: #FFFF99; text-decoration: none; } /* Center text, used in the over views cells that contain message level counts */ .textCentered { text-align: center; } /* The message cells in message tables should take up all avaliable space */ .messageCell { width: 100%; } /* Padding around the content after the h1 */ #content { padding: 0px 12px 12px 12px; } /* The overview table expands to width, with a max width of 97% */ #overview table { width: auto; max-width: 75%; } /* The messages tables are always 97% width */ #messages table { width: 97%; } /* All Icons */ .IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded { min-width: 18px; min-height: 18px; background-repeat: no-repeat; background-position: center; } /* Success icon encoded */ .IconSuccessEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+eMgQ77v3Xf3Pe51YKGqqisAEwCR1TIAsiAIblSo6xrdHeJR85Xle3mdmCQKb0PsfqyxxzM8K15HZADl/H5+sHpZwYfxyRjTs+kWwKBx8yoHd2mRiuzF8mkJniWH/13u3Fjrs/EdhsdDFHGB/DLXEJBDLh1MWPAhPo1BLB4WX5yQywHR+m3tVe/t97D52CB/ziG0nIgD/qDuYg8WuCcVZ2YGwlJ3YDugkpR/VNcAEx6GEKhERSr71FuO4YCM4XBdwKvecjIlkSnsO0Hyp/GxSeJAdzBKzpOtnPwyyiPdAZhpZptT04tU+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==); } /* Information icon encoded */ .IconInfoEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=); } /* Warning icon encoded */ .IconWarningEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==); } /* Error icon encoded */ .IconErrorEncoded { /* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */ /* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */ background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=); } </style> </head> <body> <h1 _locid="PortabilityReport">.NET Portability Report</h1> <div id="content"> <div id="submissionId" style="font-size:8pt;"> <p> <i> Submission Id&nbsp; d6b4993a-f815-4ae3-bbc2-834a4898f4fb </i> </p> </div> <h2 _locid="SummaryTitle"> <a name="Portability Summary"></a>Portability Summary </h2> <div id="summary"> <table> <tbody> <tr> <th>Assembly</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> </tr> <tr> <td><strong><a href="#Win8Controls">Win8Controls</a></strong></td> <td class="text-center">98.44 %</td> <td class="text-center">100.00 %</td> <td class="text-center">100.00 %</td> <td class="text-center">100.00 %</td> </tr> </tbody> </table> </div> <div id="details"> <a name="Win8Controls"><h3>Win8Controls</h3></a> <table> <tbody> <tr> <th>Target type</th> <th>ASP.NET 5,Version=v1.0</th> <th>Windows,Version=v8.1</th> <th>.NET Framework,Version=v4.6</th> <th>Windows Phone,Version=v8.1</th> <th>Recommended changes</th> </tr> <tr> <td>System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken</td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconSuccessEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td>System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal</td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconSuccessEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">AddEventHandler``1(System.Func{``0,System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken},System.Action{System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken},``0)</td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconSuccessEncoded"></td> <td></td> </tr> <tr> <td style="padding-left:2em">RemoveEventHandler``1(System.Action{System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken},``0)</td> <td class="IconErrorEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconSuccessEncoded"></td> <td class="IconSuccessEncoded"></td> <td></td> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </tbody> </table> <p> <a href="#Portability Summary">Back to Summary</a> </p> </div> </div> </body> </html>
{ "content_hash": "9f1257e2fe189fa29d3ca82548bc9e57", "timestamp": "", "source": "github", "line_count": 313, "max_line_length": 562, "avg_line_length": 42.201277955271564, "alnum_prop": 0.511620864562041, "repo_name": "kuhlenh/port-to-core", "id": "a6209a0eff031e2aaac563462a29afe2c2ed7d28", "size": "13209", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "Reports/wi/win8controls.0.9.2/Win8Controls-netcore45.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2323514650" } ], "symlink_target": "" }
Control your Kong instance through simple configuration. [![Build Status](https://travis-ci.org/articulate/biplane.svg?branch=master)](https://travis-ci.org/articulate/biplane) ![biplane](http://drops.articulate.com/w1ad/NQlLBhGp+) ## Versioning :warning: - The `1.3.x` branch and release branch is for pre-0.10 Kong, namely the `0.9.x` branch. - The `1.4.x` release line (currently master) is for Kong `+0.10.x`. The `1.4.x` branch is being actively developed to keep up with changes in the latest Kong release cycles. `1.3.x` will be maintained with any backwards compatable changes needed to resolve issues found in future releases that affect Kong `0.9.x`. We will likely not add new features introduced to `1.4.x` to the `1.3.x` branch. ## Installation Download a binary from the [releases page](https://github.com/articulate/biplane/releases) and place somewhere in your `PATH`. You will likely also need to install libevent, libyaml and [bdw-gc](http://braumeister.org/formula/bdw-gc) via Homebrew: `brew install libevent libyaml bdw-gc` ### Docker We also provide a [Docker image](https://hub.docker.com/r/articulate/biplane): `docker pull articulate/biplane`. Images are tagged to match versions as they are released. - `latest` = last tagged version - `master` = current code available on GitHub `master` branch. - `X.Y.Z` = matches release from the GitHub [releases](https://github.com/articulate/biplane/releases) page. ## Usage ### The `--help` ``` biplane - Biplane manages your config changes to a Kong instance Usage: biplane [command] [arguments] Commands: apply [filename] # Apply config to Kong instance config [cmd] [options] # Set biplane configuration options diff [filename] # Diff Kong instance with local config dump [filename] # Retrieve current Kong config help [command] # Help about any command. version # Print biplane version Flags: -h, --help # Help for this command. default: 'false'. ``` ### Using Docker As the Docker image is pointed at the biplane executable simply provide parameters to actually do something. Get the help file. docker run --rm -it articulate/biplane -h Dump the current config to STDOUT docker run --rm -it articulate/biplane dump --host="my-machine-name" --no-https ### Config format Biplane follows the same conventions as [Kongfig](https://github.com/mybuilder/kongfig). If you want to start configuration from an existing Kong instance, you can dump the current config and modify as needed. `biplane dump --host <kong ip/hostname> kong.yml` Config can also be dumped to `stdout` if no output file is specified. The format can also be modified to output as JSON, though the JSON file **cannot** be used to configure Kong through biplane. `biplane dump <...> --format json kong.json` A dumped file might look like the following: ```yaml --- apis: - name: products_admin_api attributes: uris: /admin/products strip_uri: true upstream_url: http://www.example.com/admin/products plugins: - name: acl attributes: config: whitelist: - google-auth - name: jwt attributes: config: key_claim_name: aud secret_is_base64: true uri_param_names: - jwt consumers: - username: google-auth credentials: - name: jwt attributes: key: xxx secret: yyy acls: - group: google-auth - username: docs-user credentials: - name: basic-auth attributes: username: abc password: efg acls: - group: docs ``` You do not need to dump an API in order to apply it. It is merely a convenience mechanism to work with existing Kong instances. You can build a config file from scratch so long as it conforms to the structure shown above. ### Persistent Options Most biplane actions require a host or IP, a port (if not the default of 8001) and, if not using SSL, the `--no-https` flag. These flags can be saved using the `config` command: `biplane config set kong.host=api.example.com kong.port=8888 kong.https=false` This will allow you to simply run biplane commands without needing to specify the host/port/https flags each time you run a command. ### Applying Config `biplane apply my-config.yaml` This will also show the differences as they are applied. If you would rather dry run this operation, use the [`diff`](#diffing) command instead. ### Diffing `biplane diff my-config.yaml` This will output a colored diff of changes between your local config and the current API. One caveat is that Kong often supplies _and returns_ default values that are not required to be set in the calls to the API. So the diff can often contain differences that you did not set in your config. This **will** trigger an API call when doing an `apply`, however, if they are default values and they remain unchanged in your config, this update will not affect any change. In order to avoid these "false positives", please add any default values supplied by Kong to your config. This is good practice anyways to avoid issues where Kong or plugin vendors might update defaults without your knowledge. ## Building Locally If you have Crystal 0.15.0 installed (the currently supported version of Crystal), you can simply `make build` If you don't or can't install 0.15.0, you can build it using the local Dockerfile definition: `make build-container` This will install deps, run specs and build the executable. To run: `./bin/docker <command>` This runtime will load files from the local directory that the command is run from. You can also simply use the command in the `bin/docker` file to run the built image anywhere you want on your filesystem. ## Roadmap _(In no particular order)_ - [x] Config linting - [x] Variable interpolation in the config - [ ] Parallel fanout of API requests - [ ] Self updating binary - [ ] Extract Kong library into separate shard - [ ] Prettier error messaging ## Contributing 1. Fork it ( https://github.com/plukevdh/biplane/fork ) 2. Create your feature branch (git checkout -b my-new-feature) 3. Commit your changes (git commit -am 'Add some feature') 4. Push to the branch (git push origin my-new-feature) 5. Create a new Pull Request ## Contributors - [plukevdh](https://github.com/plukevdh) Luke van der Hoeven - creator, maintainer
{ "content_hash": "5cc6c4ec0f22a4313d05c82273f7bc1d", "timestamp": "", "source": "github", "line_count": 176, "max_line_length": 695, "avg_line_length": 36.69886363636363, "alnum_prop": 0.7160551168911596, "repo_name": "articulate/biplane", "id": "8d0e9c319f8b0e801d01b0b1d2bb3277ab8e7e52", "size": "6470", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Crystal", "bytes": "88452" }, { "name": "Makefile", "bytes": "559" }, { "name": "Shell", "bytes": "2515" } ], "symlink_target": "" }
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Rename Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename ''' <summary> ''' This test class contains tests which verifies that the rename engine performs correct ''' refactorings that do not break user code. These tests call through the ''' Renamer.RenameSymbol entrypoint, and thus do not test any behavior with interactive ''' rename. The position given with the $$ mark in the tests is just the symbol that is renamed; ''' there is no fancy logic applied to it. ''' </summary> Partial Public Class RenameEngineTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <WorkItem(543661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543661")> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CannotRenameNamespaceAlias() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using [|sys|] = System; class Program { static void Main(string[] args) { [|$$sys|].Console.Write("test"); } } </Document> </Project> </Workspace>, renameTo:="Sys2") End Using End Sub <WorkItem(813409, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813409")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameTypeDoesNotRenameGeneratedConstructorCalls() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> struct [|$$Type|] { [|Type|](int x) : this() { } } </Document> </Project> </Workspace>, renameTo:="U") End Using End Sub <WorkItem(856078, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/856078")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub UnmodifiedDocumentsAreNotCheckedOutBySourceControl() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Test1.cs"> class C { int [|$$abc|] = 5; } </Document> <Document FilePath="Test2.cs"> class C2 { int abc = 5; } </Document> </Project> </Workspace>, renameTo:="def") Dim originalDocument = result.ConflictResolution.OldSolution.Projects.First().Documents.Where(Function(d) d.FilePath = "Test2.cs").Single() Dim newDocument = result.ConflictResolution.NewSolution.Projects.First().Documents.Where(Function(d) d.FilePath = "Test2.cs").Single() Assert.Same(originalDocument.State, newDocument.State) Assert.Equal(1, result.ConflictResolution.NewSolution.GetChangedDocuments(result.ConflictResolution.OldSolution).Count) End Using End Sub <WorkItem(773400, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773400")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ReferenceConflictInsideDelegateLocalNotRenamed() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { public delegate void Foo(int x); public void FooMeth(int x) { } public void Sub() { Foo {|DeclConflict:x|} = new Foo(FooMeth); int [|$$z|] = 1; // Rename z to x x({|unresolve2:z|}); } } </Document> </Project> </Workspace>, renameTo:="x") result.AssertLabeledSpansAre("DeclConflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("unresolve2", "x", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(773673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773673")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMoreThanOneTokenInUnResolvedStatement() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class {|DeclConflict:C|} { public void Sub() { {|unresolve1:D|} d = new {|unresolve2:D|}(); } } class {|unresolve3:$$D|} // Rename to C { } </Document> </Project> </Workspace>, renameTo:="C") result.AssertLabeledSpansAre("DeclConflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("unresolve1", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("unresolve2", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("unresolve3", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInvocationExpressionAcrossProjects() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document FilePath="Test1.cs"> public class [|$$ClassA|] { public static void Bar() { } } </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>CSharpAssembly</ProjectReference> <Document FilePath="Test2.cs"> public class B { void foo() { [|ClassA|].Bar(); } } </Document> </Project> </Workspace>, renameTo:="A") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInvocationExpressionAcrossProjectsWithPartialClass() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document FilePath="Test1.cs"> public partial class [|$$ClassA|] { public static void Bar() { } } public partial class [|ClassA|] { } </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>CSharpAssembly</ProjectReference> <Document FilePath="Test2.cs"> public class B { void foo() { [|ClassA|].Bar(); } } </Document> </Project> </Workspace>, renameTo:="A") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInvocationExpressionAcrossProjectsWithConflictResolve() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document FilePath="Test1.cs"> namespace X { public class [|$$ClassA|] { public {|resolve:A|}.B B; public static void Bar() { } } } namespace A { public class B { } } </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>CSharpAssembly</ProjectReference> <Document FilePath="Test2.cs"> using X; public class B { void foo() { {|resolve2:ClassA|}.Bar(); } } </Document> </Project> </Workspace>, renameTo:="A") result.AssertLabeledSpansAre("resolve", "global::A", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansAre("resolve2", "X.A.Bar();", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RollBackExpandedConflicts_WithinInvocationExpression() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void Main(string[] {|conflict1:a|}) { var [|$$b|] = Convert.{|conflict3:ToDouble|}({|conflict2:a|}[0]); } } </Document> </Project> </Workspace>, renameTo:="a") result.AssertLabeledSpansAre("conflict1", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("conflict2", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("conflict3", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RollBackExpandedConflicts_WithinQuery() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Dim [|$$x|] As String() ' rename x to y Dim {|conflict1:y|} = From x In {|conflict2:x|} Select x End Class </Document> </Project> </Workspace>, renameTo:="y") result.AssertLabeledSpansAre("conflict1", "y", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("conflict2", "y", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameOverloadCSharp() Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameOverloads, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { public void [|$$foo|]() { [|foo|](); } public void [|foo|]&lt;T&gt;() { [|foo|]&lt;T&gt;(); } public void [|foo|](int i) { [|foo|](i); } } </Document> </Project> </Workspace>, renameTo:="BarBaz", changedOptionSet:=changingOptions) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameOverloadVisualBasic() Dim changingOptions = New Dictionary(Of OptionKey, Object)() changingOptions.Add(RenameOptions.RenameOverloads, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Collections.Generic Imports System.Linq Public Class Program Sub Main(args As String()) End Sub Public Sub [|$$foo|]() [|foo|]() End Sub Public Sub [|foo|](Of T)() [|foo|](Of T)() End Sub Public Sub [|foo|](s As String) [|foo|](s) End Sub Public Shared Sub [|foo|](d As Double) [|foo|](d) End Sub End Class </Document> </Project> </Workspace>, renameTo:="BarBaz", changedOptionSet:=changingOptions) End Using End Sub <Fact, WorkItem(761929, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/761929"), Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictCheckInInvocationCSharp() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication5 { class [|$$Program2|] { private static Func&lt;[|Program2|], bool> func = null; private static void Main23(object v) { func(new [|Program2|]()); } } } </Document> </Project> </Workspace>, renameTo:="Bar") End Using End Sub <Fact, WorkItem(761922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/761922"), Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ConflictCheckInInvocationVisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Collections.Generic Imports System.Linq Namespace ns Class [|Program2|] Private Shared func As Func(Of [|Program2|], Boolean) = Nothing Private Shared Sub Main2343(args As String()) func(New [|$$Program2|]()) End Sub End Class End Namespace </Document> </Project> </Workspace>, renameTo:="Bar") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameType() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Foo|] { void Blah() { {|stmt1:Foo|} f = new {|stmt1:Foo|}(); } } </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("stmt1", replacement:="BarBaz", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameTypeAcrossFiles() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#"> <Document> class [|$$Foo|] { void Blah() { {|stmt1:Foo|} f = new {|stmt1:Foo|}(); } } </Document> <Document> class FogBar { void Blah() { {|stmt2:Foo|} f = new {|stmt2:Foo|}(); } } </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("stmt1", replacement:="BarBaz", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", replacement:="BarBaz", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameTypeAcrossProjectsAndLanguages() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document> namespace N { public class [|$$Foo|] { void Blah() { {|csstmt1:Foo|} f = new {|csstmt1:Foo|}(); } } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>CSharpAssembly</ProjectReference> <Document> Imports N Class FogBar Sub Blah() Dim f = new {|vbstmt1:Foo|}() End Sub End Class </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("csstmt1", "BarBaz", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("vbstmt1", "BarBaz", RelatedLocationType.NoConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCSharpTypeFromConstructorDefinition() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|Foo|] { [|$$Foo|]() { } void Blah() { {|stmt1:Foo|} f = new {|stmt1:Foo|}(); } } </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("stmt1", replacement:="BarBaz", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCSharpTypeFromConstructorUse() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|Foo|] { [|Foo|]() { } void Blah() { {|stmt1:Foo|} f = new {|stmt1:$$Foo|}(); } } </Document> </Project> </Workspace>, renameTo:="Bar") result.AssertLabeledSpansAre("stmt1", replacement:="Bar", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCSharpTypeFromDestructor() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|Foo|] { ~[|$$Foo|]() { } } </Document> </Project> </Workspace>, renameTo:="BarBaz") End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCSharpTypeFromSynthesizedConstructorUse() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|Foo|] { void Blah() { {|stmt1:Foo|} f = new {|stmt1:$$Foo|}(); } } </Document> </Project> </Workspace>, renameTo:="Bar") result.AssertLabeledSpansAre("stmt1", replacement:="Bar", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCSharpPredefinedTypeVariables1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class Program { static void Main(string[] args) { System.Int32 {|stmt1:$$foofoo|} = 23; } } </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("stmt1", "BarBaz", RelatedLocationType.NoConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCSharpPredefinedTypeVariables2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class Program { static void Main(string[] args) { Int32 {|stmt1:$$foofoo|} = 23; } } </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("stmt1", "BarBaz", RelatedLocationType.NoConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCSharpPredefinedTypeVariables3() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class Program { static void Main(string[] args) { int {|stmt1:$$fogbar|} = 45; } } </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("stmt1", "BarBaz", RelatedLocationType.NoConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameVisualBasicPredefinedTypeVariables1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main(args As String()) Dim {|stmt1:$$a|} As System.Int32 = 1 End Sub End Module </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("stmt1", "BarBaz", RelatedLocationType.NoConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameVisualBasicPredefinedTypeVariables2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main(args As String()) Dim {|stmt1:$$a|} As Int32 = 1 End Sub End Module </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("stmt1", "BarBaz", RelatedLocationType.NoConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameVisualBasicPredefinedTypeVariables3() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Program Sub Main(args As String()) Dim {|stmt1:$$a|} As Integer = 1 End Sub End Module </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("stmt1", "BarBaz", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(539801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539801")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCSharpEnumMemberToContainingEnumName() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> enum Test { [|$$FogBar|], }; </Document> </Project> </Workspace>, renameTo:="Test") End Using End Sub <WorkItem(539801, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539801")> <WorkItem(5886, "https://github.com/dotnet/roslyn/pull/5886")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCSharpEnumToEnumMemberName() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> enum [|$$FogBar|] { TestEnum, }; </Document> </Project> </Workspace>, renameTo:="TestEnum") End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameVisualBasicTypeFromConstructorUse() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|Foo|] Public Sub New() End Sub Public Sub Blah() Dim x = New {|stmt1:$$Foo|}() End Sub End Class </Document> </Project> </Workspace>, renameTo:="Bar") result.AssertLabeledSpansAre("stmt1", "Bar", RelatedLocationType.NoConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameVisualBasicTypeFromSynthesizedConstructorUse() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|Foo|] Public Sub Blah() Dim x = New {|stmt1:$$Foo|}() End Sub End Class </Document> </Project> </Workspace>, renameTo:="Bar") result.AssertLabeledSpansAre("stmt1", "Bar", RelatedLocationType.NoConflict) End Using End Sub <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameNamespace() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Namespace [|$$FooNamespace|] End Namespace </Document> <Document> namespace [|FooNamespace|] { } </Document> </Project> </Workspace>, renameTo:="BarBazNamespace") End Using End Sub <Fact> <WorkItem(6874, "http://vstfdevdiv:8080/DevDiv_Projects/Roslyn/_workitems/edit/6874")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameVisualBasicEnum() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Enum [|$$Test|] One Two End Enum </Document> </Project> </Workspace>, renameTo:="BarBaz") End Using End Sub <Fact> <WorkItem(6874, "http://vstfdevdiv:8080/DevDiv_Projects/Roslyn/_workitems/edit/6874")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameVisualBasicEnumMember() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Enum Test [|$$One|] Two End Enum </Document> </Project> </Workspace>, renameTo:="BarBaz") End Using End Sub <Fact> <WorkItem(539525, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539525")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub DoNothingRename() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Foo { void [|$$Blah|]() { } } </Document> </Project> </Workspace>, renameTo:="Blah") End Using End Sub <Fact> <WorkItem(553631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553631")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CSharpBugfix553631() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { void Main(string[] args) { string {|stmt1:$$s|} = Foo&lt;string, string&gt;(); } string Foo&lt;T, S&gt;() { Return Foo &lt;T, S&gt;(); } } </Document> </Project> </Workspace>, renameTo:="Blah") result.AssertLabeledSpansAre("stmt1", replacement:="Blah", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <WorkItem(553631, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553631")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VisualBasicBugfix553631() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Collections.Generic Imports System.Linq Class Program Sub Main(args As String()) End Sub Public Sub Bar() Dim {|stmt1:$$e|} As String = Foo(Of String)() End Sub Public Function Foo(Of A)() As String End Function End Class </Document> </Project> </Workspace>, renameTo:="Blah") result.AssertLabeledSpansAre("stmt1", replacement:="Blah", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <WorkItem(541697, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541697")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameExtensionMethod() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public static class C { public static void [|$$Foo|](this string s) { } } class Program { static void Main() { "".{|stmt1:Foo|}(); } } </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("stmt1", replacement:="BarBaz", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <WorkItem(542202, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542202")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCSharpIndexerNamedArgument1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { int this[int x = 5, int [|y|] = 7] { get { return 0; } set { } } void Foo() { var y = this[{|stmt1:$$y|}: 1]; } } </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("stmt1", replacement:="BarBaz", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <WorkItem(542106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542106")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCSharpIndexerNamedArgument2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { int this[int [|$$x|]] { set { } } void Foo() { this[{|stmt1:x|}: 1] = 0; } } </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("stmt1", replacement:="BarBaz", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <WorkItem(541928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541928")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameRangeVariable() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Linq; class C { static void Main(string[] args) { var temp = from x in "abc" let {|stmt1:y|} = x.ToString() select {|stmt1:$$y|} into w select w; } } </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("stmt1", replacement:="BarBaz", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <WorkItem(542106, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542106")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameVisualBasicParameterizedPropertyNamedArgument() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Default Property Item([|$$x|] As Integer) As Integer Get Return 42 End Get Set End Set End Property Sub Foo() Me({|stmt1:x|}:=1) = 0 End Sub End Class </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("stmt1", "BarBaz", RelatedLocationType.NoConflict) End Using End Sub <Fact> <WorkItem(543340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543340")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameIndexerParameterFromDeclaration() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { int this[int [|$$x|], int y] { get { return {|stmt1:x|} + y; } set { value = {|stmt2:x|} + y; } } } </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("stmt1", replacement:="BarBaz", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", replacement:="BarBaz", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <WorkItem(543340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543340")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameIndexerParameterFromUseInsideGetAccessor() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { int this[int [|x|], int y] { get { return {|stmt1:$$x|} + y; } set { value = {|stmt2:x|} + y; } } } </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("stmt1", replacement:="BarBaz", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", replacement:="BarBaz", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <WorkItem(543340, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543340")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameIndexerParameterFromUseInsideSetAccessor() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { int this[int [|x|], int y] { get { return {|stmt1:x|} + y; } set { value = {|stmt2:$$x|} + y; } } } </Document> </Project> </Workspace>, renameTo:="BarBaz") result.AssertLabeledSpansAre("stmt1", replacement:="BarBaz", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", replacement:="BarBaz", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact> <WorkItem(542492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542492")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamePartialMethodParameter() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; public partial class Test { partial void Foo(object [|$$o|]) { } } partial class Test { partial void Foo(object [|o|]); } </Document> </Project> </Workspace>, renameTo:="BarBaz") End Using End Sub <WorkItem(528820, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528820")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameVisualBasicAnonymousKey() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Option Infer On Imports System Module Program Sub Main(args As String()) Dim namedCust = New With {.Name = "Blue Yonder Airlines", .[|$$City|] = "Snoqualmie"} End Sub End Module </Document> </Project> </Workspace>, renameTo:="y") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(542543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542543")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameIncludesPreviouslyInvalidReference() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; class Program { int [|$$y|] = 2; static void Main(string[] args) { {|stmt1:x|} = 1; } } </Document> </Project> </Workspace>, renameTo:="x") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(543027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543027")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameVariableInQueryAsUsingStatement() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document FilePath="Test.cs"> using System; using System.Linq; class Program { public static void Main(string[] args) { MyManagedType {|stmt1:mnObj1|} = new MyManagedType(); using ({|stmt2:m$$nObj1|}) { } } } class MyManagedType : System.IDisposable { public void Dispose() { } } </Document> </Project> </Workspace>, renameTo:="y") result.AssertLabeledSpansAre("stmt1", replacement:="y", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", replacement:="y", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(543169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543169")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub LambdaWithOutParameter() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document FilePath="Test.cs"> using System; using System.Linq; class D { static void Main(string[] args) { string[] str = new string[] { }; var s = str.Where(out {|stmt1:$$x|} => { return {|stmt1:x|} == "1"; }); } } </Document> </Project> </Workspace>, renameTo:="y") result.AssertLabeledSpansAre("stmt1", replacement:="y", type:=RelatedLocationType.NoConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(543567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543567")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CascadeBetweenOverridingProperties() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="VisualBasicAssembly" CommonReferences="true"> <Document FilePath="Test.vb"> Module Program Sub Main(args As String()) End Sub End Module Class C Public Overridable ReadOnly Property [|$$Total|]() As Double Get Return 42 End Get End Property End Class Class M Inherits C Public Overrides ReadOnly Property [|Total|]() As Double Get Return MyBase.{|stmt1:Total|} * rate End Get End Property End Class </Document> </Project> </Workspace>, renameTo:="Foo") result.AssertLabeledSpansAre("stmt1", "Foo", RelatedLocationType.NoConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(529799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529799")> Public Sub CascadeBetweenImplementedInterfaceEvent() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="VisualBasicAssembly" CommonReferences="true"> <Document FilePath="Test.vb"> Class C Event E([|$$x|] As Integer) Sub Foo() RaiseEvent E({|stmt1:x|}:=1) End Sub End Class </Document> </Project> </Workspace>, renameTo:="y") result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(543567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543567")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CascadeBetweenEventParameters() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document FilePath="Test.cs"> using System; interface IFoo { event EventHandler [|$$Foo|]; } class Bar : IFoo { public event EventHandler [|Foo|]; } </Document> </Project> </Workspace>, renameTo:="BarBaz") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(531260, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531260")> Public Sub DoNotCascadeToMetadataSymbols() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class C Implements System.ICloneable Public Function [|$$Clone|]() As Object Implements System.ICloneable.Clone Throw New System.NotImplementedException() End Function End Class </Document> </Project> </Workspace>, renameTo:="CloneImpl") End Using End Sub <WorkItem(545473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545473")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamePartialTypeParameter_CSharp1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ partial class Class1 { partial void foo<$$[|T|]>([|T|] x); partial void foo<[|T|]>([|T|] x) { } }]]></Document> </Project> </Workspace>, renameTo:="BarBaz") End Using End Sub <WorkItem(545473, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545473")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamePartialTypeParameter_CSharp2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ partial class Class1 { partial void foo<[|T|]>([|T|] x); partial void foo<$$[|T|]>([|T|] x) { } }]]></Document> </Project> </Workspace>, renameTo:="BarBaz") End Using End Sub <WorkItem(545472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545472")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamePartialTypeParameter_VB1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Public Module Module1 Partial Private Sub Foo(Of [|$$T|] As Class)(x as [|T|]) End Sub Private Sub foo(Of [|T|] As Class)(x as [|T|]) End Sub End Module ]]></Document> </Project> </Workspace>, renameTo:="BarBaz") End Using End Sub <WorkItem(545472, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545472")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamePartialTypeParameter_VB2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Public Module Module1 Partial Private Sub Foo(Of [|T|] As Class)(x as [|T|]) End Sub Private Sub foo(Of [|$$T|] As Class)(x as [|T|]) End Sub End Module ]]></Document> </Project> </Workspace>, renameTo:="BarBaz") End Using End Sub <WorkItem(529163, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529163")> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub AmbiguousBeforeRenameHandledCorrectly_Bug11516() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Namespace NS Module M End Module End Namespace Namespace NS.[|$$M|] End Namespace </Document> </Project> </Workspace>, renameTo:="N") End Using End Sub <WorkItem(529163, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529163")> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub AmbiguousBeforeRenameHandledCorrectly_Bug11516_2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> namespace Foo { class B { } } namespace Foo.[|$$B|] { } </Document> </Project> </Workspace>, renameTo:="N") End Using End Sub <WorkItem(554092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554092")> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamePartialMethods_1_CS() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class Foo { partial void [|F|](); } partial class Foo { partial void [|$$F|]() { throw new System.Exception("F"); } } </Document> </Project> </Workspace>, renameTo:="Bar") End Using End Sub <WorkItem(554092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554092")> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamePartialMethods_2_CS() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class Foo { partial void [|$$F|](); } partial class Foo { partial void [|F|]() { throw new System.Exception("F"); } } </Document> </Project> </Workspace>, renameTo:="Bar") End Using End Sub <WorkItem(554092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554092")> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamePartialMethods_1_VB() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> partial class Foo partial private sub [|F|]() end class partial class Foo private sub [|$$F|]() throw new System.Exception("F") end sub end class </Document> </Project> </Workspace>, renameTo:="Bar") End Using End Sub <WorkItem(554092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554092")> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamePartialMethods_2_VB() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> partial class Foo partial private sub [|$$F|]() end class partial class Foo private sub [|F|]() throw new System.Exception("F") end sub end class </Document> </Project> </Workspace>, renameTo:="Bar") End Using End Sub <WorkItem(530740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530740")> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug530740() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using MyInt = System.[|Int32|]; namespace System { public struct [|$$Int32|] { public static implicit operator MyInt(int x) { return default(MyInt); } } } class A { static void Foo(int x) { Console.WriteLine("int"); } static void Foo(MyInt x) { Console.WriteLine("MyInt"); } static void Main() { Foo((MyInt)0); } } </Document> </Project> </Workspace>, renameTo:="MyInt") End Using End Sub <WorkItem(530082, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530082")> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMethodThatImplementsInterfaceMethod() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Interface I Sub Foo(Optional x As Integer = 0) End Interface Class C Implements I Shared Sub Main() DirectCast(New C(), I).Foo() End Sub Private Sub [|$$I_Foo|](Optional x As Integer = 0) Implements I.Foo Console.WriteLine("test") End Sub End Class </Document> </Project> </Workspace>, renameTo:="Foo") End Using End Sub <WorkItem(529874, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529874")> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub DoNotRemoveAttributeSuffixOn__Attribute() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System &lt;[|_Attribute2|]&gt; ' full width _! Class [|$$_Attribute2|] Inherits Attribute End Class </Document> </Project> </Workspace>, renameTo:="_Attribute") End Using End Sub <WorkItem(553315, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553315")> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameEventParameterOnUsage() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Event E([|x|] As Integer) Sub Foo() RaiseEvent E({|stmt1:$$x|}:=1) End Sub End Class </Document> </Project> </Workspace>, renameTo:="bar") result.AssertLabeledSpansAre("stmt1", "bar", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(529819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529819")> <Fact> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCompilerGeneratedBackingFieldForNonCustomEvent() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class B Event [|$$X|]() ' Rename X to Y Sub Foo() {|stmt1:XEvent|}() End Sub End Class </Document> </Project> </Workspace>, renameTo:="Y") result.AssertLabeledSpecialSpansAre("stmt1", "YEvent", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(576607, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576607")> <WorkItem(529819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529819")> <Fact()> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCompilerGeneratedEventHandlerForNonCustomEvent() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class B Event [|$$X|]() ' Rename X to Y Sub Foo() Dim y = New B.{|stmt1:XEventHandler|}(AddressOf bar) End Sub Shared Sub bar() End Sub End Class </Document> </Project> </Workspace>, renameTo:="Y") result.AssertLabeledSpecialSpansAre("stmt1", "YEventHandler", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(576966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576966")> <Fact()> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CSharpRenameParenthesizedFunctionName() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|$$Foo|]() { (({|stmt1:Foo|}))(); } } </Document> </Project> </Workspace>, renameTo:="Bar") result.AssertLabeledSpansAre("stmt1", "Bar", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(601123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/601123")> <Fact()> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VisualBasicAwaitAsIdentifierInAsyncShouldBeEscaped() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Module M Async Function methodIt() As Task(Of String) Dim a As Func(Of String) = AddressOf {|stmt1:Foo|} End Function Function [|$$Foo|]() As String End Function End Module </Document> </Project> </Workspace>, renameTo:="Await") result.AssertLabeledSpecialSpansAre("stmt1", "[Await]", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(601123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/601123")> <Fact()> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CSharpAwaitAsIdentifierInAsyncMethodShouldBeEscaped0() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using System.Threading.Tasks; class M { async public Task<string> methodIt() { Func<string> a = {|stmt1:Foo|}; return null; } public static string [|$$Foo|]() { return ""; } } ]]> </Document> </Project> </Workspace>, renameTo:="await") result.AssertLabeledSpansAre("stmt1", "@await", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(601123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/601123")> <Fact()> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CSharpAwaitAsIdentifierInAsyncLambdaShouldBeEscaped() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using System.Threading.Tasks; class s { public void abc() { Func<Task> sin = async () => { {|stmt1:Foo|}(); }; } public int [|$$Foo|]() { return 0; } } ]]> </Document> </Project> </Workspace>, renameTo:="await") result.AssertLabeledSpansAre("stmt1", "@await", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(601123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/601123")> <Fact()> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CSharpAwaitAsIdentifierInAsyncLambdaShouldBeEscaped1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using System.Threading.Tasks; class s { public void abc() { Func<int, Task<int>> sink2 = (async c => { return {|stmt2:Foo|}(); }); } public int [|$$Foo|]() { return 0; } } ]]> </Document> </Project> </Workspace>, renameTo:="await") result.AssertLabeledSpansAre("stmt2", "@await", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(601123, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/601123")> <Fact()> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CSharpAwaitAsIdentifierInAsyncLambdaShouldNotBeEscaped() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ using System; using System.Threading.Tasks; class s { public void abc() { Func<int, int> sink4 = ((c) => { return {|stmt3:Foo|}(); }); } public int [|$$Foo|]() { return 0; } } ]]> </Document> </Project> </Workspace>, renameTo:="await") result.AssertLabeledSpansAre("stmt3", "await", RelatedLocationType.NoConflict) End Using End Sub <Fact()> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VBRoundTripMissingModuleName_1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports N Module Program Sub Main() Dim mybar As N.{|stmt1:Foo|} = New {|stmt1:Foo|}() End Sub End Module Namespace N Module X Class [|$$Foo|] End Class End Module End Namespace </Document> </Project> </Workspace>, renameTo:="Bar") result.AssertLabeledSpansAre("stmt1", "Bar", RelatedLocationType.NoConflict) End Using End Sub <Fact()> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VBRoundTripMissingModuleName_2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports N Module Program Sub Main() N.{|stmt1:Foo|}() End Sub End Module Namespace N Module X Sub [|$$Foo|]() End Sub End Module End Namespace </Document> </Project> </Workspace>, renameTo:="Bar") result.AssertLabeledSpansAre("stmt1", "Bar", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(603767, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603767")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug603767_RenamePartialAttributeDeclarationWithDifferentCasingAndCSharpUsage() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Imports System Public Class [|XAttribute|] Inherits Attribute End Class Partial Public Class [|$$XATTRIBUTE|] Inherits Attribute End Class </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> [{|resolved:X|}] class C { } </Document> </Project> </Workspace>, renameTo:="XATTRIBUTe") result.AssertLabeledSpansAre("resolved", "XATTRIBUTe", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(603371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603371")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug603371_VisualBasicRenameAttributeToGlobal() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Imports System &lt;{|escaped:Foo|}&gt; Class {|escaped:$$Foo|} ' Rename Foo to Global Inherits Attribute End Class </Document> </Project> </Workspace>, renameTo:="Global") result.AssertLabeledSpecialSpansAre("escaped", "[Global]", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(603371, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/603371")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug603371_VisualBasicRenameAttributeToGlobal_2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Imports System &lt;{|escaped:Foo|}&gt; Class {|escaped:$$Foo|} ' Rename Foo to Global Inherits Attribute End Class </Document> </Project> </Workspace>, renameTo:="[global]") result.AssertLabeledSpansAre("escaped", "[global]", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(602494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602494")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug602494_RenameOverrideWithNoOverriddenMember() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document> class C1 { override void [|$$Foo|]() {} } </Document> </Project> </Workspace>, renameTo:="Bar") End Using End Sub <WorkItem(576607, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576607")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug576607() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Class B Event [|$$X|]() Sub Foo() Dim y = New {|stmt1:XEventHandler|}(AddressOf bar) End Sub Shared Sub bar() End Sub End Class </Document> </Project> </Workspace>, renameTo:="Baz") result.AssertLabeledSpecialSpansAre("stmt1", "BazEventHandler", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug529765_VisualBasicOverrideImplicitPropertyAccessor() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Public Class A Public Overridable ReadOnly Property [|$$X|](y As Integer) As Integer Get Return 0 End Get End Property End Class Public Class C Inherits A Public Overrides Function {|getaccessor:get_X|}(Y As Integer) As Integer End Function End Class </Document> </Project> </Workspace>, renameTo:="Z") result.AssertLabeledSpecialSpansAre("getaccessor", "get_Z", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug529765_VisualBasicOverrideImplicitPropertyAccessor_2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Public Class A Public Overridable ReadOnly Property [|X|](y As Integer) As Integer Get Return 0 End Get End Property End Class Public Class C Inherits A Public Overrides Function {|getaccessor:$$Get_X|}(Y As Integer) As Integer End Function End Class </Document> </Project> </Workspace>, renameTo:="Z") result.AssertLabeledSpecialSpansAre("getaccessor", "Get_Z", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug529765_VisualBasicOverrideImplicitPropertyAccessor_3() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Public Class A Public Overridable ReadOnly Property [|X|](y As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class Public Class C Inherits A Public Overrides Function {|getaccessor:$$Get_X|}(Y As Integer) As Integer End Function Public Overrides Sub {|setaccessor:Set_X|}(index as integer, Y As Integer) End Sub End Class </Document> </Project> </Workspace>, renameTo:="Z") result.AssertLabeledSpecialSpansAre("getaccessor", "Get_Z", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("setaccessor", "Set_Z", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug529765_CrossLanguageOverrideImplicitPropertyAccessor_1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Public Class A Public Overridable Property [|$$X|](y As Integer) As Integer Get Return 0 End Get Set End Set End Property Public Shared Sub Main() End Sub End Class </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> class B : A { public override int {|getaccessor:get_X|}(int y) { } public override void {|setaccessor:set_X|}(int y, int value) { } } </Document> </Project> </Workspace>, renameTo:="Z") result.AssertLabeledSpecialSpansAre("getaccessor", "get_Z", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("setaccessor", "set_Z", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug529765_CrossLanguageOverrideImplicitPropertyAccessor_2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Public Class A Public Overridable Property [|$$X|](y As Integer) As Integer Get Return 0 End Get Set End Set End Property Public Shared Sub Main() End Sub End Class </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> class B : A { public override int {|getaccessor:get_X|}(int y) { return base.{|getaccessorstmt:get_X|}(y); } public override void {|setaccessor:set_X|}(int y, int value) { base.{|setaccessorstmt:set_X|}(y, value); } } </Document> </Project> </Workspace>, renameTo:="Z") result.AssertLabeledSpecialSpansAre("getaccessor", "get_Z", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("setaccessor", "set_Z", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("getaccessorstmt", "get_Z", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("setaccessorstmt", "set_Z", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug529765_CrossLanguageOverrideImplicitPropertyAccessor_3() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Public Class A Public Overridable Property [|X|](y As Integer) As Integer Get Return 0 End Get Set End Set End Property Public Shared Sub Main() End Sub End Class </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> class B : A { public override int {|getaccessor:get_X|}(int y) { return base.{|getaccessorstmt:get_X|}(y); } public override void {|setaccessor:set_X|}(int y, int value) { base.{|setaccessorstmt:$$set_X|}(y, value); } } </Document> </Project> </Workspace>, renameTo:="Z") result.AssertLabeledSpecialSpansAre("getaccessor", "get_Z", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("setaccessor", "set_Z", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("getaccessorstmt", "get_Z", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("setaccessorstmt", "set_Z", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug529765_CrossLanguageOverrideImplicitPropertyAccessor_4() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Public Class A Public Overridable Property [|X|](y As Integer) As Integer Get Return 0 End Get Set End Set End Property Public Shared Sub Main() End Sub End Class Public Class B Inherits A Public Overrides Property [|$$X|](y As Integer) As Integer Get Return 0 End Get Set End Set End Property Public Shared Sub Main() End Sub End Class </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> class B : A { public override int {|getaccessor:get_X|}(int y) { return base.{|getaccessorstmt:get_X|}(y); } public override void {|setaccessor:set_X|}(int y, int value) { base.{|setaccessorstmt:set_X|}(y, value); } } </Document> </Project> </Workspace>, renameTo:="Z") result.AssertLabeledSpecialSpansAre("getaccessor", "get_Z", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("setaccessor", "set_Z", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("getaccessorstmt", "get_Z", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("setaccessorstmt", "set_Z", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(529765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529765")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug529765_CrossLanguageOverrideImplicitPropertyAccessor_5() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Public Class A Public Overridable Property [|X|](y As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class Public Class B Inherits A Public Overrides Property [|X|](y As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> class B : A { public override int {|getaccessor:get_X|}(int y) { return base.{|getaccessorstmt:get_X|}(y); } public override void {|setaccessor:$$set_X|}(int y, int value) { base.{|setaccessorstmt:set_X|}(y, value); } } </Document> </Project> </Workspace>, renameTo:="Z") result.AssertLabeledSpecialSpansAre("getaccessor", "get_Z", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("setaccessor", "set_Z", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("getaccessorstmt", "get_Z", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("setaccessorstmt", "set_Z", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(610120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/610120")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug610120_CrossLanguageOverrideImplicitPropertyAccessorConflictWithVBProperty() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Public Class A Public Overridable Property {|conflict:X|}({|declconflict:y|} As Integer) As Integer Get Return 0 End Get Set End Set End Property Public Shared Sub Main() End Sub End Class Public Class B Inherits A Public Overrides Property {|conflict:X|}({|declconflict:y|} As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> class B : A { public override int {|getaccessor:get_X|}(int y) { return base.{|getaccessorstmt:get_X|}(y); } public override void {|setaccessor:$$set_X|}(int y, int value) { base.{|setaccessorstmt:set_X|}(y, value); } } </Document> </Project> </Workspace>, renameTo:="y") result.AssertLabeledSpansAre("conflict", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("getaccessorstmt", "get_y", RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("setaccessorstmt", "set_y", RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansAre("declconflict", "y", RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpecialSpansAre("setaccessor", "set_y", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("getaccessor", "get_y", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(612380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/612380")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug612380_CrossLanguageOverrideImplicitPropertyAccessorCascadesToInterface() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Public Class A Public Overridable Property {|conflict:$$X|}({|declconflict:y|} As Integer) As Integer Get Return 0 End Get Set End Set End Property Public Shared Sub Main() End Sub End Class </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> class B : A { public override int {|getaccessor:get_X|}(int y) { return base.{|getaccessorstmt:get_X|}(y); } } interface I { int {|getaccessor:get_X|}(int y); } class C : B, I { public override int {|getaccessor:get_X|}(int y) { return base.{|getaccessor:get_X|}(y); } } </Document> </Project> </Workspace>, renameTo:="y") result.AssertLabeledSpansAre("conflict", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("declconflict", "y", RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpecialSpansAre("getaccessor", "get_y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("getaccessorstmt", "get_y", RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(866094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/866094")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug866094() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Public Module A Public Sub [|M|]() End Sub End Module </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> class C { static void N() { A.[|$$M|](); } } </Document> </Project> </Workspace>, renameTo:="X") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameDynamicallyBoundFunction() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document> Imports System class A { class B { public void [|Boo|](int d) { } } void Bar() { B b = new B(); dynamic d = 1.5f; b.{|Stmt1:$$Boo|}(d); } } </Document> </Project> </Workspace>, renameTo:="Bar") result.AssertLabeledSpansAre("Stmt1", "Bar", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(529989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529989")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CSharp_RenameToIdentifierWithUnicodeEscaping() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document> public class A { public static void [|$$Main|]() { A.{|stmt1:Main|}(); } } </Document> </Project> </Workspace>, renameTo:="M\u0061in") result.AssertLabeledSpansAre("stmt1", "M\u0061in", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(576966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576966")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CSharp_RenameParenthesizedMethodNames() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document> class C { void [|$$Foo|]() { (({|stmt1:Foo|}))(); } } </Document> </Project> </Workspace>, renameTo:="Bar") result.AssertLabeledSpansAre("stmt1", "Bar", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(632052, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632052")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub CSharp_RenameParameterUsedInObjectInitializer() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document> using System; class Program { void M(int [|$$p|]) { var v1 = new C() { tuple = Tuple.Create({|stmt1:p|}) }; Tuple&lt;int&gt; v2 = Tuple.Create({|stmt2:p|}); } } class C { public Tuple&lt;int&gt; tuple; } </Document> </Project> </Workspace>, renameTo:="n") result.AssertLabeledSpansAre("stmt1", "n", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "n", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(624092, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624092")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub LocationsIssue() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document> namespace N { public class D { } } </Document> </Project> <Project Language="Visual Basic" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> Namespace N Module M Public Class [|$$C|] 'Rename C to D End Class End Module End Namespace Module Program Sub Main(args As String()) Dim d = New N.D() Dim c = New N.{|resolved:C|}() End Sub End Module </Document> </Project> </Workspace>, renameTo:="D") result.AssertLabeledSpansAre("resolved", "Dim c = New N.M.D()", type:=RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameParam1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class Program { /// <summary> /// <paramref name="[|args|]" /> /// </summary> /// <param name="[|args|]"></param> static void Main(string[] [|$$args|]) { } }]]> </Document> </Project> </Workspace>, renameTo:="pargs") End Using End Sub <WorkItem(569103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569103")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameParam1_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class Program ''' <summary> ''' <paramref name="[|args|]" /> ''' </summary> ''' <param name="[|args|]"></param> Private Shared Sub Main([|$$args|] As String()) End Sub End Class]]> </Document> </Project> </Workspace>, renameTo:="pargs") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameParam2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class Program { /// <summary> /// <paramref name="{|ResolveWithoutAt:args|}" /> /// </summary> /// <param name="{|ResolveWithoutAt:$$args|}"></param> static void Main(string[] {|Resolve:args|}) { } } ]]> </Document> </Project> </Workspace>, renameTo:="if") result.AssertLabeledSpecialSpansAre("Resolve", "@if", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("ResolveWithoutAt", "if", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(569103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569103")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameParam2_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class Program ''' <summary> ''' <paramref name="{|Resolve:args|}" /> ''' </summary> ''' <param name="{|Resolve:$$args|}"></param> Private Shared Sub Main({|Resolve:args|} As String()) End Sub End Class]]> </Document> </Project> </Workspace>, renameTo:="[If]") result.AssertLabeledSpansAre("Resolve", <![CDATA[[If]]]>.Value, RelatedLocationType.NoConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameTypeParam1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ /// <summary> /// <typeparamref name="[|$$T|]"/> /// </summary> /// <typeparam name="[|T|]"></typeparam> class B<[|T|]> { /// <summary> /// <typeparamref name="[|T|]"/> /// </summary> /// <typeparam name="U"></typeparam> /// <typeparam name="P"></typeparam> /// <param name="x"></param> /// <param name="z"></param> [|T|] Foo<U, P>(U x, [|T|] z) { return z; } }]]> </Document> </Project> </Workspace>, renameTo:="D") End Using End Sub <WorkItem(569103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569103")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameTypeParam1_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ ''' <summary> ''' <typeparamref name="[|$$T|]"/> ''' </summary> ''' <typeparam name="[|T|]"></typeparam> Class B(Of [|T|]) ''' <summary> ''' <typeparamref name="[|T|]"/> ''' </summary> ''' <typeparam name="U"></typeparam> ''' <typeparam name="P"></typeparam> ''' <param name="x"></param> ''' <param name="z"></param> Private Function Foo(Of U, P)(x As U, z As [|T|]) As [|T|] Return z End Function End Class]]> </Document> </Project> </Workspace>, renameTo:="D") End Using End Sub <WorkItem(624310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624310")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug624310_VBCascadeLambdaParameterInFieldInitializer() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Option Strict On Module M Dim field As Object = If(True, Function({|fieldinit:$$y|} As String) {|fieldinit:y|}.ToUpper(), Function({|fieldinit:y|} As String) {|fieldinit:y|}.ToLower()) Sub Main() Dim local As Object = If(True, Function(x As String) x.ToUpper(), Function(x As String) x.ToLower()) End Sub End Module </Document> </Project> </Workspace>, renameTo:="z") result.AssertLabeledSpansAre("fieldinit", "z", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(624310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624310")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug624310_CSNoCascadeLambdaParameterInFieldInitializer() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ using System; class Program { public object O = true ? (Func<string, string>)((string {|fieldinit:$$x|}) => {return {|fieldinit:x|}.ToUpper(); }) : (Func<string, string>)((string x) => {return x.ToLower(); }); } ]]>] </Document> </Project> </Workspace>, renameTo:="z") result.AssertLabeledSpansAre("fieldinit", "z", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(633582, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633582")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug633582_CSDoNotAddParenthesesInExpansionForParenthesizedBinaryExpression() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ using System.Linq; class Program { void aaa() { var bbb = from x in new[] { 1, 2, 3 } where ((1 + x > 'a')) join {|stmt:$$ddd|} in new[] { 5, 2, 9, 4, } on 7 equals {|stmt:ddd|} + 5 into eee select eee; } } ]]>] </Document> </Project> </Workspace>, renameTo:="xxx") result.AssertLabeledSpansAre("stmt", "xxx", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(622086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/622086")> <Fact(Skip:="https://github.com/dotnet/roslyn/issues/9412")> <Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug622086_CSRenameExplicitInterfaceImplementation() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ namespace X { interface [|$$IFoo|] { void Clone(); } class Baz : [|IFoo|] { void [|IFoo|].Clone() { } } } ]]>] </Document> </Project> </Workspace>, renameTo:="IFooEx") End Using End Sub <WorkItem(8139, "https://github.com/dotnet/roslyn/issues/8139")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameExplicitInterfaceImplementationFromDifferentProject() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <ProjectReference>Project2</ProjectReference> <Document> class Program { static void Main(string[] args) { Test(new Class1()); } static void Test(IInterface i) { i.[|M|](); } } </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <Document> public class Class1 : IInterface { void IInterface.[|$$M|]() { } // Rename 'M' from here } public interface IInterface { void [|M|](); } </Document> </Project> </Workspace>, renameTo:="Foo") End Using End Sub <WorkItem(529803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529803")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingEventCascadesToCSUsingEventHandlerDelegate() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Public Interface IA Event [|$$X|]() ' Rename X to Y End Interface Class C Implements IA Public Event [|X|] As IA.{|handler:XEventHandler|} Implements IA.[|X|] End Class </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> using System; class Program : IA { event IA.{|handler:XEventHandler|} IA.[|X|] { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } } </Document> </Project> </Workspace>, renameTo:="Y") result.AssertLabeledSpecialSpansAre("handler", "YEventHandler", type:=RelatedLocationType.NoConflict) End Using End Sub <WorkItem(529803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529803")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingCompilerGeneratedDelegateTypeForEventCascadesBackToEvent_1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Public Interface IA Event [|X|]() ' Rename X to Y End Interface Class C Implements IA Dim A As IA.{|handler:XEventHandler|} Public Event [|$$X|] Implements IA.[|X|] End Class </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> using System; class Program : IA { event IA.{|handler:XEventHandler|} IA.[|X|] { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } } </Document> </Project> </Workspace>, renameTo:="Y") result.AssertLabeledSpecialSpansAre("handler", "YEventHandler", type:=RelatedLocationType.NoConflict) End Using End Sub <WorkItem(529803, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529803")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingCompilerGeneratedDelegateTypeForEventCascadesBackToEvent_2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Public Interface IA Event [|X|]() ' Rename X to Y End Interface Class C Implements IA Public Event [|X|] As IA.{|handler:XEventHandler|} Implements IA.[|X|] End Class </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> using System; class Program : IA { event IA.{|handler:$$XEventHandler|} IA.[|X|] { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } } </Document> </Project> </Workspace>, renameTo:="Y") result.AssertLabeledSpecialSpansAre("handler", "YEventHandler", type:=RelatedLocationType.NoConflict) End Using End Sub <WorkItem(655621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/655621")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingCompilerGeneratedDelegateTypeForEventCascadesBackToEvent_3() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Public Interface IA Event [|$$X|]() ' Rename X to Y End Interface </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> using System; class C { object x = new IA.{|handler:XEventHandler|}(() => { }); } </Document> </Project> </Workspace>, renameTo:="Y") result.AssertLabeledSpecialSpansAre("handler", "YEventHandler", type:=RelatedLocationType.NoConflict) End Using End Sub <WorkItem(655621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/655621")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingCompilerGeneratedDelegateTypeForEventCascadesBackToEvent_4() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Public Interface IA Event [|X|]() ' Rename X to Y End Interface </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> using System; class C { object x = new IA.{|handler:$$XEventHandler|}(() => { }); } </Document> </Project> </Workspace>, renameTo:="Y") result.AssertLabeledSpecialSpansAre("handler", "YEventHandler", type:=RelatedLocationType.NoConflict) End Using End Sub <WorkItem(655621, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/655621"), WorkItem(762094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/762094")> <WpfFact(Skip:="762094"), Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenamingCompilerGeneratedDelegateTypeForEventCascadesBackToEvent_5() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Public Interface IA Event [|X|]() ' Rename X to Y End Interface </Document> </Project> <Project Language="Visual Basic" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> Imports System Class C public x as new IA.{|handler:$$XEventHandler|}( Sub() Console.WriteLine() ) Class C </Document> </Project> </Workspace>, renameTo:="Y") result.AssertLabeledSpecialSpansAre("handler", "YEventHandler", type:=RelatedLocationType.NoConflict) End Using End Sub <WorkItem(627297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627297")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug622086_CSRenameVarNotSupported() Assert.ThrowsAny(Of ArgumentException)(Sub() Dim result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ using System; namespace X { class Baz { void M() { [|$$var|] x = new Int32(); } } } ]]>] </Document> </Project> </Workspace>, renameTo:="Int32") End Sub) End Sub <WorkItem(627297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627297")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug622086_CSRenameCustomTypeNamedVarSupported() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ using System; namespace X { class [|var|] {} class Baz { void M() { {|stmt:$$var|} x = new {|stmt:var|}();; } } } ]]>] </Document> </Project> </Workspace>, renameTo:="bar") result.AssertLabeledSpansAre("stmt", "bar", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(627297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627297")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug622086_CSRenameDynamicNotSupported() Assert.ThrowsAny(Of ArgumentException)(Sub() Dim result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ using System; namespace X { class Baz { void M() { [|$$dynamic|] x = new Int32(); } } } ]]>] </Document> </Project> </Workspace>, renameTo:="Int32") End Sub) End Sub <WorkItem(627297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627297")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug622086_CSRenameToVarSupported() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ class [|Program|] { static void Main(string[] args) { {|stmt:$$Program|} x = null; } } ]]>] </Document> </Project> </Workspace>, renameTo:="var") result.AssertLabeledSpansAre("stmt", "var", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(627297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627297")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug622086_CSRenameToVarSupportedButConflictsWithOtherVar() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ class [|Program|] { static void Main(string[] args) { {|stmt:$$Program|} x = null; {|conflict:var|} y = 23; } } ]]>] </Document> </Project> </Workspace>, renameTo:="var") result.AssertLabeledSpansAre("stmt", "var", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(627297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627297")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug622086_CSRenameToVarSupportedButDoesntConflictsWithOtherVarOfSameType() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ class [|Program|] { static void Main(string[] args) { {|stmt1:$$Program|} x = null; var y = new {|stmt2:Program|}(); } } ]]>] </Document> </Project> </Workspace>, renameTo:="var") result.AssertLabeledSpansAre("stmt1", "var", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "var", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(627297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627297")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug622086_CSRenameToDynamicSupported() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ class [|Program|] { static void Main(string[] args) { {|stmt:$$Program|} x = null; } } ]]>] </Document> </Project> </Workspace>, renameTo:="dynamic") result.AssertLabeledSpansAre("stmt", "dynamic", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(627297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627297")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug622086_CSRenameToDynamicSupportedButConflictsWithOtherDynamic_1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ class [|Program|] { static void Main(string[] args) { {|stmt:$$Program|} x = null; {|conflict:dynamic|} y = 23; } } ]]>] </Document> </Project> </Workspace>, renameTo:="dynamic") result.AssertLabeledSpansAre("stmt", "dynamic", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(627297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/627297")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub Bug622086_CSRenameToDynamicSupportedButConflictsWithOtherDynamic_2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ class [|Program|] { static void Main(string[] args) { {|stmt1:$$Program|} x = null; {|conflict:dynamic|} y = new {|stmt2:Program|}(); } } ]]>] </Document> </Project> </Workspace>, renameTo:="dynamic") result.AssertLabeledSpansAre("stmt1", "dynamic", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "dynamic", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(608988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608988")> <WorkItem(608989, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608989")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameNamespaceInVbFromCSharReference() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Namespace [|N|] Public Class X End Class End Namespace </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> class Y : [|$$N|].X { } </Document> </Project> </Workspace>, renameTo:="Foo") End Using End Sub #Region "Cref" <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameTypeFromCref() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document FilePath="Test.cs"> <![CDATA[ class [|Program|] { /// <see cref="[|$$Program|]"/> to start the program. static void Main(string[] args) { } } ]]> </Document> </Project> </Workspace>, renameTo:="y") End Using End Sub <WorkItem(569103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569103")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameTypeFromCref_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="VisualBasicAssembly" CommonReferences="true"> <Document> <![CDATA[ Class [|Program|] ''' <see cref="[|$$Program|]"/> to start the program. Private Shared Sub Main(args As String()) End Sub End Class ]]> </Document> </Project> </Workspace>, renameTo:="Y") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMemberFromCref() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document FilePath="Test.cs"> <![CDATA[ class Program { /// <see cref="Program.[|$$Main|]"/> to start the program. static void [|Main|](string[] args) { } } ]]> </Document> </Project> </Workspace>, renameTo:="y") End Using End Sub <WorkItem(569103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569103")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMemberFromCref_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="VisualBasicAssembly" CommonReferences="true"> <Document> <![CDATA[ Class Program ''' <see cref="Program.[|$$Main|]"/> to start the program. Private Shared Sub [|Main|](args As String()) End Sub End Class ]]> </Document> </Project> </Workspace>, renameTo:="Y") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCrefFromMember() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document FilePath="Test.cs"> <![CDATA[ class Program { /// <see cref="Program.[|Main|]"/> to start the program. static void [|$$Main|](string[] args) { } } ]]> </Document> </Project> </Workspace>, renameTo:="y") End Using End Sub <WorkItem(569103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569103")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCrefFromMember_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="VisualBasicAssembly" CommonReferences="true"> <Document> <![CDATA[ Class Program ''' <see cref="Program.[|Main|]"/> to start the program. Private Shared Sub [|$$Main|](args As String()) End Sub End Class ]]> </Document> </Project> </Workspace>, renameTo:="y") End Using End Sub <WorkItem(546952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546952")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameIncludingCrefContainingAttribute() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document FilePath="Test.cs"> <![CDATA[ using System; /// <summary> /// <see cref="{|yAttribute:FooAttribute|}" /> /// </summary> [{|y:Foo|}] class {|yAttribute:F$$ooAttribute|} : Attribute { } ]]> </Document> </Project> </Workspace>, renameTo:="yAttribute") result.AssertLabeledSpansAre("yAttribute", replacement:="yAttribute", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("y", replacement:="y", type:=RelatedLocationType.NoConflict) End Using End Sub <WorkItem(546952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546952")> <WorkItem(569103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569103")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameIncludingCrefContainingAttribute_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="VisualBasicAssembly" CommonReferences="true"> <Document> <![CDATA[ ''' <summary> ''' <see cref="{|YAttribute:$$FooAttribute|}" /> ''' </summary> <{|Y:Foo|}> Class {|YAttribute:FooAttribute|} Inherits Attribute End Class ]]> </Document> </Project> </Workspace>, renameTo:="YAttribute") result.AssertLabeledSpansAre("YAttribute", replacement:="YAttribute", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Y", replacement:="Y", type:=RelatedLocationType.NoConflict) End Using End Sub <WorkItem(546952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546952")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameFromCrefContainingAttribute() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document FilePath="Test.cs"> <![CDATA[ using System; /// <summary> /// <see cref="{|yAttribute:FooA$$ttribute|}" /> /// </summary> [{|y:Foo|}] class {|yAttribute:FooAttribute|} : Attribute { } ]]> </Document> </Project> </Workspace>, renameTo:="yAttribute") result.AssertLabeledSpansAre("yAttribute", replacement:="yAttribute", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("y", replacement:="y", type:=RelatedLocationType.NoConflict) End Using End Sub <WorkItem(546952, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546952"), WorkItem(569103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569103")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameFromCrefContainingAttribute_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="VisualBasicAssembly" CommonReferences="true"> <Document FilePath="Test.vb"> <![CDATA[ Imports System ''' <summary> ''' <see cref="{|yAttribute:FooA$$ttribute|}" /> ''' </summary> <{|y:Foo|}> Class {|yAttribute:FooAttribute|} : Inherits Attribute End Class ]]> </Document> </Project> </Workspace>, renameTo:="yAttribute") result.AssertLabeledSpansAre("yAttribute", replacement:="yAttribute", type:=RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("y", replacement:="y", type:=RelatedLocationType.NoConflict) End Using End Sub <WorkItem(531015, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531015")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCrefTypeParameter() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document FilePath="Test.cs"> <![CDATA[ /// <see cref="C{[|$$T|]}.M({|Conflict:T|})"/> class C<T> { } ]]></Document> </Project> </Workspace>, renameTo:="K") result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(640373, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/640373")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class Tester { private int {|Resolve:$$x|}; /// <summary> /// <see cref="Tester.{|Resolve:x|}"/> /// </summary> public int X { get { return {|Resolve:x|}; } set { {|Resolve:x|} = value; } } }]]> </Document> </Project> </Workspace>, renameTo:="if") result.AssertLabeledSpecialSpansAre("Resolve", "@if", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(640373, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/640373")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref1_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Imports System Class Tester Private {|Resolve1:$$_x|} As Integer ''' <summary> ''' <see cref="Tester.{|Resolve2:_x|}"/> ''' </summary> Public Property X As Integer Get Return {|Resolve1:_x|}; End Get Set {|Resolve1:_x|} = value; End Set End Property End Class]]> </Document> </Project> </Workspace>, renameTo:="If") result.AssertLabeledSpecialSpansAre("Resolve1", "[If]", RelatedLocationType.NoConflict) result.AssertLabeledSpecialSpansAre("Resolve2", "If", RelatedLocationType.NoConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class Tester { private int [|$$x|]; /// <summary> /// <see cref="[|x|]"/> /// </summary> public int X { get { return {|Stmt1:x|}; } set { {|Stmt2:x|} = value; } } }]]> </Document> </Project> </Workspace>, renameTo:="y") result.AssertLabeledSpansAre("Stmt1", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Stmt2", "y", RelatedLocationType.NoConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref2_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Imports System Class Tester Private [|$$_x|] As Integer ''' <summary> ''' <see cref="[|_x|]"/> ''' </summary> Public Property X As Integer Get Return {|Stmt1:_x|} End Get Set {|Stmt2:_x|} = value End Set End Property End Class]]> </Document> </Project> </Workspace>, renameTo:="y") result.AssertLabeledSpansAre("Stmt1", "y", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("Stmt2", "y", RelatedLocationType.NoConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref3() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C<[|$$T|]> { /// <summary> /// <see cref="C{T}"/> /// </summary> /// <param name="x"></param> void Foo(C<dynamic> x, C<string> y) { } }]]> </Document> </Project> </Workspace>, renameTo:="D") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref3_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class C(Of [|$$T|]) ''' <summary> ''' <see cref="C(Of [|T|])"/> ''' </summary> ''' <param name="x"></param> Sub Foo(x As C(Of Object), y As C(Of String)) End Sub End Class]]> </Document> </Project> </Workspace>, renameTo:="D") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref4() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C<T> { /// <summary> /// <see cref="C{[|$$T|]}"/> /// <see cref="C{T}.Bar(T)" /> /// </summary> /// <param name="x"></param> void Foo(C<dynamic> x, C<string> y) { } void Bar(T x) { } }]]> </Document> </Project> </Workspace>, renameTo:="D") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref4_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class C(Of [|T|]) ''' <summary> ''' <see cref="C(Of [|$$T|])"/> ''' <see cref="C(Of [|T|]).Bar(Of [|T|])" /> ''' </summary> ''' <param name="x"></param> Sub Foo(x As C(Of Object), y As C(Of String)) End Sub Sub Bar(x As [|T|]) End Sub End Class]]> </Document> </Project> </Workspace>, renameTo:="D") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref5() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class {|Resolve:C|}<T> { /// <summary> /// <see cref="{|Resolve:C|}{T}"/> /// </summary> /// <param name="x"></param> void Foo({|Resolve:$$C|}<dynamic> x, {|Resolve:C|}<string> y) { } }]]> </Document> </Project> </Workspace>, renameTo:="string") result.AssertLabeledSpecialSpansAre("Resolve", "@string", RelatedLocationType.NoConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref5_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class {|Resolve:C|}(Of T) ''' <summary> ''' <see cref="{|Resolve:C|}(Of T)"/> ''' </summary> ''' <param name="x"></param> Sub Foo(x As {|Resolve:$$C|}(Of Object), y As {|Resolve:C|}(Of String)) End Sub End Class]]> </Document> </Project> </Workspace>, renameTo:="String") result.AssertLabeledSpecialSpansAre("Resolve", "[String]", RelatedLocationType.NoConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref6() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ namespace Test { /// <summary> /// <seealso cref="global::[|$$C|]"/> /// </summary> class C { void Foo() { } } } class [|C|] { }]]> </Document> </Project> </Workspace>, renameTo:="D") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref6_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Namespace Test ''' <summary> ''' <seealso cref="Global.[|$$C|]"/> ''' </summary> Class C Sub Foo() End Sub End Class End Namespace Class [|C|] End Class]]> </Document> </Project> </Workspace>, renameTo:="D") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref7() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ namespace Test { /// <summary> /// <see cref="P"/> /// <see cref="P.[|K|]"/> /// </summary> public class C { /// <summary> /// <see cref="P"/> /// <see cref="[|K|]"/> /// </summary> public class P { /// <summary> /// <see cref="[|$$K|]"/> /// </summary> public class [|K|] { } } } /// <summary> /// <see cref="C.P.[|K|]"/> /// </summary> public class P { } }]]> </Document> </Project> </Workspace>, renameTo:="C") End Using End Sub <Fact(), Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref7_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Namespace Test ''' <summary> ''' <see cref="P"/> ''' <see cref="P.[|K|]"/> ''' </summary> Class C ''' <summary> ''' <see cref="P"/> ''' <see cref="[|K|]"/> ''' </summary> Class P ''' <summary> ''' <see cref="[|$$K|]"/> ''' </summary> Class [|K|] End Class End Class End Class ''' <summary> ''' <see cref="C.P.[|K|]"/> ''' </summary> Class P End Class End Namespace]]> </Document> </Project> </Workspace>, renameTo:="C") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref8() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ interface I { void [|Bar|](); } abstract class C { public abstract void [|Bar|](); } class B : C, I { /// <summary> /// <see cref="I.[|Bar|]()"/> /// <see cref="[|$$Bar|]()"/> /// <see cref="C.[|Bar|]()"/> /// </summary> public override void [|Bar|]() { throw new NotImplementedException(); } }]]> </Document> </Project> </Workspace>, renameTo:="Foo") End Using End Sub <Fact(), Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref8_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Interface I Sub [|Bar|] End Interface MustInherit Class C Public MustOverride Sub [|Bar|]() End Class Class B : Inherits C : Implements I ''' <summary> ''' <see cref="I.[|Bar|]()"/> ''' <see cref="[|$$Bar|]()"/> ''' <see cref="B.[|Bar|]()"/> ''' <see cref="C.[|Bar|]()"/> ''' </summary> Public Overrides Sub [|Bar|]() Implements I.[|Bar|] Throw new NotImplementedException() End Sub End Class]]> </Document> </Project> </Workspace>, renameTo:="Foo") End Using End Sub <WpfFact(Skip:="640502"), Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref9() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ interface I { void [|Foo|](); } abstract class C { public void [|Foo|]() { } } class B : C, I { /// <summary> /// <see cref="I.[|Foo|]()"/> /// <see cref="[|Foo|]()"/> /// <see cref="C.[|Foo|]()"/> /// </summary> public void Bar() { [|$$Foo|](); } }]]> </Document> </Project> </Workspace>, renameTo:="Baz") End Using End Sub <Fact(), Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref9_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Interface I Sub {|Interface:Foo|}() End Interface MustInherit Class C Public Sub [|Foo|]() End Sub End Class Class B : Inherits C : Implements I ''' <summary> ''' <see cref="I.{|Interface:Foo|}()"/> ''' <see cref="[|Foo|]()"/> ''' <see cref="C.[|Foo|]()"/> ''' </summary> Public Sub Bar() Implements I.Foo [|$$Foo|]() End Sub End Class]]> </Document> </Project> </Workspace>, renameTo:="Baz") result.AssertLabeledSpansAre("Interface", "Foo") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref10() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { delegate void [|$$Del|](int x); /// <summary> /// <see cref="[|Del|]"/> /// <see cref="B.Del" /> /// </summary> void Foo() { [|Del|] d; } class B { /// <summary> /// <see cref="C.[|Del|]"/> /// </summary> /// <param name="x"></param> delegate void Del(int x); } }]]> </Document> </Project> </Workspace>, renameTo:="Bel") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref10_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class C Delegate Sub [|$$Del|](x As Integer) ''' <summary> ''' <see cref="[|Del|]"/> ''' <see cref="B.Del" /> ''' </summary> Sub Foo() Dim d As [|Del|] End Sub Class B ''' <summary> ''' <see cref="C.[|Del|]"/> ''' </summary> ''' <param name="x"></param> Delegate Sub Del(x As Integer) End Class End Class]]> </Document> </Project> </Workspace>, renameTo:="Bel") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref11() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class Test { /// <summary> /// <see cref="[|P|]"/> /// </summary> /// <param name="x"></param> public delegate void Del(int x); public event Del [|P|]; void Sub() { [|$$P|](1); } }]]> </Document> </Project> </Workspace>, renameTo:="Bel") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref11_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class Test ''' <summary> ''' <see cref="[|P|]"/> ''' </summary> Public Event [|P|](x As Integer) Sub Subroutine() RaiseEvent [|$$P|](1) End Sub End Class]]> </Document> </Project> </Workspace>, renameTo:="Bel") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref12() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class Program { /// <summary> /// <see cref="{|resolve:Bar|}"></see> /// </summary> /// <param name="args"></param> static void Main(string[] args) { } static void [|$$Foo|]() { } } class Bar { }]]> </Document> </Project> </Workspace>, renameTo:="Bar") result.AssertLabeledSpansAre("resolve", "global::Bar", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref12_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program ''' <summary> ''' <see cref="{|resolve:Bar|}"></see> ''' </summary> ''' <param name="args"></param> Shared Sub Main(args As String()) End Sub Shared Sub [|$$Foo|]() End Sub End Class Class Bar End Class]]> </Document> </Project> </Workspace>, renameTo:="Bar") result.AssertLabeledSpansAre("resolve", "Global.Bar", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref13() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class Program { /// <summary> /// <see cref="{|resolve:Bar|}"></see> /// </summary> /// <param name="args"></param> static void Main(string[] args) { } public class [|$$Baz|] { } } public class Bar { }]]> </Document> </Project> </Workspace>, renameTo:="Bar") result.AssertLabeledSpansAre("resolve", "global::Bar", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref13_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Imports System Class Program ''' <summary> ''' <see cref="{|resolve:Bar|}"></see> ''' </summary> ''' <param name="args"></param> Shared Sub Main(args As String()) End Sub Public Class [|$$Baz|] End Class End Class Public Class Bar End Class]]> </Document> </Project> </Workspace>, renameTo:="Bar") result.AssertLabeledSpansAre("resolve", "Global.Bar", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref14() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ public class A { public class B { public class C { /// <summary> /// <see cref=" {|resolve:D|}"/> /// </summary> static void [|$$foo|]() { } } public class D { } } }]]> </Document> </Project> </Workspace>, renameTo:="D") result.AssertLabeledSpansAre("resolve", "B.D", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref14_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Public Class A Public Class B Public Class C ''' <summary> ''' <see cref="{|resolve:D|}"/> ''' </summary> Shared Sub [|$$foo|]() End Sub End Class Public Class D End Class End Class End Class]]> </Document> </Project> </Workspace>, renameTo:="D") result.AssertLabeledSpansAre("resolve", "B.D", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(673562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673562")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref15() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ namespace N { class C { /// <summary> /// <see cref="{|Resolve:N|}.C"/> /// </summary> void Sub() { } } namespace [|$$K|] // Rename K to N { class C { } } }]]> </Document> </Project> </Workspace>, renameTo:="N") result.AssertLabeledSpansAre("Resolve", "global::N", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(673562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673562")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref15_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Namespace N Class C ''' <summary> ''' <see cref="{|Resolve:N|}.C"/> ''' </summary> Sub Subroutine() End Sub End Class Namespace [|$$K|] ' Rename K to N Class C End Class End Namespace End Namespace]]> </Document> </Project> </Workspace>, renameTo:="N") result.AssertLabeledSpansAre("Resolve", "Global.N.C", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(673667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673667"), WorkItem(760850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760850")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref17() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System; class P { /// <summary> /// <see cref="[|b|]"/> /// </summary> Action<int> [|$$b|] = (int x) => { }; // Rename b to a class B { /// <summary> /// <see cref="{|Resolve:b|}"/> /// </summary> void a() { } } }]]> </Document> </Project> </Workspace>, renameTo:="a") result.AssertLabeledSpansAre("Resolve", "P.a", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <WorkItem(673667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673667"), WorkItem(760850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760850")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref17_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Imports System Class P ''' <summary> ''' <see cref="[|_b|]"/> ''' </summary> Private [|$$_b|] As Action(Of Integer) = Sub(x As Integer) End Sub ' Rename _b to a Class B ''' <summary> ''' <see cref="{|Resolve:_b|}"/> ''' </summary> Sub a() End Sub End Class End Class]]> </Document> </Project> </Workspace>, renameTo:="a") result.AssertLabeledSpansAre("Resolve", "P.a", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <WorkItem(673667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673667")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCref18() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ namespace N { using K = {|Resolve:N|}.C; class C { } /// <summary> /// <see cref="[|D|]"/> /// </summary> class [|$$D|] { class C { [|D|] x; } } }]]> </Document> </Project> </Workspace>, renameTo:="N") result.AssertLabeledSpansAre("Resolve", "global::N", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCrefWithUsing1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using R1 = N1.C1; namespace N1 { class C1 { public class C2 { } } namespace N2 { /// <summary> /// <see cref="{|Resolve:R1|}.C2"/> /// </summary> class [|$$K|] { class C2 { } } } }]]> </Document> </Project> </Workspace>, renameTo:="R1") result.AssertLabeledSpansAre("Resolve", "C1", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(569103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569103")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCrefWithUsing1_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Imports R1 = N1.C1 Namespace N1 Class C1 Public Class C2 End Class End Class Namespace N2 ''' <summary> ''' <see cref="{|Resolve:R1|}.C2"/> ''' </summary> Class [|$$K|] Private Class C2 End Class End Class End Namespace End Namespace ]]> </Document> </Project> </Workspace>, renameTo:="R1") result.AssertLabeledSpansAre("Resolve", "C1.C2", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCrefWithUsing2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using R1 = N1; namespace N1 { public class C1 { public class C2 { } } } namespace N2 { class N1 { class C2 { /// <summary> /// <see cref="{|Resolve:R1|}.C1.C2"/> /// </summary> class C3 { } class [|$$K|] { } } } }]]> </Document> </Project> </Workspace>, renameTo:="R1") result.AssertLabeledSpansAre("Resolve", "global::N1", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(767163, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/767163")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCrefWithUsing2_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Imports R1 = N1 Namespace N1 Public Class C1 Public Class C2 End Class End Class End Namespace Namespace N2 Class N1 Class C2 ''' <summary> ''' <see cref="{|Resolve:R1|}.C1.C2"/> ''' </summary> Class C3 End Class Class [|$$K|] End Class End Class End Class End Namespace ]]> </Document> </Project> </Workspace>, renameTo:="R1") result.AssertLabeledSpansAre("Resolve", "Global.N1.C1.C2", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCrefWithInterface() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ namespace N { interface [|I|] { void Foo(); } class C : [|I|] { /// <summary> /// <see cref="{|Resolve:$$I|}.Foo"/> /// </summary> public void Foo() { } class K { } } }]]> </Document> </Project> </Workspace>, renameTo:="K") result.AssertLabeledSpansAre("Resolve", "N.K", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <WorkItem(767163, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/767163")> <WorkItem(569103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/569103")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCrefWithInterface_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Namespace N Interface [|I|] Sub Foo() End Interface Class C : Implements {|Resolve1:I|} ''' <summary> ''' <see cref="{|Resolve2:$$I|}.Foo"/> ''' </summary> Public Sub Foo() Implements {|Resolve1:I|}.Foo End Sub Class K End Class End Class End Namespace]]> </Document> </Project> </Workspace>, renameTo:="K") result.AssertLabeledSpansAre("Resolve1", "N.K", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("Resolve2", "N.K.Foo", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCrefCrossAssembly() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <Document><![CDATA[ class D : [|N|].C { /// <summary> /// <see cref="{|Resolve:N|}.C.Foo"/> /// </summary> public void Sub() { Foo(); } class R { class C { public void Foo() { } } } }]]> </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBAssembly"> <Document> Namespace [|$$N|] Public Class C Public Sub Foo() End Sub End Class End Namespace </Document> </Project> </Workspace>, renameTo:="R") result.AssertLabeledSpansAre("Resolve", "global::R", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <WorkItem(767163, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/767163")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameCrefCrossAssembly_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>CSAssembly</ProjectReference> <Document><![CDATA[ Class D : Inherits {|Resolve1:N|}.C ''' <summary> ''' <see cref="{|Resolve2:N|}.C.Foo"/> ''' </summary> Public Sub Subroutine() Foo() End Sub Class R Class C Public Sub Foo() End Sub End Class End Class End Class]]> </Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly"> <Document><![CDATA[ namespace [|$$N|] { public class C { public void Foo() { } } }]]> </Document> </Project> </Workspace>, renameTo:="R") result.AssertLabeledSpansAre("Resolve1", "Global.R", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansAre("Resolve2", "Global.R.C.Foo", RelatedLocationType.ResolvedReferenceConflict) End Using End Sub <WorkItem(673809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673809")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameStaticConstructorInsideCref1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class [|P|] { /// <summary> /// <see cref="[|P|].[|P|]"/> /// </summary> static [|$$P|]() { } /// <summary> /// <see cref="[|P|].[|P|]"/> /// </summary> public [|P|]() { } }]]> </Document> </Project> </Workspace>, renameTo:="Q") End Using End Sub <WorkItem(673809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673809")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameStaticConstructorInsideCref1_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class [|$$P|] ''' <summary> ''' <see cref="[|P|].New()"/> ''' </summary> Shared Sub New() End Sub ''' <summary> ''' <see cref="[|P|].New()"/> ''' </summary> Public Sub New() End Sub End Class]]> </Document> </Project> </Workspace>, renameTo:="Q") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameStaticConstructorInsideCref2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class [|P|] { /// <summary> /// <see cref="[|P|].[|$$P|]"/> /// </summary> static [|P|]() { } /// <summary> /// <see cref="[|P|].[|P|]"/> /// </summary> public [|P|]() { } }]]> </Document> </Project> </Workspace>, renameTo:="Q") End Using End Sub <WorkItem(673809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673809")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameStaticConstructorInsideCref2_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class [|P|] ''' <summary> ''' <see cref="[|P|].New()"/> ''' </summary> Shared Sub New() End Sub ''' <summary> ''' <see cref="[|$$P|].New()"/> ''' </summary> Public Sub New() End Sub End Class]]> </Document> </Project> </Workspace>, renameTo:="Q") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInheritanceCref1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class P { public int y; } class Q : P { int [|$$x|]; /// <summary> /// <see cref="y"/> /// </summary> void Sub() { } }]]> </Document> </Project> </Workspace>, renameTo:="y") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInheritanceCref1_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Class P Public y As Integer End Class Class Q : Inherits P Private [|$$x|] As Integer ''' <summary> ''' <see cref="{|Resolve:y|}"/> ''' </summary> Sub Subroutine() End Sub End Class]]> </Document> </Project> </Workspace>, renameTo:="y") result.AssertLabeledSpansAre("Resolve", "P.y", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(673858, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673858"), WorkItem(666167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/666167")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameGenericTypeCrefWithConflict() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ namespace N { using K = C<int>; class C<T> { /// <summary> /// <see cref="C{T}"/> /// </summary> /// <typeparam name="T"></typeparam> class D<T> { /// <summary> /// <see cref="{|Resolve:K|}.D{int}"/> /// </summary> /// <typeparam name="P"></typeparam> class [|$$C|] // Rename C To K { class D<T> { } } class C<T> { } } } }]]> </Document> </Project> </Workspace>, renameTo:="K") result.AssertLabeledSpansAre("Resolve", "N.C{int}", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(673858, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673858"), WorkItem(666167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/666167"), WorkItem(768000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768000")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameGenericTypeCrefWithConflict_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Imports K = N.C(Of Integer) Namespace N Class C(Of T) ''' <summary> ''' <see cref="C(Of T)"/> ''' </summary> ''' <typeparam name="T"></typeparam> Class D(Of T) ''' <summary> ''' <see cref="{|Resolve:K|}.D(Of Integer)"/> ''' </summary> ''' <typeparam name="P"></typeparam> Class [|$$C|] ' Rename C To K Class D(Of T) End Class End Class Class C(Of T) End Class End Class End Class End Namespace]]> </Document> </Project> </Workspace>, renameTo:="K") result.AssertLabeledSpansAre("Resolve", "N.C(Of Integer).D(Of Integer)", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub #End Region <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameNestedNamespaceToParent1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ namespace N { namespace [|$$K|] { } }]]> </Document> </Project> </Workspace>, renameTo:="N") End Using End Sub <WorkItem(673641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673641")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameNestedNamespaceToParent2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ namespace N { class C { void Foo() { {|Resolve:N|}.C x; } } namespace [|$$K|] { class C { } } }]]> </Document> </Project> </Workspace>, renameTo:="N") result.AssertLabeledSpansAre("Resolve", "global::N.C x;", RelatedLocationType.ResolvedNonReferenceConflict) End Using End Sub <WorkItem(673809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673809")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameStaticConstructor() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class [|Simple|] { static [|$$Simple|]() // Rename simple here to p { } public [|Simple|]() { } } ]]> </Document> </Project> </Workspace>, renameTo:="P") End Using End Sub <WorkItem(675882, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/675882")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub SingleOnlyLocalDeclarationInsideLambdaRecurseInfinitely() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Module Lambdas Sub Main() End Sub Public l1 = Sub() Dim x = 1 End Sub Public L3 = Function([|x|] As Integer) [|$$x|] Mod 2 End Module ]]> </Document> </Project> </Workspace>, renameTo:="xx") End Using End Sub <WorkItem(641231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/641231")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameDontReplaceBaseConstructorToken_CSharp() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class [|A|] {} class B : [|A|] { public B() : base() { } } class Program { static void Main() { [|$$A|] a = new B(); } } ]]> </Document> </Project> </Workspace>, renameTo:="P") End Using End Sub <WorkItem(641231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/641231")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameDontReplaceBaseConstructorToken_VisualBasic() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document><![CDATA[ Module Program Sub Main(args As String()) Dim Asa As [|$$A|] = New B() End Sub End Module Class [|A|] End Class Class B Inherits [|A|] Public Sub New() MyBase.New() End Sub End Class ]]> </Document> </Project> </Workspace>, renameTo:="D") End Using End Sub <WorkItem(674762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674762")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMergedNamespaceAcrossProjects() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ Namespace [|$$N|] Public Class X End Class End Namespace ]]> </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> class Y : [|N|].X { } namespace [|N|] { } </Document> </Project> </Workspace>, renameTo:="D") End Using End Sub <WorkItem(674764, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674764")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMergedNamespaceAcrossProjects_1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ Namespace [|N|] Public Class X End Class End Namespace ]]> </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> class Y : [|$$N|].X { } namespace [|N|] { } </Document> </Project> </Workspace>, renameTo:="D") End Using End Sub <WorkItem(716278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716278")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMainWithoutAssertFailureVB() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub [|$$Main|](args As String()) End Sub End Module ]]> </Document> </Project> </Workspace>, renameTo:="D") End Using End Sub <WorkItem(716278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716278")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMainWithoutAssertFailureCSharp() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; class Program { static void [|$$Main|](string[] args) { } } </Document> </Project> </Workspace>, renameTo:="D") End Using End Sub <WorkItem(719062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/719062")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameEscapedIdentifierToUnescapedIdentifier() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim [|[dim]$$|] = 4 End Sub End Module ]]> </Document> </Project> </Workspace>, renameTo:="D") End Using End Sub <WorkItem(719062, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/719062")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameEscapedIdentifierToUnescapedIdentifierKeyword() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim {|iden1:[dim]$$|} = 4 End Sub End Module ]]> </Document> </Project> </Workspace>, renameTo:="do") result.AssertLabeledSpecialSpansAre("iden1", "[do]", RelatedLocationType.NoConflict) End Using End Sub <WorkItem(767187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/767187")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameEscapedTypeNew() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ Class [|[New]|] End Class Class C Public Sub F() Dim a = New [|$$[New]|] End Sub End Class ]]> </Document> </Project> </Workspace>, renameTo:="D") End Using End Sub <WorkItem(767187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/767187")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameConstructorInCref() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ /// <see cref="[|C|].[|$$C|]"> class [|C|] { public [|C|]() {} } ]]> </Document> </Project> </Workspace>, renameTo:="D") End Using End Sub <WorkItem(1009633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1009633")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameWithTryCatchBlock1() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ Class C Sub M() Dim [|$$msg|] = "hello" Try Catch Dim newMsg = [|msg|] End Try End Sub End Class ]]> </Document> </Project> </Workspace>, renameTo:="msg2") End Using End Sub <WorkItem(1009633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1009633")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameWithTryCatchBlock2() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ Class C Sub M() Dim [|$$msg|] = "hello" Try Catch ex As Exception Dim newMsg = [|msg|] End Try End Sub End Class ]]> </Document> </Project> </Workspace>, renameTo:="msg2") End Using End Sub #Region "Rename in strings/comments" <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInStrings() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, True) renamingOptions.Add(RenameOptions.RenameInComments, False) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ Module [|$$Program|] ''' <summary> ''' Program PROGRAM! Program! ''' </summary> ''' <param name="args"></param> Sub Main(args As String()) ' Program PROGRAM! Program! Dim renamed = {|RenameInString:"Program Program!"|} ' Program Dim notRenamed = "PROGRAM! Program1 ProgramProgram" End Sub End Module ]]> </Document> </Project> </Workspace>, renameTo:="NewProgram", changedOptionSet:=renamingOptions) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInString", """NewProgram NewProgram!""") End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInStrings_CSharp() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, True) renamingOptions.Add(RenameOptions.RenameInComments, False) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ public class [|$$Program|] { /// <summary> /// Program PROGRAM! Program! /// <Program></Program> /// </summary> public static void Main(string[] args) { // Program PROGRAM! Program! var renamed = {|RenameInString:"Program Program!"|}; var notRenamed = "PROGRAM! Program1 ProgramProgram"; } } ]]> </Document> </Project> </Workspace>, renameTo:="NewProgram", changedOptionSet:=renamingOptions) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInString", """NewProgram NewProgram!""") End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInComments() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, False) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ Module [|$$Program|] ''' <summary> '''{|RenameInComment1: Program PROGRAM! Program!|} ''' </summary> ''' <param name="args"></param> Sub Main(args As String()) {|RenameInComment2:' Program PROGRAM! Program!|} Dim renamed = "Program Program!" {|RenameInComment3:' Program|} Dim notRenamed = "PROGRAM! Program1 ProgramProgram" End Sub End Module ]]> </Document> </Project> </Workspace>, renameTo:="NewProgram", changedOptionSet:=renamingOptions) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment1", " NewProgram PROGRAM! NewProgram!") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment2", "' NewProgram PROGRAM! NewProgram!") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment3", "' NewProgram") End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInComments_CSharp() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, False) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ public class [|$$Program|] { /// <summary> ///{|RenameInComment1: Program PROGRAM! Program!|} /// </summary> public static void Main(string[] args) { {|RenameInComment2:// Program PROGRAM! Program!|} var renamed = "Program Program!"; var notRenamed = "PROGRAM! Program1 ProgramProgram"; } } ]]> </Document> </Project> </Workspace>, renameTo:="NewProgram", changedOptionSet:=renamingOptions) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment1", " NewProgram PROGRAM! NewProgram!") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment2", "// NewProgram PROGRAM! NewProgram!") End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInComments_XmlName() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, False) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ ''' <summary> ''' <{|RenameInComment:Program|}> </{|RenameInComment:Program|}> ''' </summary> Public Class [|$$Program|] End Class ]]> </Document> </Project> </Workspace>, renameTo:="NewProgram", changedOptionSet:=renamingOptions) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment", "NewProgram") End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInComments_XmlName2() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, False) renamingOptions.Add(RenameOptions.RenameInComments, False) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ ' Should not rename XmlName if not renaming in comments ''' <summary> ''' <Program> </Program> ''' </summary> Public Class [|$$Program|] End Class ]]> </Document> </Project> </Workspace>, renameTo:="NewProgram", changedOptionSet:=renamingOptions) Assert.Equal(1, result.ConflictResolution.RelatedLocations.Count) End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInComments_XmlName_CSharp() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, False) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ /// <summary> /// <{|RenameInComment:Program|}> </{|RenameInComment:Program|}> /// </summary> public class [|$$Program|] { } ]]> </Document> </Project> </Workspace>, renameTo:="NewProgram", changedOptionSet:=renamingOptions) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment", "NewProgram") End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInComments_XmlName_CSharp2() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, False) renamingOptions.Add(RenameOptions.RenameInComments, False) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ // Should not rename XmlName if not renaming in comments /// <summary> /// <Program> </Program> /// </summary> public class [|$$Program|] { } ]]> </Document> </Project> </Workspace>, renameTo:="NewProgram", changedOptionSet:=renamingOptions) Assert.Equal(1, result.ConflictResolution.RelatedLocations.Count) End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInStringsAndComments() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, True) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ Module [|$$Program|] ''' <summary> '''{|RenameInComment1: Program PROGRAM! Program!|} ''' </summary> ''' <param name="args"></param> Sub Main(args As String()) {|RenameInComment2:' Program PROGRAM! Program!|} {|RenameInComment2:' Program PROGRAM! Program!|} Dim renamed = {|RenameInString:"Program Program!"|} {|RenameInComment3:' Program|} Dim notRenamed = "PROGRAM! Program1 ProgramProgram" End Sub End Module ]]> </Document> </Project> </Workspace>, renameTo:="NewProgram", changedOptionSet:=renamingOptions) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInString", """NewProgram NewProgram!""") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment1", " NewProgram PROGRAM! NewProgram!") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment2", "' NewProgram PROGRAM! NewProgram!") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment3", "' NewProgram") End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInStringsAndComments_CSharp() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, True) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ public class [|$$Program|] { /// <summary> ///{|RenameInComment1: Program PROGRAM! Program!|} /// </summary> public static void Main(string[] args) { {|RenameInComment2:// Program PROGRAM! Program!|} var renamed = {|RenameInString:"Program Program!"|}; var notRenamed = "PROGRAM! Program1 ProgramProgram"; } } ]]> </Document> </Project> </Workspace>, renameTo:="NewProgram", changedOptionSet:=renamingOptions) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInString", """NewProgram NewProgram!""") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment1", " NewProgram PROGRAM! NewProgram!") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment2", "// NewProgram PROGRAM! NewProgram!") End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInStringsAndComments_SmallerReplacementString() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, True) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ Module [|$$Program|] ''' <summary> '''{|RenameInComment1: Program PROGRAM! Program!|} ''' </summary> ''' <param name="args"></param> Sub Main(args As String()) {|RenameInComment2:' Program PROGRAM! Program!|} Dim renamed = {|RenameInString:"Program Program!"|} {|RenameInComment3:' Program|} Dim notRenamed = "PROGRAM! Program1 ProgramProgram" End Sub End Module ]]> </Document> </Project> </Workspace>, renameTo:="P", changedOptionSet:=renamingOptions) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInString", """P P!""") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment1", " P PROGRAM! P!") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment2", "' P PROGRAM! P!") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment3", "' P") End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInStringsAndComments_SmallerReplacementString_CSharp() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, True) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ public class [|$$Program|] { /// <summary> ///{|RenameInComment1: Program PROGRAM! Program!|} /// </summary> public static void Main(string[] args) { {|RenameInComment2:// Program PROGRAM! Program!|} var renamed = {|RenameInString:"Program Program!"|}; var notRenamed = "PROGRAM! Program1 ProgramProgram"; } } ]]> </Document> </Project> </Workspace>, renameTo:="P", changedOptionSet:=renamingOptions) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInString", """P P!""") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment1", " P PROGRAM! P!") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment2", "// P PROGRAM! P!") End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInStringsAndComments_AnotherSourceFile() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, True) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ Module [|$$Program|] End Module ]]> </Document> <Document><![CDATA[ Class AnotherFile ''' <summary> '''{|RenameInComment1: Program PROGRAM! Program!|} ''' </summary> ''' <param name="args"></param> Sub Main(args As String()) {|RenameInComment2:' Program PROGRAM! Program!|} Dim renamed = {|RenameInString:"Program Program!"|} {|RenameInComment3:' Program|} Dim notRenamed = "PROGRAM! Program1 ProgramProgram" End Sub End Class ]]> </Document> </Project> </Workspace>, renameTo:="P", changedOptionSet:=renamingOptions) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInString", """P P!""") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment1", " P PROGRAM! P!") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment2", "' P PROGRAM! P!") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment3", "' P") End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInStringsAndComments_AnotherSourceFile_CSharp() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, True) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ public class [|$$Program|] { } ]]> </Document> <Document><![CDATA[ public class AnotherFile { /// <summary> ///{|RenameInComment1: Program PROGRAM! Program!|} /// </summary> public static void Main(string[] args) { {|RenameInComment2:// Program PROGRAM! Program!|} var renamed = {|RenameInString:"Program Program!"|}; var notRenamed = "PROGRAM! Program1 ProgramProgram"; } } ]]> </Document> </Project> </Workspace>, renameTo:="NewProgram", changedOptionSet:=renamingOptions) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInString", """NewProgram NewProgram!""") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment1", " NewProgram PROGRAM! NewProgram!") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment2", "// NewProgram PROGRAM! NewProgram!") End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInStringsAndComments_AnotherProject() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, True) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ Public Class [|$$Program|] End Class ]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document><![CDATA[ ' Renames should occur in referencing projects where rename symbol is accessible. Class ReferencingProject ''' <summary> '''{|RenameInComment1: Program PROGRAM! Program!|} ''' </summary> ''' <param name="args"></param> Sub Main(args As String()) {|RenameInComment2:' Program PROGRAM! Program!|} {|RenameInComment2:' Program PROGRAM! Program!|} Dim renamed = {|RenameInString:"Program Program!"|} {|RenameInComment3:' Program|} Dim notRenamed = "PROGRAM! Program1 ProgramProgram" End Sub End Class ]]> </Document> </Project> </Workspace>, renameTo:="NewProgram", changedOptionSet:=renamingOptions) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInString", """NewProgram NewProgram!""") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment1", " NewProgram PROGRAM! NewProgram!") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment2", "' NewProgram PROGRAM! NewProgram!") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment3", "' NewProgram") End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInStringsAndComments_AnotherProject_CSharp() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, True) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ public class [|$$Program|] { } ]]> </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document><![CDATA[ // Renames should occur in referencing projects where rename symbol is accessible. public class AnotherFile { /// <summary> ///{|RenameInComment1: Program PROGRAM! Program!|} /// </summary> public static void Main(string[] args) { {|RenameInComment2:// Program PROGRAM! Program!|} var renamed = {|RenameInString:"Program Program!"|}; var notRenamed = "PROGRAM! Program1 ProgramProgram"; } } ]]> </Document> </Project> </Workspace>, renameTo:="NewProgram", changedOptionSet:=renamingOptions) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInString", """NewProgram NewProgram!""") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment1", " NewProgram PROGRAM! NewProgram!") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment2", "// NewProgram PROGRAM! NewProgram!") End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInStringsAndComments_AnotherProject2() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, True) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ Namespace N Private Class [|$$Program|] End Class End Namespace ]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="ReferencingProjectButSymbolNotVisible" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document><![CDATA[ ' Renames should not occur in referencing projects where rename symbol is not accessible. ' Type "Program" is not accessible in this project Imports N Class ReferencingProjectButSymbolNotVisible ''' <summary> ''' Program PROGRAM! Program! ''' </summary> ''' <param name="args"></param> Sub Main(args As String()) ' Program PROGRAM! Program! ' Program PROGRAM! Program! Dim renamed = "Program Program!" ' Program Dim notRenamed = "PROGRAM! Program1 ProgramProgram" End Sub End Class ]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="NotReferencingProject" CommonReferences="true"> <Document><![CDATA[ ' Renames should not occur in non-referencing projects. ' Type "Program" is not visible in this project Imports N Class NotReferencingProject ''' <summary> ''' Program PROGRAM! Program! ''' </summary> ''' <param name="args"></param> Sub Main(args As String()) ' Program PROGRAM! Program! ' Program PROGRAM! Program! Dim renamed = "Program Program!" ' Program Dim notRenamed = "PROGRAM! Program1 ProgramProgram" End Sub End Class ]]> </Document> </Project> </Workspace>, renameTo:="NewProgram", changedOptionSet:=renamingOptions) Assert.Equal(1, result.ConflictResolution.RelatedLocations.Count) End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInStringsAndComments_AnotherProject_CSharp2() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, True) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ namespace N { private class [|$$Program|] { } } ]]> </Document> </Project> <Project Language="C#" AssemblyName="ReferencingProjectButSymbolNotVisible" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document><![CDATA[ // Renames should not occur in referencing projects where rename symbol is not accessible. // Type "Program" is not accessible in this project using N; public class ReferencingProjectButSymbolNotVisible { /// <summary> /// Program PROGRAM! Program! /// </summary> public static void Main(string[] args) { // Program PROGRAM! Program! var renamed = "Program Program!"; var notRenamed = "PROGRAM! Program1 ProgramProgram"; } } ]]> </Document> </Project> <Project Language="C#" AssemblyName="NotReferencingProject" CommonReferences="true"> <Document><![CDATA[ // Renames should not occur in non-referencing projects. // Type "Program" is not visible in this project public class NotReferencingProject { /// <summary> /// Program PROGRAM! Program! /// </summary> public static void Main(string[] args) { // Program PROGRAM! Program! var renamed = "Program Program!"; var notRenamed = "PROGRAM! Program1 ProgramProgram"; } } ]]> </Document> </Project> </Workspace>, renameTo:="NewProgram", changedOptionSet:=renamingOptions) Assert.Equal(1, result.ConflictResolution.RelatedLocations.Count) End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInStringsAndComments_WithResolvableConflict() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, True) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ Module M Public Sub [|$$Foo|](Of T)(ByVal x As T) {|RenameInComment1:' Rename Foo to Bar|} End Sub End Module Class C Public Sub Bar(ByVal x As String) End Sub Class M Public Shared Bar As Action(Of String) = Sub(ByVal x As String) End Sub End Class Public Sub Test() {|stmt1:Foo|}("1") {|RenameInComment2:' Foo FOO! Foo!|} Dim renamed = {|RenameInString:"Foo Foo!"|} {|RenameInComment3:' Foo|} Dim notRenamed = "FOO! Foo1 FooFoo" End Sub End Class ]]> </Document> </Project> </Workspace>, renameTo:="Bar", changedOptionSet:=renamingOptions) result.AssertLabeledSpansAre("stmt1", "Call Global.M.Bar(""1"")", RelatedLocationType.ResolvedReferenceConflict) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment1", "' Rename Bar to Bar") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInString", """Bar Bar!""") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment2", "' Bar FOO! Bar!") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment3", "' Bar") End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInStringsAndComments_WithResolvableConflict_CSharp() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, True) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ class Foo { int foo; void Blah(int [|$$bar|]) { {|stmt2:foo|} = {|stmt1:bar|}; {|RenameInComment:// bar BAR! bar!|} var renamed = {|RenameInString:"bar bar!"|}; var notRenamed = "BAR! bar1 barbar"; } } End Sub End Class ]]> </Document> </Project> </Workspace>, renameTo:="foo", changedOptionSet:=renamingOptions) result.AssertLabeledSpansAre("stmt1", "this.foo = foo;", RelatedLocationType.NoConflict) result.AssertLabeledSpansAre("stmt2", "this.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInString", """foo foo!""") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment", "// foo BAR! foo!") End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInStringsAndComments_WithUnresolvableConflict() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, True) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ Option Explicit Off Module Program Function [|$$Foo|] {|Conflict:Bar|} = 1 {|RenameInComment1:' Foo FOO! Foo!|} Dim renamed = {|RenameInString:"Foo Foo!"|} {|RenameInComment2:' Foo|} Dim notRenamed = "FOO! Foo1 FooFoo" End Function End Module ]]> </Document> </Project> </Workspace>, renameTo:="Bar", changedOptionSet:=renamingOptions) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInString", """Bar Bar!""") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment1", "' Bar FOO! Bar!") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment2", "' Bar") End Using End Sub <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925")> <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameInStringsAndComments_WithUnresolvableConflict_CSharp() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameInStrings, True) renamingOptions.Add(RenameOptions.RenameInComments, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ class {|Conflict:foo|} { int [|$$bar|]; {|RenameInComment:// bar BAR! bar!|} var renamed = {|RenameInString:"bar bar!"|}; var notRenamed = "BAR! bar1 barbar"; } ]]> </Document> </Project> </Workspace>, renameTo:="foo", changedOptionSet:=renamingOptions) result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict) result.AssertLabeledSpansInStringsAndCommentsAre("RenameInString", """foo foo!""") result.AssertLabeledSpansInStringsAndCommentsAre("RenameInComment", "// foo BAR! foo!") End Using End Sub #End Region #Region "Rename In NameOf" <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMethodWithNameof_NoOverloads_CSharp() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ class C { void [|$$M|]() { nameof([|M|]).ToString(); } } ]]> </Document> </Project> </Workspace>, renameTo:="Mo") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMethodWithNameof_WithOverloads_CSharp() Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ class C { void [|$$M|]() { nameof(M).ToString(); } void M(int x) { } } ]]> </Document> </Project> </Workspace>, renameTo:="Mo") End Using End Sub <Fact, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMethodWithNameof_WithOverloads_WithRenameOverloadsOption_CSharp() Dim renamingOptions = New Dictionary(Of OptionKey, Object)() renamingOptions.Add(RenameOptions.RenameOverloads, True) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" AssemblyName="Project1" CommonReferences="true"> <Document><![CDATA[ class C { void [|$$M|]() { nameof([|M|]).ToString(); } void [|M|](int x) { } } ]]> </Document> </Project> </Workspace>, renameTo:="Mo", changedOptionSet:=renamingOptions) End Using End Sub #End Region End Class End Namespace
{ "content_hash": "a557bcf697436be77317a2e964975942", "timestamp": "", "source": "github", "line_count": 6820, "max_line_length": 254, "avg_line_length": 36.906451612903226, "alnum_prop": 0.49550659112760326, "repo_name": "ValentinRueda/roslyn", "id": "8a19f3cab05cdd1cf9d831bc5a5ad39c025e0cac", "size": "251708", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/EditorFeatures/Test2/Rename/RenameEngineTests.vb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "18341" }, { "name": "C#", "bytes": "76556567" }, { "name": "C++", "bytes": "6311" }, { "name": "F#", "bytes": "421" }, { "name": "Groovy", "bytes": "7799" }, { "name": "Makefile", "bytes": "2796" }, { "name": "PowerShell", "bytes": "16967" }, { "name": "Shell", "bytes": "6600" }, { "name": "Visual Basic", "bytes": "60820087" } ], "symlink_target": "" }
<?php namespace Pushman\Http\Middleware; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier; class VerifyCsrfToken extends BaseVerifier { protected $except = [ 'sites/*/channels/*/max', 'api/*', 'ban/update', ]; }
{ "content_hash": "7ba86f5f038879a8e4b0b9e2f269bfb8", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 74, "avg_line_length": 19.428571428571427, "alnum_prop": 0.6654411764705882, "repo_name": "PushmanPHP/pushman", "id": "0cb416020fca28d94ed4c15f676965474b345646", "size": "272", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/Http/Middleware/VerifyCsrfToken.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "356" }, { "name": "CSS", "bytes": "60699" }, { "name": "HTML", "bytes": "3162" }, { "name": "JavaScript", "bytes": "2331" }, { "name": "PHP", "bytes": "195823" }, { "name": "Ruby", "bytes": "61390" }, { "name": "Shell", "bytes": "286" } ], "symlink_target": "" }
""" WSGI config for scotland_yard project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "scotland_yard.settings") application = get_wsgi_application()
{ "content_hash": "ce559c80283adafe046a348b80781cbd", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 78, "avg_line_length": 25.1875, "alnum_prop": 0.771712158808933, "repo_name": "BoardFellows/ScotlandYard", "id": "7078e35a3fe3a90ccb5cf670eda76f9cb206ecdd", "size": "403", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "scotland_yard/scotland_yard/wsgi.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "81737" } ], "symlink_target": "" }
package dagger.internal.codegen.compileroption; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; /** A collection of options that dictate how the compiler will run. */ public abstract class CompilerOptions { public abstract boolean usesProducers(); /** * Returns true if the fast initialization flag, {@code fastInit}, is enabled. * * <p>If enabled, the generated code will attempt to optimize for fast component initialization. * This is done by reducing the number of factory classes loaded during initialization and the * number of eagerly initialized fields at the cost of potential memory leaks and higher * per-provision instantiation time. */ public abstract boolean fastInit(TypeElement element); public abstract boolean formatGeneratedSource(); public abstract boolean writeProducerNameInToken(); public abstract Diagnostic.Kind nullableValidationKind(); public final boolean doCheckForNulls() { return nullableValidationKind().equals(Diagnostic.Kind.ERROR); } public abstract Diagnostic.Kind privateMemberValidationKind(); public abstract Diagnostic.Kind staticMemberValidationKind(); /** * If {@code true}, Dagger will generate factories and components even if some members-injected * types have {@code private} or {@code static} {@code @Inject}-annotated members. * * <p>This should only ever be enabled by the TCK tests. Disabling this validation could lead to * generating code that does not compile. */ public abstract boolean ignorePrivateAndStaticInjectionForComponent(); public abstract ValidationType scopeCycleValidationType(); /** * If {@code true}, Dagger will validate all transitive component dependencies of a component. * Otherwise, Dagger will only validate the direct component dependencies. * * <p>Note: this is different from scopeCycleValidationType, which lets you silence errors of * transitive component dependencies, but still requires the full transitive dependencies in the * classpath. * * <p>The main motivation for this flag is to prevent requiring the transitive component * dependencies in the classpath to speed up builds. See * https://github.com/google/dagger/issues/970. */ public abstract boolean validateTransitiveComponentDependencies(); public abstract boolean warnIfInjectionFactoryNotGeneratedUpstream(); public abstract boolean headerCompilation(); public abstract ValidationType fullBindingGraphValidationType(); /** * If {@code true}, each plugin will visit the full binding graph for the given element. * * @throws IllegalArgumentException if {@code element} is not a module or (sub)component */ public abstract boolean pluginsVisitFullBindingGraphs(TypeElement element); public abstract Diagnostic.Kind moduleHasDifferentScopesDiagnosticKind(); public abstract ValidationType explicitBindingConflictsWithInjectValidationType(); public abstract boolean experimentalDaggerErrorMessages(); /** Returns the number of bindings allowed per shard. */ public int keysPerComponentShard(TypeElement component) { return 3500; } /** * This option enables a fix to an issue where Dagger previously would erroneously allow * multibinding contributions in a component to have dependencies on child components. This will * eventually become the default and enforced. */ public abstract boolean strictMultibindingValidation(); }
{ "content_hash": "6c2b8b08d30c563ce585a5dac3cec2d8", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 98, "avg_line_length": 38.23076923076923, "alnum_prop": 0.7703363035354988, "repo_name": "dushmis/dagger", "id": "a0d1cda347fde7b225561dcb13a5b6750bc35d9c", "size": "4081", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "java/dagger/internal/codegen/compileroption/CompilerOptions.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1289133" }, { "name": "Shell", "bytes": "2962" } ], "symlink_target": "" }
import { Helper, Types } from "gd-sprest"; import { Component } from "react"; import { IAttachmentFile } from "../../fields/types"; /** * Field Information */ export interface IItemFormField { /** The form control mode. */ controlMode?: number; /** The field name. */ name: string; /** The on change event */ onChange?: (value: any) => void; /** The on render method */ onRender?: (fieldInfo: Helper.IListFormFieldInfo) => JSX.Element; } /** * Item Form */ export class ItemForm extends Component<IItemFormProps, IItemFormState> { } /** * Properties */ export interface IItemFormProps { /** The class name to apply to the item form element. */ className?: string; /** The form control mode. */ controlMode?: number; /** The form fields to exclude from the form. */ excludeFields?: Array<string>; /** The field class name to apply to the field elements. */ fieldClassName?: string; /** The form fields. */ fields?: Array<IItemFormField>; /** The existing item. */ item?: any; /** The item id */ itemId?: number; /** The list display name. */ listName: string; /** The attachment added event. */ onAttachmentAdded?: (file: IAttachmentFile) => void; /** The click event for the attachment. */ onAttachmentClick?: (file: IAttachmentFile, controlMode: number) => void; /** The render event for the attachment. */ onAttachmentRender?: (file: IAttachmentFile, controlMode: number) => any; /** The field render event */ onFieldRender?: (fieldInfo: Helper.IListFormFieldInfo, field: JSX.Element) => any; /** The on form render event. */ onRender?: (controlMode: number) => any; /** The on form render attachments event. */ onRenderAttachments?: (files: Array<IAttachmentFile>, controlMode: number) => any; /** The item query, used when refreshing the item after a save. */ query?: Types.IODataQuery; /** The max number of items to return for the lookup data queries. (Default: 500) */ queryTop?: number; /** The form fields to make read-only in the form. */ readOnlyFields?: Array<string>; /** Flag to display the attachments. */ showAttachments?: boolean; /** The relative web url containing the list. */ webUrl?: string; } /** * State */ export interface IItemFormState { /** The form information */ formInfo?: Helper.IListFormResult; /** The item id. */ itemId?: number; /** The form fields. */ fields?: Array<IItemFormField>; /** The refresh flag. */ refreshFl?: boolean; /** The save flag. */ saveFl?: boolean; /** The update flag. */ updateFl?: boolean; }
{ "content_hash": "416a19ac3380b0b76965cc64337b74ae", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 88, "avg_line_length": 24.745454545454546, "alnum_prop": 0.6274797942689199, "repo_name": "gunjandatta/sprest-react", "id": "3aafd2a3b1e369dfd20de412eed23dab6aab1db1", "size": "2722", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/types/itemForm.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "196" }, { "name": "JavaScript", "bytes": "2245" }, { "name": "SCSS", "bytes": "683" }, { "name": "TypeScript", "bytes": "167320" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for node.js v5.2.0 - v5.3.0: Class Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v5.2.0 - v5.3.0 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li class="current"><a href="functions.html"><span>All</span></a></li> <li><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> <li><a href="functions_type.html"><span>Typedefs</span></a></li> <li><a href="functions_enum.html"><span>Enumerations</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li><a href="functions.html#index_a"><span>a</span></a></li> <li><a href="functions_b.html#index_b"><span>b</span></a></li> <li><a href="functions_c.html#index_c"><span>c</span></a></li> <li><a href="functions_d.html#index_d"><span>d</span></a></li> <li><a href="functions_e.html#index_e"><span>e</span></a></li> <li><a href="functions_f.html#index_f"><span>f</span></a></li> <li><a href="functions_g.html#index_g"><span>g</span></a></li> <li><a href="functions_h.html#index_h"><span>h</span></a></li> <li><a href="functions_i.html#index_i"><span>i</span></a></li> <li><a href="functions_j.html#index_j"><span>j</span></a></li> <li class="current"><a href="functions_k.html#index_k"><span>k</span></a></li> <li><a href="functions_l.html#index_l"><span>l</span></a></li> <li><a href="functions_m.html#index_m"><span>m</span></a></li> <li><a href="functions_n.html#index_n"><span>n</span></a></li> <li><a href="functions_o.html#index_o"><span>o</span></a></li> <li><a href="functions_p.html#index_p"><span>p</span></a></li> <li><a href="functions_r.html#index_r"><span>r</span></a></li> <li><a href="functions_s.html#index_s"><span>s</span></a></li> <li><a href="functions_t.html#index_t"><span>t</span></a></li> <li><a href="functions_u.html#index_u"><span>u</span></a></li> <li><a href="functions_v.html#index_v"><span>v</span></a></li> <li><a href="functions_w.html#index_w"><span>w</span></a></li> <li><a href="functions_~.html#index_~"><span>~</span></a></li> </ul> </div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">Here is a list of all documented class members with links to the class documentation for each member:</div> <h3><a class="anchor" id="index_k"></a>- k -</h3><ul> <li>kPersistentHandleNoClassId : <a class="el" href="classv8_1_1HeapProfiler.html#a272c9af3ea5cd90a2737af3d22a7eb78">v8::HeapProfiler</a> </li> <li>kUnknownObjectId : <a class="el" href="classv8_1_1HeapProfiler.html#abf2b9d8facb18473f9b124ab8baf5786">v8::HeapProfiler</a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{ "content_hash": "6a94e0b7c07241d3aeedcd7676b2bac1", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 154, "avg_line_length": 45.93617021276596, "alnum_prop": 0.6237455612166126, "repo_name": "v8-dox/v8-dox.github.io", "id": "c8418cde3f8d5ff981c7b30559700af567971160", "size": "6477", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "99fd1ec/html/functions_k.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php namespace JHWEB\ParqueaderoBundle\Controller; use JHWEB\ParqueaderoBundle\Entity\PqoGruaCiudadano; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;use Symfony\Component\HttpFoundation\Request; /** * Pqogruaciudadano controller. * * @Route("pqogruaciudadano") */ class PqoGruaCiudadanoController extends Controller { /** * Lists all pqoGruaCiudadano entities. * * @Route("/index", name="pqogruaciudadano_index") * @Method({"GET", "POST"}) */ public function indexAction(Request $request) { $helpers = $this->get("app.helpers"); $json = $request->get("data",null); $params = json_decode($json); $em = $this->getDoctrine()->getManager(); $gruaCiudadanos = $em->getRepository('JHWEBParqueaderoBundle:PqoGruaCiudadano')->findByGrua( $params->idGrua ); $response['data'] = array(); if ($gruaCiudadanos) { $response = array( 'status' => 'success', 'code' => 200, 'message' => count($gruaCiudadanos)." Registros encontrados", 'data'=> $gruaCiudadanos, ); } return $helpers->json($response); } /** * Creates a new pqoGruaCiudadano entity. * * @Route("/new", name="pqogruaciudadano_new") * @Method({"GET", "POST"}) */ public function newAction(Request $request) { $helpers = $this->get("app.helpers"); $hash = $request->get("authorization", null); $authCheck = $helpers->authCheck($hash); if ($authCheck== true) { $json = $request->get("data",null); $params = json_decode($json); $gruaCiudadano = new PqoGruaCiudadano(); $em = $this->getDoctrine()->getManager(); $gruaCiudadano->setFechaInicial(new \Datetime($params->fechaInicial)); if ($params->observaciones) { $gruaCiudadano->setObservaciones($params->observaciones); } $gruaCiudadano->setTipo($params->tipo); if ($params->idGrua) { $grua = $em->getRepository('JHWEBParqueaderoBundle:PqoCfgGrua')->find( $params->idGrua ); $gruaCiudadano->setGrua($grua); } if ($params->idCiudadano) { $ciudadano = $em->getRepository('JHWEBUsuarioBundle:UserCiudadano')->find( $params->idCiudadano ); $gruaCiudadano->setCiudadano($ciudadano); } $gruaCiudadano->setActivo(true); $em->persist($gruaCiudadano); $em->flush(); $response = array( 'status' => 'success', 'code' => 200, 'message' => "Registro creado con exito", ); }else{ $response = array( 'status' => 'error', 'code' => 400, 'message' => "Autorizacion no valida", ); } return $helpers->json($response); } /** * Finds and displays a pqoGruaCiudadano entity. * * @Route("/{id}", name="pqogruaciudadano_show") * @Method("GET") */ public function showAction(PqoGruaCiudadano $pqoGruaCiudadano) { $deleteForm = $this->createDeleteForm($pqoGruaCiudadano); return $this->render('pqogruaciudadano/show.html.twig', array( 'pqoGruaCiudadano' => $pqoGruaCiudadano, 'delete_form' => $deleteForm->createView(), )); } /** * Displays a form to edit an existing pqoGruaCiudadano entity. * * @Route("/{id}/edit", name="pqogruaciudadano_edit") * @Method({"GET", "POST"}) */ public function editAction(Request $request, PqoGruaCiudadano $pqoGruaCiudadano) { $deleteForm = $this->createDeleteForm($pqoGruaCiudadano); $editForm = $this->createForm('JHWEB\ParqueaderoBundle\Form\PqoGruaCiudadanoType', $pqoGruaCiudadano); $editForm->handleRequest($request); if ($editForm->isSubmitted() && $editForm->isValid()) { $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('pqogruaciudadano_edit', array('id' => $pqoGruaCiudadano->getId())); } return $this->render('pqogruaciudadano/edit.html.twig', array( 'pqoGruaCiudadano' => $pqoGruaCiudadano, 'edit_form' => $editForm->createView(), 'delete_form' => $deleteForm->createView(), )); } /** * Deletes a pqoGruaCiudadano entity. * * @Route("/{id}", name="pqogruaciudadano_delete") * @Method("DELETE") */ public function deleteAction(Request $request, PqoGruaCiudadano $pqoGruaCiudadano) { $form = $this->createDeleteForm($pqoGruaCiudadano); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->remove($pqoGruaCiudadano); $em->flush(); } return $this->redirectToRoute('pqogruaciudadano_index'); } /** * Creates a form to delete a pqoGruaCiudadano entity. * * @param PqoGruaCiudadano $pqoGruaCiudadano The pqoGruaCiudadano entity * * @return \Symfony\Component\Form\Form The form */ private function createDeleteForm(PqoGruaCiudadano $pqoGruaCiudadano) { return $this->createFormBuilder() ->setAction($this->generateUrl('pqogruaciudadano_delete', array('id' => $pqoGruaCiudadano->getId()))) ->setMethod('DELETE') ->getForm() ; } }
{ "content_hash": "d854bf12be22c00e9df2439dcff379c9", "timestamp": "", "source": "github", "line_count": 186, "max_line_length": 113, "avg_line_length": 31.698924731182796, "alnum_prop": 0.5620759837177748, "repo_name": "edosgn/colossus-sit", "id": "aa20df79e1a0e6bc72b612224fbcd1b89266afe1", "size": "5896", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/JHWEB/ParqueaderoBundle/Controller/PqoGruaCiudadanoController.php", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "326601" }, { "name": "PHP", "bytes": "6284297" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "2cf13e221182d1f03a18d0f8cb27cda8", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "1fd8183be7e7bcb7c7e1cc46a4cece232f10fc30", "size": "206", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Chrysobalanaceae/Dactyladenia/Dactyladenia pierrei/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.example.plugintest.manymethods.d.d; public class A1 { public static void a0(String msg) { System.out.println("msg=" + msg + 0); } public static void a1(String msg) { System.out.println("msg=" + msg + 1); } public static void a2(String msg) { System.out.println("msg=" + msg + 2); } public static void a3(String msg) { System.out.println("msg=" + msg + 3); } public static void a4(String msg) { System.out.println("msg=" + msg + 4); } public static void a5(String msg) { System.out.println("msg=" + msg + 5); } public static void a6(String msg) { System.out.println("msg=" + msg + 6); } public static void a7(String msg) { System.out.println("msg=" + msg + 7); } public static void a8(String msg) { System.out.println("msg=" + msg + 8); } public static void a9(String msg) { System.out.println("msg=" + msg + 9); } public static void a10(String msg) { System.out.println("msg=" + msg + 10); } public static void a11(String msg) { System.out.println("msg=" + msg + 11); } public static void a12(String msg) { System.out.println("msg=" + msg + 12); } public static void a13(String msg) { System.out.println("msg=" + msg + 13); } public static void a14(String msg) { System.out.println("msg=" + msg + 14); } public static void a15(String msg) { System.out.println("msg=" + msg + 15); } public static void a16(String msg) { System.out.println("msg=" + msg + 16); } public static void a17(String msg) { System.out.println("msg=" + msg + 17); } public static void a18(String msg) { System.out.println("msg=" + msg + 18); } public static void a19(String msg) { System.out.println("msg=" + msg + 19); } public static void a20(String msg) { System.out.println("msg=" + msg + 20); } public static void a21(String msg) { System.out.println("msg=" + msg + 21); } public static void a22(String msg) { System.out.println("msg=" + msg + 22); } public static void a23(String msg) { System.out.println("msg=" + msg + 23); } public static void a24(String msg) { System.out.println("msg=" + msg + 24); } public static void a25(String msg) { System.out.println("msg=" + msg + 25); } public static void a26(String msg) { System.out.println("msg=" + msg + 26); } public static void a27(String msg) { System.out.println("msg=" + msg + 27); } public static void a28(String msg) { System.out.println("msg=" + msg + 28); } public static void a29(String msg) { System.out.println("msg=" + msg + 29); } public static void a30(String msg) { System.out.println("msg=" + msg + 30); } public static void a31(String msg) { System.out.println("msg=" + msg + 31); } public static void a32(String msg) { System.out.println("msg=" + msg + 32); } public static void a33(String msg) { System.out.println("msg=" + msg + 33); } public static void a34(String msg) { System.out.println("msg=" + msg + 34); } public static void a35(String msg) { System.out.println("msg=" + msg + 35); } public static void a36(String msg) { System.out.println("msg=" + msg + 36); } public static void a37(String msg) { System.out.println("msg=" + msg + 37); } public static void a38(String msg) { System.out.println("msg=" + msg + 38); } public static void a39(String msg) { System.out.println("msg=" + msg + 39); } public static void a40(String msg) { System.out.println("msg=" + msg + 40); } public static void a41(String msg) { System.out.println("msg=" + msg + 41); } public static void a42(String msg) { System.out.println("msg=" + msg + 42); } public static void a43(String msg) { System.out.println("msg=" + msg + 43); } public static void a44(String msg) { System.out.println("msg=" + msg + 44); } public static void a45(String msg) { System.out.println("msg=" + msg + 45); } public static void a46(String msg) { System.out.println("msg=" + msg + 46); } public static void a47(String msg) { System.out.println("msg=" + msg + 47); } public static void a48(String msg) { System.out.println("msg=" + msg + 48); } public static void a49(String msg) { System.out.println("msg=" + msg + 49); } public static void a50(String msg) { System.out.println("msg=" + msg + 50); } public static void a51(String msg) { System.out.println("msg=" + msg + 51); } public static void a52(String msg) { System.out.println("msg=" + msg + 52); } public static void a53(String msg) { System.out.println("msg=" + msg + 53); } public static void a54(String msg) { System.out.println("msg=" + msg + 54); } public static void a55(String msg) { System.out.println("msg=" + msg + 55); } public static void a56(String msg) { System.out.println("msg=" + msg + 56); } public static void a57(String msg) { System.out.println("msg=" + msg + 57); } public static void a58(String msg) { System.out.println("msg=" + msg + 58); } public static void a59(String msg) { System.out.println("msg=" + msg + 59); } public static void a60(String msg) { System.out.println("msg=" + msg + 60); } public static void a61(String msg) { System.out.println("msg=" + msg + 61); } public static void a62(String msg) { System.out.println("msg=" + msg + 62); } public static void a63(String msg) { System.out.println("msg=" + msg + 63); } public static void a64(String msg) { System.out.println("msg=" + msg + 64); } public static void a65(String msg) { System.out.println("msg=" + msg + 65); } public static void a66(String msg) { System.out.println("msg=" + msg + 66); } public static void a67(String msg) { System.out.println("msg=" + msg + 67); } public static void a68(String msg) { System.out.println("msg=" + msg + 68); } public static void a69(String msg) { System.out.println("msg=" + msg + 69); } public static void a70(String msg) { System.out.println("msg=" + msg + 70); } public static void a71(String msg) { System.out.println("msg=" + msg + 71); } public static void a72(String msg) { System.out.println("msg=" + msg + 72); } public static void a73(String msg) { System.out.println("msg=" + msg + 73); } public static void a74(String msg) { System.out.println("msg=" + msg + 74); } public static void a75(String msg) { System.out.println("msg=" + msg + 75); } public static void a76(String msg) { System.out.println("msg=" + msg + 76); } public static void a77(String msg) { System.out.println("msg=" + msg + 77); } public static void a78(String msg) { System.out.println("msg=" + msg + 78); } public static void a79(String msg) { System.out.println("msg=" + msg + 79); } public static void a80(String msg) { System.out.println("msg=" + msg + 80); } public static void a81(String msg) { System.out.println("msg=" + msg + 81); } public static void a82(String msg) { System.out.println("msg=" + msg + 82); } public static void a83(String msg) { System.out.println("msg=" + msg + 83); } public static void a84(String msg) { System.out.println("msg=" + msg + 84); } public static void a85(String msg) { System.out.println("msg=" + msg + 85); } public static void a86(String msg) { System.out.println("msg=" + msg + 86); } public static void a87(String msg) { System.out.println("msg=" + msg + 87); } public static void a88(String msg) { System.out.println("msg=" + msg + 88); } public static void a89(String msg) { System.out.println("msg=" + msg + 89); } public static void a90(String msg) { System.out.println("msg=" + msg + 90); } public static void a91(String msg) { System.out.println("msg=" + msg + 91); } public static void a92(String msg) { System.out.println("msg=" + msg + 92); } public static void a93(String msg) { System.out.println("msg=" + msg + 93); } public static void a94(String msg) { System.out.println("msg=" + msg + 94); } public static void a95(String msg) { System.out.println("msg=" + msg + 95); } public static void a96(String msg) { System.out.println("msg=" + msg + 96); } public static void a97(String msg) { System.out.println("msg=" + msg + 97); } public static void a98(String msg) { System.out.println("msg=" + msg + 98); } public static void a99(String msg) { System.out.println("msg=" + msg + 99); } }
{ "content_hash": "29dea76868db352a399173fdff072b52", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 81, "avg_line_length": 79.3173076923077, "alnum_prop": 0.6343799248393744, "repo_name": "limpoxe/Android-Plugin-Framework", "id": "2bcf446f40afa9a02956bb453fed08695ec10a85", "size": "8249", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Samples/PluginTest/src/main/java/com/example/plugintest/manymethods/d/d/A1.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "746511" }, { "name": "Shell", "bytes": "693" } ], "symlink_target": "" }
package master import ( "bytes" "fmt" "os" "path" "strings" "github.com/ghodss/yaml" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" api "k8s.io/client-go/pkg/api/v1" kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm" kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants" "k8s.io/kubernetes/cmd/kubeadm/app/images" bootstrapapi "k8s.io/kubernetes/pkg/bootstrap/api" authzmodes "k8s.io/kubernetes/pkg/kubeapiserver/authorizer/modes" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" ) // Static pod definitions in golang form are included below so that `kubeadm init` can get going. const ( DefaultCloudConfigPath = "/etc/kubernetes/cloud-config" etcd = "etcd" apiServer = "apiserver" controllerManager = "controller-manager" scheduler = "scheduler" proxy = "proxy" kubeAPIServer = "kube-apiserver" kubeControllerManager = "kube-controller-manager" kubeScheduler = "kube-scheduler" kubeProxy = "kube-proxy" ) // WriteStaticPodManifests builds manifest objects based on user provided configuration and then dumps it to disk // where kubelet will pick and schedule them. func WriteStaticPodManifests(cfg *kubeadmapi.MasterConfiguration) error { volumes := []api.Volume{k8sVolume(cfg)} volumeMounts := []api.VolumeMount{k8sVolumeMount()} if isCertsVolumeMountNeeded() { volumes = append(volumes, certsVolume(cfg)) volumeMounts = append(volumeMounts, certsVolumeMount()) } if isPkiVolumeMountNeeded() { volumes = append(volumes, pkiVolume(cfg)) volumeMounts = append(volumeMounts, pkiVolumeMount()) } // Prepare static pod specs staticPodSpecs := map[string]api.Pod{ kubeAPIServer: componentPod(api.Container{ Name: kubeAPIServer, Image: images.GetCoreImage(images.KubeAPIServerImage, cfg, kubeadmapi.GlobalEnvParams.HyperkubeImage), Command: getAPIServerCommand(cfg, false), VolumeMounts: volumeMounts, LivenessProbe: componentProbe(int(cfg.API.BindPort), "/healthz", api.URISchemeHTTPS), Resources: componentResources("250m"), Env: getProxyEnvVars(), }, volumes...), kubeControllerManager: componentPod(api.Container{ Name: kubeControllerManager, Image: images.GetCoreImage(images.KubeControllerManagerImage, cfg, kubeadmapi.GlobalEnvParams.HyperkubeImage), Command: getControllerManagerCommand(cfg, false), VolumeMounts: volumeMounts, LivenessProbe: componentProbe(10252, "/healthz", api.URISchemeHTTP), Resources: componentResources("200m"), Env: getProxyEnvVars(), }, volumes...), kubeScheduler: componentPod(api.Container{ Name: kubeScheduler, Image: images.GetCoreImage(images.KubeSchedulerImage, cfg, kubeadmapi.GlobalEnvParams.HyperkubeImage), Command: getSchedulerCommand(cfg, false), VolumeMounts: []api.VolumeMount{k8sVolumeMount()}, LivenessProbe: componentProbe(10251, "/healthz", api.URISchemeHTTP), Resources: componentResources("100m"), Env: getProxyEnvVars(), }, k8sVolume(cfg)), } // Add etcd static pod spec only if external etcd is not configured if len(cfg.Etcd.Endpoints) == 0 { etcdPod := componentPod(api.Container{ Name: etcd, Command: []string{ "etcd", "--listen-client-urls=http://127.0.0.1:2379", "--advertise-client-urls=http://127.0.0.1:2379", "--data-dir=/var/lib/etcd", }, VolumeMounts: []api.VolumeMount{certsVolumeMount(), etcdVolumeMount(), k8sVolumeMount()}, Image: images.GetCoreImage(images.KubeEtcdImage, cfg, kubeadmapi.GlobalEnvParams.EtcdImage), LivenessProbe: componentProbe(2379, "/health", api.URISchemeHTTP), }, certsVolume(cfg), etcdVolume(cfg), k8sVolume(cfg)) etcdPod.Spec.SecurityContext = &api.PodSecurityContext{ SELinuxOptions: &api.SELinuxOptions{ // Unconfine the etcd container so it can write to /var/lib/etcd with SELinux enforcing: Type: "spc_t", }, } staticPodSpecs[etcd] = etcdPod } manifestsPath := path.Join(kubeadmapi.GlobalEnvParams.KubernetesDir, "manifests") if err := os.MkdirAll(manifestsPath, 0700); err != nil { return fmt.Errorf("failed to create directory %q [%v]", manifestsPath, err) } for name, spec := range staticPodSpecs { filename := path.Join(manifestsPath, name+".yaml") serialized, err := yaml.Marshal(spec) if err != nil { return fmt.Errorf("failed to marshal manifest for %q to YAML [%v]", name, err) } if err := cmdutil.DumpReaderToFile(bytes.NewReader(serialized), filename); err != nil { return fmt.Errorf("failed to create static pod manifest file for %q (%q) [%v]", name, filename, err) } } return nil } // etcdVolume exposes a path on the host in order to guarantee data survival during reboot. func etcdVolume(cfg *kubeadmapi.MasterConfiguration) api.Volume { return api.Volume{ Name: "etcd", VolumeSource: api.VolumeSource{ HostPath: &api.HostPathVolumeSource{Path: kubeadmapi.GlobalEnvParams.HostEtcdPath}, }, } } func etcdVolumeMount() api.VolumeMount { return api.VolumeMount{ Name: "etcd", MountPath: "/var/lib/etcd", } } func isCertsVolumeMountNeeded() bool { // Always return true for now. We may add conditional logic here for images which do not require host mounting /etc/ssl // hyperkube for example already has valid ca-certificates installed return true } // certsVolume exposes host SSL certificates to pod containers. func certsVolume(cfg *kubeadmapi.MasterConfiguration) api.Volume { return api.Volume{ Name: "certs", VolumeSource: api.VolumeSource{ // TODO(phase1+) make path configurable HostPath: &api.HostPathVolumeSource{Path: "/etc/ssl/certs"}, }, } } func certsVolumeMount() api.VolumeMount { return api.VolumeMount{ Name: "certs", MountPath: "/etc/ssl/certs", } } func isPkiVolumeMountNeeded() bool { // On some systems were we host-mount /etc/ssl/certs, it is also required to mount /etc/pki. This is needed // due to symlinks pointing from files in /etc/ssl/certs into /etc/pki/ if _, err := os.Stat("/etc/pki"); err == nil { return true } return false } func pkiVolume(cfg *kubeadmapi.MasterConfiguration) api.Volume { return api.Volume{ Name: "pki", VolumeSource: api.VolumeSource{ // TODO(phase1+) make path configurable HostPath: &api.HostPathVolumeSource{Path: "/etc/pki"}, }, } } func pkiVolumeMount() api.VolumeMount { return api.VolumeMount{ Name: "pki", MountPath: "/etc/pki", } } func flockVolume() api.Volume { return api.Volume{ Name: "var-lock", VolumeSource: api.VolumeSource{ HostPath: &api.HostPathVolumeSource{Path: "/var/lock"}, }, } } func flockVolumeMount() api.VolumeMount { return api.VolumeMount{ Name: "var-lock", MountPath: "/var/lock", ReadOnly: false, } } func k8sVolume(cfg *kubeadmapi.MasterConfiguration) api.Volume { return api.Volume{ Name: "k8s", VolumeSource: api.VolumeSource{ HostPath: &api.HostPathVolumeSource{Path: kubeadmapi.GlobalEnvParams.KubernetesDir}, }, } } func k8sVolumeMount() api.VolumeMount { return api.VolumeMount{ Name: "k8s", MountPath: "/etc/kubernetes/", ReadOnly: true, } } func componentResources(cpu string) api.ResourceRequirements { return api.ResourceRequirements{ Requests: api.ResourceList{ api.ResourceName(api.ResourceCPU): resource.MustParse(cpu), }, } } func componentProbe(port int, path string, scheme api.URIScheme) *api.Probe { return &api.Probe{ Handler: api.Handler{ HTTPGet: &api.HTTPGetAction{ Host: "127.0.0.1", Path: path, Port: intstr.FromInt(port), Scheme: scheme, }, }, InitialDelaySeconds: 15, TimeoutSeconds: 15, FailureThreshold: 8, } } func componentPod(container api.Container, volumes ...api.Volume) api.Pod { return api.Pod{ TypeMeta: metav1.TypeMeta{ APIVersion: "v1", Kind: "Pod", }, ObjectMeta: metav1.ObjectMeta{ Name: container.Name, Namespace: "kube-system", Labels: map[string]string{"component": container.Name, "tier": "control-plane"}, }, Spec: api.PodSpec{ Containers: []api.Container{container}, HostNetwork: true, Volumes: volumes, }, } } func getComponentBaseCommand(component string) []string { if kubeadmapi.GlobalEnvParams.HyperkubeImage != "" { return []string{"/hyperkube", component} } return []string{"kube-" + component} } func getAPIServerCommand(cfg *kubeadmapi.MasterConfiguration, selfHosted bool) []string { var command []string // self-hosted apiserver needs to wait on a lock if selfHosted { command = []string{"/usr/bin/flock", "--exclusive", "--timeout=30", "/var/lock/api-server.lock"} } defaultArguments := map[string]string{ "insecure-port": "0", "admission-control": kubeadmconstants.DefaultAdmissionControl, "service-cluster-ip-range": cfg.Networking.ServiceSubnet, "service-account-key-file": path.Join(cfg.CertificatesDir, kubeadmconstants.ServiceAccountPublicKeyName), "client-ca-file": path.Join(cfg.CertificatesDir, kubeadmconstants.CACertName), "tls-cert-file": path.Join(cfg.CertificatesDir, kubeadmconstants.APIServerCertName), "tls-private-key-file": path.Join(cfg.CertificatesDir, kubeadmconstants.APIServerKeyName), "kubelet-client-certificate": path.Join(cfg.CertificatesDir, kubeadmconstants.APIServerKubeletClientCertName), "kubelet-client-key": path.Join(cfg.CertificatesDir, kubeadmconstants.APIServerKubeletClientKeyName), "secure-port": fmt.Sprintf("%d", cfg.API.BindPort), "allow-privileged": "true", "experimental-bootstrap-token-auth": "true", "storage-backend": "etcd3", "kubelet-preferred-address-types": "InternalIP,ExternalIP,Hostname", // add options to configure the front proxy. Without the generated client cert, this will never be useable // so add it unconditionally with recommended values "requestheader-username-headers": "X-Remote-User", "requestheader-group-headers": "X-Remote-Group", "requestheader-extra-headers-prefix": "X-Remote-Extra-", "requestheader-client-ca-file": path.Join(cfg.CertificatesDir, kubeadmconstants.FrontProxyCACertName), "requestheader-allowed-names": "front-proxy-client", // add options which allow the kube-apiserver to act as a front-proxy to aggregated API servers "proxy-client-cert-file": path.Join(cfg.CertificatesDir, kubeadmconstants.FrontProxyClientCertName), "proxy-client-key-file": path.Join(cfg.CertificatesDir, kubeadmconstants.FrontProxyClientKeyName), } command = getComponentBaseCommand(apiServer) command = append(command, getExtraParameters(cfg.APIServerExtraArgs, defaultArguments)...) command = append(command, getAuthzParameters(cfg.AuthorizationModes)...) if selfHosted { command = append(command, "--advertise-address=$(POD_IP)") } else { command = append(command, fmt.Sprintf("--advertise-address=%s", cfg.API.AdvertiseAddress)) } // Check if the user decided to use an external etcd cluster if len(cfg.Etcd.Endpoints) > 0 { command = append(command, fmt.Sprintf("--etcd-servers=%s", strings.Join(cfg.Etcd.Endpoints, ","))) } else { command = append(command, "--etcd-servers=http://127.0.0.1:2379") } // Is etcd secured? if cfg.Etcd.CAFile != "" { command = append(command, fmt.Sprintf("--etcd-cafile=%s", cfg.Etcd.CAFile)) } if cfg.Etcd.CertFile != "" && cfg.Etcd.KeyFile != "" { etcdClientFileArg := fmt.Sprintf("--etcd-certfile=%s", cfg.Etcd.CertFile) etcdKeyFileArg := fmt.Sprintf("--etcd-keyfile=%s", cfg.Etcd.KeyFile) command = append(command, etcdClientFileArg, etcdKeyFileArg) } if cfg.CloudProvider != "" { command = append(command, "--cloud-provider="+cfg.CloudProvider) // Only append the --cloud-config option if there's a such file if _, err := os.Stat(DefaultCloudConfigPath); err == nil { command = append(command, "--cloud-config="+DefaultCloudConfigPath) } } return command } func getControllerManagerCommand(cfg *kubeadmapi.MasterConfiguration, selfHosted bool) []string { var command []string // self-hosted controller-manager needs to wait on a lock if selfHosted { command = []string{"/usr/bin/flock", "--exclusive", "--timeout=30", "/var/lock/controller-manager.lock"} } defaultArguments := map[string]string{ "address": "127.0.0.1", "leader-elect": "true", "kubeconfig": path.Join(kubeadmapi.GlobalEnvParams.KubernetesDir, kubeadmconstants.ControllerManagerKubeConfigFileName), "root-ca-file": path.Join(cfg.CertificatesDir, kubeadmconstants.CACertName), "service-account-private-key-file": path.Join(cfg.CertificatesDir, kubeadmconstants.ServiceAccountPrivateKeyName), "cluster-signing-cert-file": path.Join(cfg.CertificatesDir, kubeadmconstants.CACertName), "cluster-signing-key-file": path.Join(cfg.CertificatesDir, kubeadmconstants.CAKeyName), "insecure-experimental-approve-all-kubelet-csrs-for-group": bootstrapapi.BootstrapGroup, "use-service-account-credentials": "true", "controllers": "*,bootstrapsigner,tokencleaner", } command = getComponentBaseCommand(controllerManager) command = append(command, getExtraParameters(cfg.ControllerManagerExtraArgs, defaultArguments)...) if cfg.CloudProvider != "" { command = append(command, "--cloud-provider="+cfg.CloudProvider) // Only append the --cloud-config option if there's a such file if _, err := os.Stat(DefaultCloudConfigPath); err == nil { command = append(command, "--cloud-config="+DefaultCloudConfigPath) } } // Let the controller-manager allocate Node CIDRs for the Pod network. // Each node will get a subspace of the address CIDR provided with --pod-network-cidr. if cfg.Networking.PodSubnet != "" { command = append(command, "--allocate-node-cidrs=true", "--cluster-cidr="+cfg.Networking.PodSubnet) } return command } func getSchedulerCommand(cfg *kubeadmapi.MasterConfiguration, selfHosted bool) []string { var command []string // self-hosted apiserver needs to wait on a lock if selfHosted { command = []string{"/usr/bin/flock", "--exclusive", "--timeout=30", "/var/lock/api-server.lock"} } defaultArguments := map[string]string{ "address": "127.0.0.1", "leader-elect": "true", "kubeconfig": path.Join(kubeadmapi.GlobalEnvParams.KubernetesDir, kubeadmconstants.SchedulerKubeConfigFileName), } command = getComponentBaseCommand(scheduler) command = append(command, getExtraParameters(cfg.SchedulerExtraArgs, defaultArguments)...) return command } func getProxyEnvVars() []api.EnvVar { envs := []api.EnvVar{} for _, env := range os.Environ() { pos := strings.Index(env, "=") if pos == -1 { // malformed environment variable, skip it. continue } name := env[:pos] value := env[pos+1:] if strings.HasSuffix(strings.ToLower(name), "_proxy") && value != "" { envVar := api.EnvVar{Name: name, Value: value} envs = append(envs, envVar) } } return envs } func getSelfHostedAPIServerEnv() []api.EnvVar { podIPEnvVar := api.EnvVar{ Name: "POD_IP", ValueFrom: &api.EnvVarSource{ FieldRef: &api.ObjectFieldSelector{ FieldPath: "status.podIP", }, }, } return append(getProxyEnvVars(), podIPEnvVar) } func getAuthzParameters(modes []string) []string { command := []string{} // RBAC is always on. If the user specified authzModes := []string{authzmodes.ModeRBAC} for _, authzMode := range modes { if len(authzMode) != 0 && authzMode != authzmodes.ModeRBAC { authzModes = append(authzModes, authzMode) } switch authzMode { case authzmodes.ModeABAC: command = append(command, "--authorization-policy-file="+kubeadmconstants.AuthorizationPolicyPath) case authzmodes.ModeWebhook: command = append(command, "--authorization-webhook-config-file="+kubeadmconstants.AuthorizationWebhookConfigPath) } } command = append(command, "--authorization-mode="+strings.Join(authzModes, ",")) return command } func getExtraParameters(overrides map[string]string, defaults map[string]string) []string { var command []string for k, v := range overrides { if len(v) > 0 { command = append(command, fmt.Sprintf("--%s=%s", k, v)) } } for k, v := range defaults { if _, overrideExists := overrides[k]; !overrideExists { command = append(command, fmt.Sprintf("--%s=%s", k, v)) } } return command }
{ "content_hash": "acacf55497b3492685630c2303aed765", "timestamp": "", "source": "github", "line_count": 482, "max_line_length": 168, "avg_line_length": 35.107883817427386, "alnum_prop": 0.692057676397589, "repo_name": "cheld/kubernetes", "id": "b1f416b7c3dd84adf863c7532c6eac8e18e70984", "size": "17491", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cmd/kubeadm/app/master/manifests.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2539" }, { "name": "Go", "bytes": "45776376" }, { "name": "HTML", "bytes": "2650745" }, { "name": "Makefile", "bytes": "79644" }, { "name": "Nginx", "bytes": "1608" }, { "name": "PowerShell", "bytes": "4261" }, { "name": "Protocol Buffer", "bytes": "692465" }, { "name": "Python", "bytes": "1473303" }, { "name": "SaltStack", "bytes": "56168" }, { "name": "Shell", "bytes": "1574361" } ], "symlink_target": "" }
package com.amazonaws.services.guardduty.model; import java.io.Serializable; import javax.annotation.Generated; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/guardduty-2017-11-28/DeleteInvitations" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteInvitationsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * A list of objects that contain the unprocessed account and a result string that explains why it was unprocessed. * </p> */ private java.util.List<UnprocessedAccount> unprocessedAccounts; /** * <p> * A list of objects that contain the unprocessed account and a result string that explains why it was unprocessed. * </p> * * @return A list of objects that contain the unprocessed account and a result string that explains why it was * unprocessed. */ public java.util.List<UnprocessedAccount> getUnprocessedAccounts() { return unprocessedAccounts; } /** * <p> * A list of objects that contain the unprocessed account and a result string that explains why it was unprocessed. * </p> * * @param unprocessedAccounts * A list of objects that contain the unprocessed account and a result string that explains why it was * unprocessed. */ public void setUnprocessedAccounts(java.util.Collection<UnprocessedAccount> unprocessedAccounts) { if (unprocessedAccounts == null) { this.unprocessedAccounts = null; return; } this.unprocessedAccounts = new java.util.ArrayList<UnprocessedAccount>(unprocessedAccounts); } /** * <p> * A list of objects that contain the unprocessed account and a result string that explains why it was unprocessed. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setUnprocessedAccounts(java.util.Collection)} or {@link #withUnprocessedAccounts(java.util.Collection)} * if you want to override the existing values. * </p> * * @param unprocessedAccounts * A list of objects that contain the unprocessed account and a result string that explains why it was * unprocessed. * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteInvitationsResult withUnprocessedAccounts(UnprocessedAccount... unprocessedAccounts) { if (this.unprocessedAccounts == null) { setUnprocessedAccounts(new java.util.ArrayList<UnprocessedAccount>(unprocessedAccounts.length)); } for (UnprocessedAccount ele : unprocessedAccounts) { this.unprocessedAccounts.add(ele); } return this; } /** * <p> * A list of objects that contain the unprocessed account and a result string that explains why it was unprocessed. * </p> * * @param unprocessedAccounts * A list of objects that contain the unprocessed account and a result string that explains why it was * unprocessed. * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteInvitationsResult withUnprocessedAccounts(java.util.Collection<UnprocessedAccount> unprocessedAccounts) { setUnprocessedAccounts(unprocessedAccounts); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getUnprocessedAccounts() != null) sb.append("UnprocessedAccounts: ").append(getUnprocessedAccounts()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteInvitationsResult == false) return false; DeleteInvitationsResult other = (DeleteInvitationsResult) obj; if (other.getUnprocessedAccounts() == null ^ this.getUnprocessedAccounts() == null) return false; if (other.getUnprocessedAccounts() != null && other.getUnprocessedAccounts().equals(this.getUnprocessedAccounts()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getUnprocessedAccounts() == null) ? 0 : getUnprocessedAccounts().hashCode()); return hashCode; } @Override public DeleteInvitationsResult clone() { try { return (DeleteInvitationsResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
{ "content_hash": "b18d8f88fd7fb86c92ff4fe8418bd9e5", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 150, "avg_line_length": 36.261744966442954, "alnum_prop": 0.6559318896909124, "repo_name": "aws/aws-sdk-java", "id": "e72d1269597c0c8d01e008af3db1c005e7ad7de0", "size": "5983", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-guardduty/src/main/java/com/amazonaws/services/guardduty/model/DeleteInvitationsResult.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
({ /** * Verify css from template is properly injected and present on loaded DOM. * known issue with IE11 and layout : W-2375142 */ testStyleCssInjectedIntoDom : { browsers : ["-IE8", "-IE11", "-IE10"], test : function(cmp) { var found = false; var cssText = ""; var styleSheets = document.styleSheets; for (var i = 0; i < styleSheets.length; i++) { var cssRules = styleSheets[i].cssRules; for (var j = 0; j < cssRules.length; j++) { /* * IE10 has a nasty habit of throwing "unknown" (when using typeof) or Member not found. exceptions with * CSS styles that it doesn't understand */ if ($A.get("$Browser").isIE10 && typeof cssRules[j].cssText === 'unknown') { continue; } cssText = cssRules[j].cssText; cssText = cssText.replace(/\s+/g, '').toLowerCase(); // Different browsers have slightly different formatting so just check enough to feel confident if (cssText.indexOf(".templaterule{border") != -1 && cssText.indexOf("font-style:italic") != -1) { found = true; continue; } } } $A.test.assertTrue(found, "Loaded app does not have template css present."); } }, /** * Same test as above (testStyleCssInjectedIntoDom), but older versions of IE have different properties on the * styleSheets object so try to find the template CSS a slightly different way. */ testStyleCssInjectedIntoDomIE : { browsers : ["IE8"], test : function(cmp) { var found = false; var styleSheets = document.styleSheets; for (var i = 0; i < styleSheets.length; i++) { var cssText = styleSheets[i].cssText; cssText = cssText.replace(/\s+/g, '').toLowerCase(); if (cssText.indexOf(".templaterule{border") != -1 && cssText.indexOf("font-style:italic") != -1) { found = true; continue; } } $A.test.assertTrue(found, "Loaded app does not have template css present."); } } })
{ "content_hash": "e01f2b24b1e898046edc1d85d7761523", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 124, "avg_line_length": 42.56140350877193, "alnum_prop": 0.5037098103874691, "repo_name": "madmax983/aura", "id": "cdc7d72f42cae9064dedd60bc5dd1c9724adaca9", "size": "3037", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "aura-components/src/test/components/test/styleTest/styleTestTest.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "782982" }, { "name": "GAP", "bytes": "10087" }, { "name": "HTML", "bytes": "3296233" }, { "name": "Java", "bytes": "9575906" }, { "name": "JavaScript", "bytes": "26838648" }, { "name": "PHP", "bytes": "3345441" }, { "name": "Python", "bytes": "9744" }, { "name": "Shell", "bytes": "20356" }, { "name": "XSLT", "bytes": "1579" } ], "symlink_target": "" }
from couchdbkit.ext.django.schema import Document from django.core.management.base import LabelCommand, CommandError from corehq.apps.domain.models import OldDomain from corehq.apps.domain.shortcuts import create_domain, create_user from corehq.apps.domain.utils import normalize_domain_name from corehq.apps.users.models import CouchUser from dimagi.utils.couch.database import get_db class Command(LabelCommand): def handle(self, *args, **options): django_domains = OldDomain.objects.all() django_domain_names = set([domain.name for domain in django_domains]) couch_domain_names = set([x['key'][0] for x in get_db().view('domain/docs', group_level=1).all()]) couch_user_domain_names = set([x['key'] for x in get_db().view('users/by_domain', group=True).all()]) print get_db().view('users/by_domain').all() normalized_names = {} domains_that_need_to_change = set() # print some warnings if things are fishy for domain in couch_domain_names.union(couch_user_domain_names): if domain not in django_domain_names: print "Warning: domain '%s' not in SQL" % domain normalized = normalize_domain_name(domain) if normalized in normalized_names: print "Warning: domains '%s' and '%s' both exist" % (domain, normalized_names[normalized]) normalized_names[normalized] = domain if normalized != domain: domains_that_need_to_change.add(domain) print "Going to change the following domains:" for domain in domains_that_need_to_change: print " %s" % domain print if raw_input("Are you sure you want to continue? (Y/n)") != 'Y': print "Mission aborted" return print "Migrating SQL domains" for django_domain in django_domains: django_domain.name = normalize_domain_name(django_domain.name) django_domain.save() print "Migrating domains in Couch docs" class MyDoc(Document): class Meta: app_label = 'domain' def get_docs(domain): chunk_size = 500 i = 0 while True: docs = MyDoc.view('domain/docs', startkey=[domain], endkey=[domain, {}], reduce=False, include_docs=True, skip=i*chunk_size, limit=chunk_size) for doc in docs: yield doc if not len(docs): break i += 1 for domain in domains_that_need_to_change: print "%s:" % domain for doc in get_docs(domain): print '.', if 'domain' in doc: doc['domain'] = normalize_domain_name(doc['domain']) if 'domains' in doc: for i,domain in enumerate(doc['domains']): doc['domains'][i] = normalize_domain_name(doc['domains'][i]) doc.save() print print "Patching users" for domain in domains_that_need_to_change: print '.', couch_users = CouchUser.view('users/by_domain', key=domain, include_docs=True, reduce=False) for user in couch_users: for dm in user.web_account.domain_memberships: dm.domain = normalize_domain_name(dm.domain) for account in user.commcare_accounts: if account.domain: account.domain = normalize_domain_name(account.domain) user.save()
{ "content_hash": "7b76af30398abd98e9fd0e54e6312502", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 109, "avg_line_length": 43.88095238095238, "alnum_prop": 0.566467715680955, "repo_name": "gmimano/commcaretest", "id": "c535861e787bcda63203babc76309840315a87e3", "size": "3686", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "corehq/apps/domain/management/commands/migrate_domain_names.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ActionScript", "bytes": "15950" }, { "name": "CSS", "bytes": "282577" }, { "name": "JavaScript", "bytes": "2731012" }, { "name": "Python", "bytes": "4738450" }, { "name": "Shell", "bytes": "22454" } ], "symlink_target": "" }
//===--- Decl.h - Swift Language Declaration ASTs ---------------*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines the Decl class and subclasses. // //===----------------------------------------------------------------------===// #ifndef SWIFT_DECL_H #define SWIFT_DECL_H #include "swift/AST/AccessScope.h" #include "swift/AST/Attr.h" #include "swift/AST/CaptureInfo.h" #include "swift/AST/ClangNode.h" #include "swift/AST/ConcreteDeclRef.h" #include "swift/AST/DefaultArgumentKind.h" #include "swift/AST/DiagnosticConsumer.h" #include "swift/AST/DiagnosticEngine.h" #include "swift/AST/GenericParamKey.h" #include "swift/AST/IfConfigClause.h" #include "swift/AST/LayoutConstraint.h" #include "swift/AST/StorageImpl.h" #include "swift/AST/TypeAlignments.h" #include "swift/AST/TypeWalker.h" #include "swift/AST/Types.h" #include "swift/AST/Witness.h" #include "swift/Basic/ArrayRefView.h" #include "swift/Basic/Compiler.h" #include "swift/Basic/Debug.h" #include "swift/Basic/InlineBitfield.h" #include "swift/Basic/NullablePtr.h" #include "swift/Basic/OptionalEnum.h" #include "swift/Basic/Range.h" #include "swift/Basic/Located.h" #include "llvm/ADT/DenseSet.h" #include "llvm/Support/TrailingObjects.h" #include <type_traits> namespace swift { enum class AccessSemantics : unsigned char; class AccessorDecl; class ApplyExpr; class AvailabilityContext; class GenericEnvironment; class ArchetypeType; class ASTContext; struct ASTNode; class ASTPrinter; class ASTWalker; class ConstructorDecl; class DestructorDecl; class DiagnosticEngine; class DynamicSelfType; class Type; class Expr; struct ExternalSourceLocs; class CaptureListExpr; class DeclRefExpr; class ForeignAsyncConvention; class ForeignErrorConvention; class LiteralExpr; class BraceStmt; class DeclAttributes; class GenericContext; class GenericParamList; class GenericSignature; class GenericTypeParamDecl; class GenericTypeParamType; class ModuleDecl; class NamedPattern; class EnumCaseDecl; class EnumElementDecl; class ParameterList; class ParameterTypeFlags; class Pattern; struct PrintOptions; struct PropertyWrapperAuxiliaryVariables; class PropertyWrapperInitializerInfo; struct PropertyWrapperTypeInfo; struct PropertyWrapperMutability; class ProtocolDecl; class PolymorphicEffectRequirementList; class ProtocolType; struct RawComment; enum class ResilienceExpansion : unsigned; enum class EffectKind : uint8_t; enum class PolymorphicEffectKind : uint8_t; class TrailingWhereClause; class TypeAliasDecl; class Stmt; class SubscriptDecl; class UnboundGenericType; class ValueDecl; class VarDecl; class OpaqueReturnTypeRepr; namespace ast_scope { class AbstractPatternEntryScope; class PatternEntryDeclScope; class PatternEntryInitializerScope; } // namespace ast_scope enum class DeclKind : uint8_t { #define DECL(Id, Parent) Id, #define LAST_DECL(Id) Last_Decl = Id, #define DECL_RANGE(Id, FirstId, LastId) \ First_##Id##Decl = FirstId, Last_##Id##Decl = LastId, #include "swift/AST/DeclNodes.def" }; enum : unsigned { NumDeclKindBits = countBitsUsed(static_cast<unsigned>(DeclKind::Last_Decl)) }; /// Fine-grained declaration kind that provides a description of the /// kind of entity a declaration represents, as it would be used in /// diagnostics. /// /// For example, \c FuncDecl is a single declaration class, but it has /// several descriptive entries depending on whether it is an /// operator, global function, local function, method, (observing) /// accessor, etc. enum class DescriptiveDeclKind : uint8_t { Import, Extension, EnumCase, TopLevelCode, IfConfig, PoundDiagnostic, PatternBinding, Var, Param, Let, Property, StaticProperty, ClassProperty, InfixOperator, PrefixOperator, PostfixOperator, PrecedenceGroup, TypeAlias, GenericTypeParam, AssociatedType, Type, Enum, Struct, Class, Protocol, GenericEnum, GenericStruct, GenericClass, GenericType, Subscript, StaticSubscript, ClassSubscript, Constructor, Destructor, LocalFunction, GlobalFunction, OperatorFunction, Method, StaticMethod, ClassMethod, Getter, Setter, Addressor, MutableAddressor, ReadAccessor, ModifyAccessor, WillSet, DidSet, EnumElement, Module, MissingMember, Requirement, OpaqueResultType, OpaqueVarType }; /// Describes which spelling was used in the source for the 'static' or 'class' /// keyword. enum class StaticSpellingKind : uint8_t { None, KeywordStatic, KeywordClass, }; /// Keeps track of whether an enum has cases that have associated values. enum class AssociatedValueCheck { /// We have not yet checked. Unchecked, /// The enum contains no cases or all cases contain no associated values. NoAssociatedValues, /// The enum contains at least one case with associated values. HasAssociatedValues, }; /// Diagnostic printing of \c StaticSpellingKind. llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, StaticSpellingKind SSK); /// Encapsulation of the overload signature of a given declaration, /// which is used to determine uniqueness of a declaration within a /// given context. /// /// Two definitions in the same context may not have the same overload /// signature. struct OverloadSignature { /// The full name of the declaration. DeclName Name; /// The kind of unary operator. UnaryOperatorKind UnaryOperator; /// Whether this is an instance member. unsigned IsInstanceMember : 1; /// Whether this is a variable. unsigned IsVariable : 1; /// Whether this is a function. unsigned IsFunction : 1; /// Whether this is an async function. unsigned IsAsyncFunction : 1; /// Whether this is a enum element. unsigned IsEnumElement : 1; /// Whether this is a nominal type. unsigned IsNominal : 1; /// Whether this is a type alias. unsigned IsTypeAlias : 1; /// Whether this signature is part of a protocol extension. unsigned InProtocolExtension : 1; /// Whether this signature is of a member defined in an extension of a generic /// type. unsigned InExtensionOfGenericType : 1; /// Whether this declaration has an opaque return type. unsigned HasOpaqueReturnType : 1; OverloadSignature() : UnaryOperator(UnaryOperatorKind::None), IsInstanceMember(false), IsVariable(false), IsFunction(false), IsAsyncFunction(false), InProtocolExtension(false), InExtensionOfGenericType(false), HasOpaqueReturnType(false) { } }; /// Determine whether two overload signatures conflict. /// /// \param sig1 The overload signature of the first declaration. /// \param sig2 The overload signature of the second declaration. /// \param skipProtocolExtensionCheck If \c true, members of protocol extensions /// will be allowed to conflict with members of protocol declarations. bool conflicting(const OverloadSignature& sig1, const OverloadSignature& sig2, bool skipProtocolExtensionCheck = false); /// Determine whether two overload signatures and overload types conflict. /// /// \param ctx The AST context. /// \param sig1 The overload signature of the first declaration. /// \param sig1Type The overload type of the first declaration. /// \param sig2 The overload signature of the second declaration. /// \param sig2Type The overload type of the second declaration. /// \param wouldConflictInSwift5 If non-null, the referenced boolean will be set /// to \c true iff the function returns \c false for this version of /// Swift, but the given overloads will conflict in Swift 5 mode. /// \param skipProtocolExtensionCheck If \c true, members of protocol extensions /// will be allowed to conflict with members of protocol declarations. bool conflicting(ASTContext &ctx, const OverloadSignature& sig1, CanType sig1Type, const OverloadSignature& sig2, CanType sig2Type, bool *wouldConflictInSwift5 = nullptr, bool skipProtocolExtensionCheck = false); /// The kind of artificial main to generate. enum class ArtificialMainKind : uint8_t { NSApplicationMain, UIApplicationMain, TypeMain, }; /// Decl - Base class for all declarations in Swift. class alignas(1 << DeclAlignInBits) Decl { protected: union { uint64_t OpaqueBits; SWIFT_INLINE_BITFIELD_BASE(Decl, bitmax(NumDeclKindBits,8)+1+1+1+1+1, Kind : bitmax(NumDeclKindBits,8), /// Whether this declaration is invalid. Invalid : 1, /// Whether this declaration was implicitly created, e.g., /// an implicit constructor in a struct. Implicit : 1, /// Whether this declaration was mapped directly from a Clang AST. /// /// Use getClangNode() to retrieve the corresponding Clang AST. FromClang : 1, /// Whether this declaration was added to the surrounding /// DeclContext of an active #if config clause. EscapedFromIfConfig : 1, /// Whether this declaration is syntactically scoped inside of /// a local context, but should behave like a top-level /// declaration for name lookup purposes. This is used by /// lldb. Hoisted : 1 ); SWIFT_INLINE_BITFIELD_FULL(PatternBindingDecl, Decl, 1+1+2+16, /// Whether this pattern binding declares static variables. IsStatic : 1, /// Whether this pattern binding is synthesized by the debugger. IsDebugger : 1, /// Whether 'static' or 'class' was used. StaticSpelling : 2, : NumPadBits, /// The number of pattern binding declarations. NumPatternEntries : 16 ); SWIFT_INLINE_BITFIELD_FULL(EnumCaseDecl, Decl, 32, : NumPadBits, /// The number of tail-allocated element pointers. NumElements : 32 ); SWIFT_INLINE_BITFIELD(ValueDecl, Decl, 1+1+1+1, AlreadyInLookupTable : 1, /// Whether we have already checked whether this declaration is a /// redeclaration. CheckedRedeclaration : 1, /// Whether the decl can be accessed by swift users; for instance, /// a.storage for lazy var a is a decl that cannot be accessed. IsUserAccessible : 1, /// Whether this member was synthesized as part of a derived /// protocol conformance. Synthesized : 1 ); SWIFT_INLINE_BITFIELD(AbstractStorageDecl, ValueDecl, 1, /// Whether this property is a type property (currently unfortunately /// called 'static'). IsStatic : 1 ); SWIFT_INLINE_BITFIELD(VarDecl, AbstractStorageDecl, 1+1+1+1+1+1, /// Encodes whether this is a 'let' binding. Introducer : 1, /// Whether this declaration captures the 'self' param under the same name. IsSelfParamCapture : 1, /// Whether this is a property used in expressions in the debugger. /// It is up to the debugger to instruct SIL how to access this variable. IsDebuggerVar : 1, /// Whether this is the backing storage for a lazy property. IsLazyStorageProperty : 1, /// Whether this is the backing storage for a property wrapper. IsPropertyWrapperBackingProperty : 1, /// Whether this is a lazily top-level global variable from the main file. IsTopLevelGlobal : 1 ); SWIFT_INLINE_BITFIELD(ParamDecl, VarDecl, 1+2+NumDefaultArgumentKindBits, /// Whether we've computed the specifier yet. SpecifierComputed : 1, /// The specifier associated with this parameter. This determines /// the storage semantics of the value e.g. mutability. Specifier : 2, /// Information about a symbolic default argument, like #file. defaultArgumentKind : NumDefaultArgumentKindBits ); SWIFT_INLINE_BITFIELD(SubscriptDecl, VarDecl, 2, StaticSpelling : 2 ); SWIFT_INLINE_BITFIELD(AbstractFunctionDecl, ValueDecl, 3+8+1+1+1+1+1+1, /// \see AbstractFunctionDecl::BodyKind BodyKind : 3, /// Import as member status. IAMStatus : 8, /// Whether the function has an implicit 'self' parameter. HasImplicitSelfDecl : 1, /// Whether we are overridden later. Overridden : 1, /// Whether the function is async. Async : 1, /// Whether the function body throws. Throws : 1, /// Whether this member's body consists of a single expression. HasSingleExpressionBody : 1, /// Whether peeking into this function detected nested type declarations. /// This is set when skipping over the decl at parsing. HasNestedTypeDeclarations : 1 ); SWIFT_INLINE_BITFIELD(FuncDecl, AbstractFunctionDecl, 1+1+2+1+1+2+1, /// Whether we've computed the 'static' flag yet. IsStaticComputed : 1, /// Whether this function is a 'static' method. IsStatic : 1, /// Whether 'static' or 'class' was used. StaticSpelling : 2, /// Whether we are statically dispatched even if overridable ForcedStaticDispatch : 1, /// Whether we've computed the 'self' access kind yet. SelfAccessComputed : 1, /// Backing bits for 'self' access kind. SelfAccess : 2, /// Whether this is a top-level function which should be treated /// as if it were in local context for the purposes of capture /// analysis. HasTopLevelLocalContextCaptures : 1 ); SWIFT_INLINE_BITFIELD(AccessorDecl, FuncDecl, 4 + 1 + 1, /// The kind of accessor this is. AccessorKind : 4, /// Whether the accessor is transparent. IsTransparent : 1, /// Whether we have computed the above. IsTransparentComputed : 1 ); SWIFT_INLINE_BITFIELD(ConstructorDecl, AbstractFunctionDecl, 1+1, /// Whether this constructor can fail, by building an Optional type. Failable : 1, /// Whether this initializer is a stub placed into a subclass to /// catch invalid delegations to a designated initializer not /// overridden by the subclass. A stub will always trap at runtime. /// /// Initializer stubs can be invoked from Objective-C or through /// the Objective-C runtime; there is no way to directly express /// an object construction that will invoke a stub. HasStubImplementation : 1 ); SWIFT_INLINE_BITFIELD_EMPTY(TypeDecl, ValueDecl); SWIFT_INLINE_BITFIELD_EMPTY(AbstractTypeParamDecl, TypeDecl); SWIFT_INLINE_BITFIELD_FULL(GenericTypeParamDecl, AbstractTypeParamDecl, 16+16, : NumPadBits, Depth : 16, Index : 16 ); SWIFT_INLINE_BITFIELD_EMPTY(GenericTypeDecl, TypeDecl); SWIFT_INLINE_BITFIELD(TypeAliasDecl, GenericTypeDecl, 1+1, /// Whether the typealias forwards perfectly to its underlying type. IsCompatibilityAlias : 1, /// Whether this was a global typealias synthesized by the debugger. IsDebuggerAlias : 1 ); SWIFT_INLINE_BITFIELD(NominalTypeDecl, GenericTypeDecl, 1+1+1, /// Whether we have already added implicitly-defined initializers /// to this declaration. AddedImplicitInitializers : 1, /// Whether there is are lazily-loaded conformances for this nominal type. HasLazyConformances : 1, /// Whether this nominal type is having its semantic members resolved. IsComputingSemanticMembers : 1 ); SWIFT_INLINE_BITFIELD_FULL(ProtocolDecl, NominalTypeDecl, 1+1+1+1+1+1+1+1+1+8+16, /// Whether the \c RequiresClass bit is valid. RequiresClassValid : 1, /// Whether this is a class-bounded protocol. RequiresClass : 1, /// Whether the \c ExistentialConformsToSelf bit is valid. ExistentialConformsToSelfValid : 1, /// Whether the existential of this protocol conforms to itself. ExistentialConformsToSelf : 1, /// Whether the \c ExistentialTypeSupported bit is valid. ExistentialTypeSupportedValid : 1, /// Whether the existential of this protocol can be represented. ExistentialTypeSupported : 1, /// True if the protocol has requirements that cannot be satisfied (e.g. /// because they could not be imported from Objective-C). HasMissingRequirements : 1, /// Whether we've computed the inherited protocols list yet. InheritedProtocolsValid : 1, /// Whether we have a lazy-loaded requirement signature. HasLazyRequirementSignature : 1, : NumPadBits, /// If this is a compiler-known protocol, this will be a KnownProtocolKind /// value, plus one. Otherwise, it will be 0. KnownProtocol : 8, // '8' for speed. This only needs 6. /// The number of requirements in the requirement signature. NumRequirementsInSignature : 16 ); SWIFT_INLINE_BITFIELD(ClassDecl, NominalTypeDecl, 1+1+2+1+1+1+1+1+1, /// Whether this class inherits its superclass's convenience initializers. InheritsSuperclassInits : 1, ComputedInheritsSuperclassInits : 1, /// \see ClassDecl::ForeignKind RawForeignKind : 2, HasMissingDesignatedInitializers : 1, ComputedHasMissingDesignatedInitializers : 1, HasMissingVTableEntries : 1, ComputedHasMissingVTableEntries : 1, /// Whether instances of this class are incompatible /// with weak and unowned references. IsIncompatibleWithWeakReferences : 1, /// Set when the class represents an actor IsActor : 1 ); SWIFT_INLINE_BITFIELD( StructDecl, NominalTypeDecl, 1 + 1, /// True if this struct has storage for fields that aren't accessible in /// Swift. HasUnreferenceableStorage : 1, /// True if this struct is imported from C++ and does not have trivial value witness functions. IsCxxNonTrivial : 1); SWIFT_INLINE_BITFIELD(EnumDecl, NominalTypeDecl, 2+1, /// True if the enum has cases and at least one case has associated values. HasAssociatedValues : 2, /// True if the enum has at least one case that has some availability /// attribute. A single bit because it's lazily computed along with the /// HasAssociatedValues bit. HasAnyUnavailableValues : 1 ); SWIFT_INLINE_BITFIELD(ModuleDecl, TypeDecl, 1+1+1+1+1+1+1+1+1+1+1, /// If the module is compiled as static library. StaticLibrary : 1, /// If the module was or is being compiled with `-enable-testing`. TestingEnabled : 1, /// If the module failed to load FailedToLoad : 1, /// Whether the module is resilient. /// /// \sa ResilienceStrategy RawResilienceStrategy : 1, /// Whether all imports have been resolved. Used to detect circular imports. HasResolvedImports : 1, /// If the module was or is being compiled with `-enable-private-imports`. PrivateImportsEnabled : 1, /// If the module is compiled with `-enable-implicit-dynamic`. ImplicitDynamicEnabled : 1, /// Whether the module is a system module. IsSystemModule : 1, /// Whether the module was imported from Clang (or, someday, maybe another /// language). IsNonSwiftModule : 1, /// Whether this module is the main module. IsMainModule : 1, /// Whether this module has incremental dependency information available. HasIncrementalInfo : 1 ); SWIFT_INLINE_BITFIELD(PrecedenceGroupDecl, Decl, 1+2, /// Is this an assignment operator? IsAssignment : 1, /// The group's associativity. A value of the Associativity enum. Associativity : 2 ); SWIFT_INLINE_BITFIELD(ImportDecl, Decl, 3+8, ImportKind : 3, /// The number of elements in this path. NumPathElements : 8 ); SWIFT_INLINE_BITFIELD(ExtensionDecl, Decl, 3+1, /// An encoding of the default and maximum access level for this extension. /// /// This is encoded as (1 << (maxAccess-1)) | (1 << (defaultAccess-1)), /// which works because the maximum is always greater than or equal to the /// default, and 'private' is never used. 0 represents an uncomputed value. DefaultAndMaxAccessLevel : 3, /// Whether there is are lazily-loaded conformances for this extension. HasLazyConformances : 1 ); SWIFT_INLINE_BITFIELD(IfConfigDecl, Decl, 1, /// Whether this decl is missing its closing '#endif'. HadMissingEnd : 1 ); SWIFT_INLINE_BITFIELD(PoundDiagnosticDecl, Decl, 1+1, /// `true` if the diagnostic is an error, `false` if it's a warning. IsError : 1, /// Whether this diagnostic has already been emitted. HasBeenEmitted : 1 ); SWIFT_INLINE_BITFIELD(MissingMemberDecl, Decl, 1+2, NumberOfFieldOffsetVectorEntries : 1, NumberOfVTableEntries : 2 ); } Bits; // Storage for the declaration attributes. DeclAttributes Attrs; /// The next declaration in the list of declarations within this /// member context. Decl *NextDecl = nullptr; friend class DeclIterator; friend class IterableDeclContext; friend class MemberLookupTable; friend class DeclDeserializer; private: llvm::PointerUnion<DeclContext *, ASTContext *> Context; Decl(const Decl&) = delete; void operator=(const Decl&) = delete; SourceLoc getLocFromSource() const; /// Returns the serialized locations of this declaration from the /// corresponding .swiftsourceinfo file. "Empty" (ie. \c BufferID of 0, an /// invalid \c Loc, and empty \c DocRanges) if either there is no /// .swiftsourceinfo or the buffer could not be created, eg. if the file /// no longer exists. const ExternalSourceLocs *getSerializedLocs() const; /// Directly set the invalid bit void setInvalidBit(); protected: Decl(DeclKind kind, llvm::PointerUnion<DeclContext *, ASTContext *> context) : Context(context) { Bits.OpaqueBits = 0; Bits.Decl.Kind = unsigned(kind); Bits.Decl.Invalid = false; Bits.Decl.Implicit = false; Bits.Decl.FromClang = false; Bits.Decl.EscapedFromIfConfig = false; Bits.Decl.Hoisted = false; } /// Get the Clang node associated with this declaration. ClangNode getClangNodeImpl() const; /// Set the Clang node associated with this declaration. void setClangNode(ClangNode Node); void updateClangNode(ClangNode node) { assert(hasClangNode()); setClangNode(node); } friend class ClangImporter; DeclContext *getDeclContextForModule() const; public: DeclKind getKind() const { return DeclKind(Bits.Decl.Kind); } /// Retrieve the name of the given declaration kind. /// /// This name should only be used for debugging dumps and other /// developer aids, and should never be part of a diagnostic or exposed /// to the user of the compiler in any way. static StringRef getKindName(DeclKind K); /// Retrieve the descriptive kind for this declaration. DescriptiveDeclKind getDescriptiveKind() const; /// Produce a name for the given descriptive declaration kind, which /// is suitable for use in diagnostics. static StringRef getDescriptiveKindName(DescriptiveDeclKind K); /// Whether swift users should be able to access this decl. For instance, /// var a.storage for lazy var a is an inaccessible decl. An inaccessible decl /// has to be implicit; but an implicit decl does not have to be inaccessible, /// for instance, self. bool isUserAccessible() const; /// Determine if the decl can have a comment. If false, a comment will /// not be serialized. bool canHaveComment() const; LLVM_READONLY DeclContext *getDeclContext() const { if (auto dc = Context.dyn_cast<DeclContext *>()) return dc; return getDeclContextForModule(); } void setDeclContext(DeclContext *DC); /// Retrieve the innermost declaration context corresponding to this /// declaration, which will either be the declaration itself (if it's /// also a declaration context) or its declaration context. DeclContext *getInnermostDeclContext() const; /// Retrieve the module in which this declaration resides. LLVM_READONLY ModuleDecl *getModuleContext() const; /// getASTContext - Return the ASTContext that this decl lives in. LLVM_READONLY ASTContext &getASTContext() const { if (auto dc = Context.dyn_cast<DeclContext *>()) return dc->getASTContext(); return *Context.get<ASTContext *>(); } const DeclAttributes &getAttrs() const { return Attrs; } DeclAttributes &getAttrs() { return Attrs; } /// Returns the innermost enclosing decl with an availability annotation. const Decl *getInnermostDeclWithAvailability() const; /// Returns the introduced OS version in the given platform kind specified /// by @available attribute. /// This function won't consider the parent context to get the information. Optional<llvm::VersionTuple> getIntroducedOSVersion(PlatformKind Kind) const; /// Returns the starting location of the entire declaration. SourceLoc getStartLoc() const { return getSourceRange().Start; } /// Returns the end location of the entire declaration. SourceLoc getEndLoc() const { return getSourceRange().End; } /// Returns the preferred location when referring to declarations /// in diagnostics. SourceLoc getLoc(bool SerializedOK = true) const; /// Returns the source range of the entire declaration. SourceRange getSourceRange() const; /// Returns the source range of the declaration including its attributes. SourceRange getSourceRangeIncludingAttrs() const; SourceLoc TrailingSemiLoc; /// Returns the appropriate kind of entry point to generate for this class, /// based on its attributes. /// /// It is an error to call this on a type that does not have either an /// *ApplicationMain or an main attribute. ArtificialMainKind getArtificialMainKind() const; SWIFT_DEBUG_DUMP; SWIFT_DEBUG_DUMPER(dump(const char *filename)); void dump(raw_ostream &OS, unsigned Indent = 0) const; /// Pretty-print the given declaration. /// /// \param OS Output stream to which the declaration will be printed. void print(raw_ostream &OS) const; void print(raw_ostream &OS, const PrintOptions &Opts) const; /// Pretty-print the given declaration. /// /// \param Printer ASTPrinter object. /// /// \param Opts Options to control how pretty-printing is performed. /// /// \returns true if the declaration was printed or false if the print options /// required the declaration to be skipped from printing. bool print(ASTPrinter &Printer, const PrintOptions &Opts) const; /// Determine whether this declaration should be printed when /// encountered in its declaration context's list of members. bool shouldPrintInContext(const PrintOptions &PO) const; bool walk(ASTWalker &walker); /// Return whether this declaration has been determined invalid. bool isInvalid() const; /// Mark this declaration invalid. void setInvalid(); /// Determine whether this declaration was implicitly generated by the /// compiler (rather than explicitly written in source code). bool isImplicit() const { return Bits.Decl.Implicit; } /// Mark this declaration as implicit. void setImplicit(bool implicit = true) { Bits.Decl.Implicit = implicit; } /// Determine whether this declaration is syntactically scoped inside of /// a local context, but should behave like a top-level declaration /// for name lookup purposes. This is used by lldb. bool isHoisted() const { return Bits.Decl.Hoisted; } /// Set whether this declaration should be syntactically scoped inside /// of a local context, but should behave like a top-level declaration, /// but should behave like a top-level declaration. This is used by lldb. void setHoisted(bool hoisted = true) { Bits.Decl.Hoisted = hoisted; } public: bool escapedFromIfConfig() const { return Bits.Decl.EscapedFromIfConfig; } void setEscapedFromIfConfig(bool Escaped) { Bits.Decl.EscapedFromIfConfig = Escaped; } /// \returns the unparsed comment attached to this declaration. RawComment getRawComment(bool SerializedOK = false) const; Optional<StringRef> getGroupName() const; Optional<StringRef> getSourceFileName() const; Optional<unsigned> getSourceOrder() const; /// \returns the brief comment attached to this declaration. StringRef getBriefComment() const; /// Returns true if there is a Clang AST node associated /// with self. bool hasClangNode() const { return Bits.Decl.FromClang; } /// Retrieve the Clang AST node from which this declaration was /// synthesized, if any. LLVM_READONLY ClangNode getClangNode() const { if (!Bits.Decl.FromClang) return ClangNode(); return getClangNodeImpl(); } /// Retrieve the Clang declaration from which this declaration was /// synthesized, if any. LLVM_READONLY const clang::Decl *getClangDecl() const { if (!Bits.Decl.FromClang) return nullptr; return getClangNodeImpl().getAsDecl(); } /// Retrieve the Clang macro from which this declaration was /// synthesized, if any. LLVM_READONLY const clang::MacroInfo *getClangMacro() { if (!Bits.Decl.FromClang) return nullptr; return getClangNodeImpl().getAsMacro(); } /// Return the GenericContext if the Decl has one. LLVM_READONLY const GenericContext *getAsGenericContext() const; bool hasUnderscoredNaming() const; bool isPrivateStdlibDecl(bool treatNonBuiltinProtocolsAsPublic = true) const; /// Check if this is a declaration defined at the top level of the Swift module bool isStdlibDecl() const; AvailabilityContext getAvailabilityForLinkage() const; /// Whether this declaration or one of its outer contexts has the /// @_weakLinked attribute. bool isAlwaysWeakImported() const; /// Whether this declaration is weak-imported from the given module, /// either because of the presence of the @_weakLinked attribute, or /// because of availability. /// /// Note that \p fromModule should either be the "main module" or /// nullptr. (This is because when it is non-null, we query the /// current deployment target, and not the deployment target that /// the module was built with.) /// /// If \p fromModule is the main module, this returns false when the /// declaration is part of the main module, or if the declaration is /// at least as available as the current deployment target. /// /// If \p fromModule is null, we instead return true if the /// declaration is meant to be weak linked with _some_ deployment /// target; that is, the presence of the @_weakLinked attribute or /// any kind of availability is enough, irrespective of the current /// deployment target. bool isWeakImported(ModuleDecl *fromModule) const; /// Returns true if the nature of this declaration allows overrides. /// Note that this does not consider whether it is final or whether /// the class it's on is final. /// /// If this returns true, the decl can be safely casted to ValueDecl. bool isPotentiallyOverridable() const; /// Retrieve the global actor attribute that applies to this declaration, /// if any. /// /// This is the "raw" global actor attribute as written directly on the /// declaration, along with the nominal type declaration to which it refers, /// without any inference rules applied. Optional<std::pair<CustomAttr *, NominalTypeDecl *>> getGlobalActorAttr() const; /// If an alternative module name is specified for this decl, e.g. using /// @_originalDefinedIn attribute, this function returns this module name. StringRef getAlternateModuleName() const; // Is this Decl an SPI? It can be directly marked with @_spi or is defined in // an @_spi context. bool isSPI() const; // List the SPI groups declared with @_spi or inherited by this decl. // // SPI groups are inherited from the parent contexts only if the local decl // doesn't declare any @_spi. ArrayRef<Identifier> getSPIGroups() const; /// Emit a diagnostic tied to this declaration. template<typename ...ArgTypes> InFlightDiagnostic diagnose( Diag<ArgTypes...> ID, typename detail::PassArgument<ArgTypes>::type... Args) const { return getDiags().diagnose(this, ID, std::move(Args)...); } /// Retrieve the diagnostic engine for diagnostics emission. LLVM_READONLY DiagnosticEngine &getDiags() const; // Make vanilla new/delete illegal for Decls. void *operator new(size_t Bytes) = delete; void operator delete(void *Data) = delete; // Only allow allocation of Decls using the allocator in ASTContext // or by doing a placement new. void *operator new(size_t Bytes, const ASTContext &C, unsigned Alignment = alignof(Decl)); void *operator new(size_t Bytes, void *Mem) { assert(Mem); return Mem; } }; /// Allocates memory for a Decl with the given \p baseSize. If necessary, /// it includes additional space immediately preceding the Decl for a ClangNode. /// \note \p baseSize does not need to include space for a ClangNode if /// requested -- the necessary space will be added automatically. template <typename DeclTy, typename AllocatorTy> void *allocateMemoryForDecl(AllocatorTy &allocator, size_t baseSize, bool includeSpaceForClangNode) { static_assert(alignof(DeclTy) >= sizeof(void *), "A pointer must fit in the alignment of the DeclTy!"); size_t size = baseSize; if (includeSpaceForClangNode) size += alignof(DeclTy); void *mem = allocator.Allocate(size, alignof(DeclTy)); if (includeSpaceForClangNode) mem = reinterpret_cast<char *>(mem) + alignof(DeclTy); return mem; } // A private class for forcing exact field layout. class alignas(8) _GenericContext { // Not really public. See GenericContext. public: llvm::PointerIntPair<GenericParamList *, 1, bool> GenericParamsAndBit; /// The trailing where clause. /// /// Note that this is not currently serialized, because semantic analysis /// moves the trailing where clause into the generic parameter list. TrailingWhereClause *TrailingWhere = nullptr; /// The generic signature of this declaration. llvm::PointerIntPair<GenericSignature, 1, bool> GenericSigAndBit; }; class GenericContext : private _GenericContext, public DeclContext { friend class GenericParamListRequest; friend class GenericSignatureRequest; protected: GenericContext(DeclContextKind Kind, DeclContext *Parent, GenericParamList *Params); public: /// Retrieve the set of parameters to a generic context, or null if /// this context is not generic. GenericParamList *getGenericParams() const; /// Retrieve the generic parameters as written in source. Unlike /// getGenericParams() this will not synthesize generic parameters for /// extensions, protocols and certain type aliases. GenericParamList *getParsedGenericParams() const; /// Determine whether this context has generic parameters /// of its own. /// /// \code /// class C<T> { /// func f1() {} // isGeneric == false /// func f2<T>() {} // isGeneric == true /// } /// /// protocol P { // isGeneric == true due to implicit Self param /// func p() // isGeneric == false /// } /// \endcode bool isGeneric() const { return getGenericParams() != nullptr; } bool hasComputedGenericSignature() const; bool isComputingGenericSignature() const; /// Retrieve the trailing where clause for this extension, if any. TrailingWhereClause *getTrailingWhereClause() const { return TrailingWhere; } /// Set the trailing where clause for this extension. void setTrailingWhereClause(TrailingWhereClause *trailingWhereClause) { TrailingWhere = trailingWhereClause; } /// Retrieve the generic signature for this context. GenericSignature getGenericSignature() const; /// Retrieve the generic context for this context. GenericEnvironment *getGenericEnvironment() const; /// Retrieve the innermost generic parameter types. TypeArrayView<GenericTypeParamType> getInnermostGenericParamTypes() const; /// Retrieve the generic requirements. ArrayRef<Requirement> getGenericRequirements() const; /// Set the generic signature of this context. void setGenericSignature(GenericSignature genericSig); /// Retrieve the position of any where clause for this context's /// generic parameters. SourceRange getGenericTrailingWhereClauseSourceRange() const; }; static_assert(sizeof(_GenericContext) + sizeof(DeclContext) == sizeof(GenericContext), "Please add fields to _GenericContext"); /// ImportDecl - This represents a single import declaration, e.g.: /// import Swift /// import typealias Swift.Int class ImportDecl final : public Decl, private llvm::TrailingObjects<ImportDecl, ImportPath::Element> { friend TrailingObjects; friend class Decl; SourceLoc ImportLoc; SourceLoc KindLoc; /// The resolved module. ModuleDecl *Mod = nullptr; ImportDecl(DeclContext *DC, SourceLoc ImportLoc, ImportKind K, SourceLoc KindLoc, ImportPath Path); public: static ImportDecl *create(ASTContext &C, DeclContext *DC, SourceLoc ImportLoc, ImportKind Kind, SourceLoc KindLoc, ImportPath Path, ClangNode ClangN = ClangNode()); /// Returns the import kind that is most appropriate for \p VD. /// /// Note that this will never return \c Type; an imported typealias will use /// the more specific kind from its underlying type. static ImportKind getBestImportKind(const ValueDecl *VD); /// Returns the most appropriate import kind for the given list of decls. /// /// If the list is non-homogeneous, or if there is more than one decl that /// cannot be overloaded, returns None. static Optional<ImportKind> findBestImportKind(ArrayRef<ValueDecl *> Decls); ImportKind getImportKind() const { return static_cast<ImportKind>(Bits.ImportDecl.ImportKind); } ImportPath getImportPath() const { return ImportPath({ getTrailingObjects<ImportPath::Element>(), static_cast<size_t>(Bits.ImportDecl.NumPathElements) }); } ImportPath::Module getModulePath() const { return getImportPath().getModulePath(getImportKind()); } ImportPath::Access getAccessPath() const { return getImportPath().getAccessPath(getImportKind()); } bool isExported() const { return getAttrs().hasAttribute<ExportedAttr>(); } ModuleDecl *getModule() const { return Mod; } void setModule(ModuleDecl *M) { Mod = M; } /// For a scoped import such as 'import class Foundation.NSString', retrieve /// the decls it references. Otherwise, returns an empty array. ArrayRef<ValueDecl *> getDecls() const; const clang::Module *getClangModule() const { return getClangNode().getClangModule(); } SourceLoc getStartLoc() const { return ImportLoc; } SourceLoc getLocFromSource() const { return getImportPath().getSourceRange().Start; } SourceRange getSourceRange() const { return SourceRange(ImportLoc, getImportPath().getSourceRange().End); } SourceLoc getKindLoc() const { return KindLoc; } static bool classof(const Decl *D) { return D->getKind() == DeclKind::Import; } }; /// An entry in the "inherited" list of a type or extension. struct InheritedEntry : public TypeLoc { /// Whether there was an @unchecked attribute. bool isUnchecked = false; InheritedEntry(const TypeLoc &typeLoc); InheritedEntry(const TypeLoc &typeLoc, bool isUnchecked) : TypeLoc(typeLoc), isUnchecked(isUnchecked) { } }; /// ExtensionDecl - This represents a type extension containing methods /// associated with the type. This is not a ValueDecl and has no Type because /// there are no runtime values of the Extension's type. class ExtensionDecl final : public GenericContext, public Decl, public IterableDeclContext { SourceLoc ExtensionLoc; // Location of 'extension' keyword. SourceRange Braces; /// The type being extended. TypeRepr *ExtendedTypeRepr; /// The nominal type being extended. /// /// The bit indicates whether binding has been attempted. The pointer can be /// null if either no binding was attempted or if binding could not find the /// extended nominal. llvm::PointerIntPair<NominalTypeDecl *, 1, bool> ExtendedNominal; ArrayRef<InheritedEntry> Inherited; /// The next extension in the linked list of extensions. /// /// The bit indicates whether this extension has been resolved to refer to /// a known nominal type. llvm::PointerIntPair<ExtensionDecl *, 1, bool> NextExtension = {nullptr, false}; /// Note that we have added a member into the iterable declaration context. void addedMember(Decl *member); friend class ExtensionIterator; friend class NominalTypeDecl; friend class MemberLookupTable; friend class ConformanceLookupTable; friend class IterableDeclContext; ExtensionDecl(SourceLoc extensionLoc, TypeRepr *extendedType, ArrayRef<InheritedEntry> inherited, DeclContext *parent, TrailingWhereClause *trailingWhereClause); /// Retrieve the conformance loader (if any), and removing it in the /// same operation. The caller is responsible for loading the /// conformances. std::pair<LazyMemberLoader *, uint64_t> takeConformanceLoader() { if (!Bits.ExtensionDecl.HasLazyConformances) return { nullptr, 0 }; return takeConformanceLoaderSlow(); } /// Slow path for \c takeConformanceLoader(). std::pair<LazyMemberLoader *, uint64_t> takeConformanceLoaderSlow(); friend class ExtendedNominalRequest; friend class Decl; public: using Decl::getASTContext; /// Create a new extension declaration. static ExtensionDecl *create(ASTContext &ctx, SourceLoc extensionLoc, TypeRepr *extendedType, ArrayRef<InheritedEntry> inherited, DeclContext *parent, TrailingWhereClause *trailingWhereClause, ClangNode clangNode = ClangNode()); SourceLoc getStartLoc() const { return ExtensionLoc; } SourceLoc getLocFromSource() const { return ExtensionLoc; } SourceRange getSourceRange() const { return { ExtensionLoc, Braces.End }; } SourceRange getBraces() const { return Braces; } void setBraces(SourceRange braces) { Braces = braces; } bool hasBeenBound() const { return ExtendedNominal.getInt(); } void setExtendedNominal(NominalTypeDecl *n) { ExtendedNominal.setPointerAndInt(n, true); } /// Retrieve the type being extended. /// /// Only use this entry point when the complete type, as spelled in the source, /// is required. For most clients, \c getExtendedNominal(), which provides /// only the \c NominalTypeDecl, will suffice. Type getExtendedType() const; /// Retrieve the nominal type declaration that is being extended. /// Will trip an assertion if the declaration has not already been computed. /// In order to fail fast when type checking work is attempted /// before extension binding has taken place. NominalTypeDecl *getExtendedNominal() const; /// Compute the nominal type declaration that is being extended. NominalTypeDecl *computeExtendedNominal() const; /// \c hasBeenBound means nothing if this extension can never been bound /// because it is not at the top level. bool canNeverBeBound() const; bool hasValidParent() const; /// Determine whether this extension has already been bound to a nominal /// type declaration. bool alreadyBoundToNominal() const { return NextExtension.getInt(); } /// Retrieve the extended type definition as written in the source, if it exists. /// /// Repr would not be available if the extension was been loaded /// from a serialized module. TypeRepr *getExtendedTypeRepr() const { return ExtendedTypeRepr; } /// Retrieve the set of protocols that this type inherits (i.e, /// explicitly conforms to). ArrayRef<InheritedEntry> getInherited() const { return Inherited; } void setInherited(ArrayRef<InheritedEntry> i) { Inherited = i; } bool hasDefaultAccessLevel() const { return Bits.ExtensionDecl.DefaultAndMaxAccessLevel != 0; } uint8_t getDefaultAndMaxAccessLevelBits() const { return Bits.ExtensionDecl.DefaultAndMaxAccessLevel; } void setDefaultAndMaxAccessLevelBits(AccessLevel defaultAccess, AccessLevel maxAccess) { Bits.ExtensionDecl.DefaultAndMaxAccessLevel = (1 << (static_cast<unsigned>(defaultAccess) - 1)) | (1 << (static_cast<unsigned>(maxAccess) - 1)); } AccessLevel getDefaultAccessLevel() const; AccessLevel getMaxAccessLevel() const; void setDefaultAndMaxAccess(AccessLevel defaultAccess, AccessLevel maxAccess) { assert(!hasDefaultAccessLevel() && "default access level already set"); assert(maxAccess >= defaultAccess); assert(maxAccess != AccessLevel::Private && "private not valid"); assert(defaultAccess != AccessLevel::Private && "private not valid"); setDefaultAndMaxAccessLevelBits(defaultAccess, maxAccess); assert(getDefaultAccessLevel() == defaultAccess && "not enough bits"); assert(getMaxAccessLevel() == maxAccess && "not enough bits"); } void setConformanceLoader(LazyMemberLoader *resolver, uint64_t contextData); /// Determine whether this is a constrained extension, which adds additional /// requirements beyond those of the nominal type. bool isConstrainedExtension() const; /// Determine whether this extension context is interchangeable with the /// original nominal type context. /// /// False if any of the following properties hold: /// - the extension is defined in a different module from the original /// nominal type decl, /// - the extension is constrained, or /// - the extension is to a protocol. /// FIXME: In a world where protocol extensions are dynamically dispatched, /// "extension is to a protocol" would no longer be a reason to use the /// extension mangling, because an extension method implementation could be /// resiliently moved into the original protocol itself. bool isEquivalentToExtendedContext() const; // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == DeclKind::Extension; } static bool classof(const DeclContext *C) { if (auto D = C->getAsDecl()) return classof(D); return false; } static bool classof(const IterableDeclContext *C) { return C->getIterableContextKind() == IterableDeclContextKind::ExtensionDecl; } using DeclContext::operator new; }; /// Iterator that walks the extensions of a particular type. class ExtensionIterator { ExtensionDecl *current; public: ExtensionIterator() : current() { } explicit ExtensionIterator(ExtensionDecl *current) : current(current) { } ExtensionDecl *operator*() const { return current; } ExtensionDecl *operator->() const { return current; } ExtensionIterator &operator++() { current = current->NextExtension.getPointer(); return *this; } ExtensionIterator operator++(int) { ExtensionIterator tmp = *this; ++(*this); return tmp; } friend bool operator==(ExtensionIterator x, ExtensionIterator y) { return x.current == y.current; } friend bool operator!=(ExtensionIterator x, ExtensionIterator y) { return x.current != y.current; } }; /// Range that covers a set of extensions. class ExtensionRange { ExtensionIterator first; ExtensionIterator last; public: ExtensionRange(ExtensionIterator first, ExtensionIterator last) : first(first), last(last) { } typedef ExtensionIterator iterator; iterator begin() const { return first; } iterator end() const { return last; } }; /// This represents one entry in a PatternBindingDecl, which are pairs of /// Pattern and Initialization expression. The pattern is always present, but /// the initializer can be null if there is none. class PatternBindingEntry { enum class Flags { Checked = 1 << 0, Removed = 1 << 1, /// Whether the contents of this initializer were subsumed by /// some other initialization, e.g., a lazy property's initializer /// gets subsumed by the getter body. Subsumed = 1 << 2, }; llvm::PointerIntPair<Pattern *, 3, OptionSet<Flags>> PatternAndFlags; struct InitializerAndEqualLoc { // When the initializer is removed we don't actually clear the pointers // because we might need to get initializer's source range. Since the // initializer is ASTContext-allocated it is safe. /// Exactly the expr the programmer wrote Expr *originalInit; /// Might be transformed, e.g. for a property wrapper. In the absence of /// transformation or synthesis, holds the expr as parsed. Expr *initAfterSynthesis; /// The location of the equal '=' token. SourceLoc EqualLoc; }; union { /// The initializer expression and its '=' token loc. InitializerAndEqualLoc InitExpr; /// The text of the initializer expression if deserialized from a module. StringRef InitStringRepresentation; }; enum class PatternFlags { IsText = 1 << 0, IsFullyValidated = 1 << 1, IsFromDebugger = 1 << 2, }; /// The initializer context used for this pattern binding entry. llvm::PointerIntPair<DeclContext *, 3, OptionSet<PatternFlags>> InitContextAndFlags; /// Values captured by this initializer. CaptureInfo Captures; friend class Parser; friend class PatternBindingInitializer; friend class PatternBindingDecl; friend class ast_scope::AbstractPatternEntryScope; friend class ast_scope::PatternEntryDeclScope; friend class ast_scope::PatternEntryInitializerScope; private: // FIXME: This API is transitional. Once the callers of // typeCheckPatternBinding are requestified, merge this bit with // Flags::Checked. friend class PatternBindingEntryRequest; bool isFullyValidated() const { return InitContextAndFlags.getInt().contains( PatternFlags::IsFullyValidated); } void setFullyValidated() { InitContextAndFlags.setInt(InitContextAndFlags.getInt() | PatternFlags::IsFullyValidated); } /// Set if this pattern binding came from the debugger. /// /// Stay away unless you are \c PatternBindingDecl::createForDebugger void setFromDebugger() { InitContextAndFlags.setInt(InitContextAndFlags.getInt() | PatternFlags::IsFromDebugger); } public: /// \p E is the initializer as parsed. PatternBindingEntry(Pattern *P, SourceLoc EqualLoc, Expr *E, DeclContext *InitContext) : PatternAndFlags(P, {}), InitExpr({E, E, EqualLoc}), InitContextAndFlags({InitContext, None}) {} private: Pattern *getPattern() const { return PatternAndFlags.getPointer(); } void setPattern(Pattern *P) { PatternAndFlags.setPointer(P); } /// Whether the given pattern binding entry is initialized. /// /// \param onlyExplicit Only consider explicit initializations (rather /// than implicitly-generated ones). bool isInitialized(bool onlyExplicit = false) const; Expr *getInit() const { if (PatternAndFlags.getInt().contains(Flags::Removed) || InitContextAndFlags.getInt().contains(PatternFlags::IsText)) return nullptr; return InitExpr.initAfterSynthesis; } /// Retrieve the initializer if it should be executed to initialize this /// particular pattern binding. Expr *getExecutableInit() const { return isInitializerSubsumed() ? nullptr : getInit(); } SourceRange getOriginalInitRange() const; void setInit(Expr *E); /// Gets the text of the initializer expression, stripping out inactive /// branches of any #ifs inside the expression. StringRef getInitStringRepresentation(SmallVectorImpl<char> &scratch) const; /// Sets the initializer string representation to the string that was /// deserialized from a partial module. void setInitStringRepresentation(StringRef str) { InitStringRepresentation = str; InitContextAndFlags.setInt(InitContextAndFlags.getInt() | PatternFlags::IsText); } /// Whether this pattern entry can generate a string representation of its /// initializer expression. bool hasInitStringRepresentation() const; /// Retrieve the location of the equal '=' token. SourceLoc getEqualLoc() const { return InitContextAndFlags.getInt().contains(PatternFlags::IsText) ? SourceLoc() : InitExpr.EqualLoc; } /// Set the location of the equal '=' token. void setEqualLoc(SourceLoc equalLoc) { assert(!InitContextAndFlags.getInt().contains(PatternFlags::IsText) && "cannot set equal loc for textual initializer"); InitExpr.EqualLoc = equalLoc; } /// Retrieve the initializer after the =, if any, as it was written in the /// source. Expr *getOriginalInit() const; /// Set the initializer after the = as it was written in the source. void setOriginalInit(Expr *); bool isInitializerChecked() const { return PatternAndFlags.getInt().contains(Flags::Checked); } void setInitializerChecked() { PatternAndFlags.setInt(PatternAndFlags.getInt() | Flags::Checked); } bool isInitializerSubsumed() const { return PatternAndFlags.getInt().contains(Flags::Subsumed); } void setInitializerSubsumed() { PatternAndFlags.setInt(PatternAndFlags.getInt() | Flags::Subsumed); } /// Returns \c true if the debugger created this pattern binding entry. bool isFromDebugger() const { return InitContextAndFlags.getInt().contains(PatternFlags::IsFromDebugger); } // Return the first variable initialized by this pattern. VarDecl *getAnchoringVarDecl() const; // Retrieve the declaration context for the initializer. DeclContext *getInitContext() const { return InitContextAndFlags.getPointer(); } /// Override the initializer context. void setInitContext(DeclContext *dc) { InitContextAndFlags.setPointer(dc); } SourceLoc getStartLoc() const; /// Retrieve the end location covered by this pattern binding entry. /// /// \param omitAccessors Whether the computation should omit the accessors /// from the source range. SourceLoc getEndLoc(bool omitAccessors = false) const; /// Retrieve the source range covered by this pattern binding entry. /// /// \param omitAccessors Whether the computation should omit the accessors /// from the source range. SourceRange getSourceRange(bool omitAccessors = false) const; CaptureInfo getCaptureInfo() const { return Captures; } void setCaptureInfo(CaptureInfo captures) { Captures = captures; } private: SourceLoc getLastAccessorEndLoc() const; }; /// This decl contains a pattern and optional initializer for a set /// of one or more VarDecls declared together. /// /// For example, in /// \code /// var (a, b) = foo(), (c,d) = bar() /// \endcode /// /// this includes two entries in the pattern list. The first contains the /// pattern "(a, b)" and the initializer "foo()". The second contains the /// pattern "(c, d)" and the initializer "bar()". /// class PatternBindingDecl final : public Decl, private llvm::TrailingObjects<PatternBindingDecl, PatternBindingEntry> { friend TrailingObjects; friend class Decl; friend class PatternBindingEntryRequest; SourceLoc StaticLoc; ///< Location of the 'static/class' keyword, if present. SourceLoc VarLoc; ///< Location of the 'var' keyword. friend class Decl; PatternBindingDecl(SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, SourceLoc VarLoc, unsigned NumPatternEntries, DeclContext *Parent); SourceLoc getLocFromSource() const { return VarLoc; } public: static PatternBindingDecl *create(ASTContext &Ctx, SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, SourceLoc VarLoc, ArrayRef<PatternBindingEntry> PatternList, DeclContext *Parent); static PatternBindingDecl *create(ASTContext &Ctx, SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, SourceLoc VarLoc, Pattern *Pat, SourceLoc EqualLoc, Expr *E, DeclContext *Parent); static PatternBindingDecl *createImplicit(ASTContext &Ctx, StaticSpellingKind StaticSpelling, Pattern *Pat, Expr *E, DeclContext *Parent, SourceLoc VarLoc = SourceLoc()); static PatternBindingDecl *createDeserialized( ASTContext &Ctx, SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, SourceLoc VarLoc, unsigned NumPatternEntries, DeclContext *Parent); // A dedicated entrypoint that allows LLDB to create pattern bindings // that look implicit to the compiler but contain user code. static PatternBindingDecl *createForDebugger(ASTContext &Ctx, StaticSpellingKind Spelling, Pattern *Pat, Expr *E, DeclContext *Parent); SourceLoc getStartLoc() const { return StaticLoc.isValid() ? StaticLoc : VarLoc; } SourceRange getSourceRange() const; unsigned getNumPatternEntries() const { return Bits.PatternBindingDecl.NumPatternEntries; } ArrayRef<PatternBindingEntry> getPatternList() const { return const_cast<PatternBindingDecl*>(this)->getMutablePatternList(); } /// Clean up walking the initializers for the pattern class InitIterator { const PatternBindingDecl &decl; unsigned currentPatternEntryIndex; void next() { ++currentPatternEntryIndex; } public: using value_type = Expr *; using pointer = value_type; using reference = value_type; using difference_type = unsigned; InitIterator(const PatternBindingDecl &decl, unsigned start = 0) : decl(decl), currentPatternEntryIndex(start) {} InitIterator &operator++() { next(); return *this; } InitIterator operator++(int) { InitIterator newIterator(decl, currentPatternEntryIndex); newIterator.next(); return newIterator; } pointer operator->() { return decl.getInit(currentPatternEntryIndex); } pointer operator*() { return decl.getInit(currentPatternEntryIndex); } difference_type operator-(const InitIterator &other) { return currentPatternEntryIndex - other.currentPatternEntryIndex; } bool operator==(const InitIterator &other) const { return &decl == &other.decl && currentPatternEntryIndex == other.currentPatternEntryIndex; } bool operator!=(const InitIterator &other) const { return !(*this == other); } }; InitIterator beginInits() const { return InitIterator(*this); } InitIterator endInits() const { return InitIterator(*this, getNumPatternEntries()); } llvm::iterator_range<InitIterator> initializers() const { return llvm::make_range(beginInits(), endInits()); } void setInitStringRepresentation(unsigned i, StringRef str) { getMutablePatternList()[i].setInitStringRepresentation(str); } /// Whether the given pattern entry is initialized. bool isInitialized(unsigned i) const { return getPatternList()[i].isInitialized(); } Expr *getInit(unsigned i) const { return getPatternList()[i].getInit(); } Expr *getExecutableInit(unsigned i) const { return getPatternList()[i].getExecutableInit(); } Expr *getOriginalInit(unsigned i) const { return getPatternList()[i].getOriginalInit(); } SourceRange getOriginalInitRange(unsigned i) const { return getPatternList()[i].getOriginalInitRange(); } void setInit(unsigned i, Expr *E) { getMutablePatternList()[i].setInit(E); } Pattern *getPattern(unsigned i) const { return getPatternList()[i].getPattern(); } void setPattern(unsigned i, Pattern *Pat, DeclContext *InitContext); DeclContext *getInitContext(unsigned i) const { return getPatternList()[i].getInitContext(); } CaptureInfo getCaptureInfo(unsigned i) const { return getPatternList()[i].getCaptureInfo(); } void setCaptureInfo(unsigned i, CaptureInfo captures) { getMutablePatternList()[i].setCaptureInfo(captures); } /// Given that this PBD is the parent pattern for the specified VarDecl, /// return the entry of the VarDecl in our PatternList. For example, in: /// /// let (a,b) = foo(), (c,d) = bar() /// /// "a" and "b" will have index 0, since they correspond to the first pattern, /// and "c" and "d" will have index 1 since they correspond to the second one. unsigned getPatternEntryIndexForVarDecl(const VarDecl *VD) const; bool isInitializerChecked(unsigned i) const { return getPatternList()[i].isInitializerChecked(); } void setInitializerChecked(unsigned i) { getMutablePatternList()[i].setInitializerChecked(); } bool isInitializerSubsumed(unsigned i) const { return getPatternList()[i].isInitializerSubsumed(); } void setInitializerSubsumed(unsigned i) { getMutablePatternList()[i].setInitializerSubsumed(); } /// Does this binding declare something that requires storage? bool hasStorage() const; /// Determines whether this binding either has an initializer expression, or is /// default initialized, without performing any type checking on it. bool isDefaultInitializable() const { for (unsigned i : range(getNumPatternEntries())) if (!isDefaultInitializable(i)) return false; return true; } /// Can the pattern at index i be default initialized? bool isDefaultInitializable(unsigned i) const; /// Can the property wrapper be used to provide default initialization? bool isDefaultInitializableViaPropertyWrapper(unsigned i) const; /// Does this pattern have a user-provided initializer expression? bool isExplicitlyInitialized(unsigned i) const; /// Whether the pattern entry at the given index can generate a string /// representation of its initializer expression. bool hasInitStringRepresentation(unsigned i) const { return getPatternList()[i].hasInitStringRepresentation(); } SourceLoc getEqualLoc(unsigned i) const; /// When the pattern binding contains only a single variable with no /// destructuring, retrieve that variable. VarDecl *getSingleVar() const; /// Return the first variable initialized by the pattern at the given index. VarDecl *getAnchoringVarDecl(unsigned i) const; bool isStatic() const { return Bits.PatternBindingDecl.IsStatic; } void setStatic(bool s) { Bits.PatternBindingDecl.IsStatic = s; } SourceLoc getStaticLoc() const { return StaticLoc; } /// \returns the way 'static'/'class' was spelled in the source. StaticSpellingKind getStaticSpelling() const { return static_cast<StaticSpellingKind>( Bits.PatternBindingDecl.StaticSpelling); } /// \returns the way 'static'/'class' should be spelled for this declaration. StaticSpellingKind getCorrectStaticSpelling() const; /// Is the pattern binding entry for this variable currently being computed? bool isComputingPatternBindingEntry(const VarDecl *vd) const; /// Is this an "async let" declaration? bool isAsyncLet() const; /// Gets the text of the initializer expression for the pattern entry at the /// given index, stripping out inactive branches of any #ifs inside the /// expression. StringRef getInitStringRepresentation(unsigned i, SmallVectorImpl<char> &scratch) const { return getPatternList()[i].getInitStringRepresentation(scratch); } /// Returns \c true if this pattern binding was created by the debugger. bool isDebuggerBinding() const { return Bits.PatternBindingDecl.IsDebugger; } static bool classof(const Decl *D) { return D->getKind() == DeclKind::PatternBinding; } private: MutableArrayRef<PatternBindingEntry> getMutablePatternList() { // Pattern entries are tail allocated. return {getTrailingObjects<PatternBindingEntry>(), getNumPatternEntries()}; } }; /// TopLevelCodeDecl - This decl is used as a container for top-level /// expressions and statements in the main module. It is always a direct /// child of a SourceFile. The primary reason for building these is to give /// top-level statements a DeclContext which is distinct from the file itself. /// This, among other things, makes it easier to distinguish between local /// top-level variables (which are not live past the end of the statement) and /// global variables. class TopLevelCodeDecl : public DeclContext, public Decl { BraceStmt *Body; SourceLoc getLocFromSource() const { return getStartLoc(); } friend class Decl; public: TopLevelCodeDecl(DeclContext *Parent, BraceStmt *Body = nullptr) : DeclContext(DeclContextKind::TopLevelCodeDecl, Parent), Decl(DeclKind::TopLevelCode, Parent), Body(Body) {} BraceStmt *getBody() const { return Body; } void setBody(BraceStmt *b) { Body = b; } SourceLoc getStartLoc() const; SourceRange getSourceRange() const; static bool classof(const Decl *D) { return D->getKind() == DeclKind::TopLevelCode; } static bool classof(const DeclContext *C) { if (auto D = C->getAsDecl()) return classof(D); return false; } using DeclContext::operator new; }; /// SerializedTopLevelCodeDeclContext - This represents what was originally a /// TopLevelCodeDecl during serialization. It is preserved only to maintain the /// correct AST structure and remangling after deserialization. class SerializedTopLevelCodeDeclContext : public SerializedLocalDeclContext { public: SerializedTopLevelCodeDeclContext(DeclContext *Parent) : SerializedLocalDeclContext(LocalDeclContextKind::TopLevelCodeDecl, Parent) {} static bool classof(const DeclContext *DC) { if (auto LDC = dyn_cast<SerializedLocalDeclContext>(DC)) return LDC->getLocalDeclContextKind() == LocalDeclContextKind::TopLevelCodeDecl; return false; } }; /// IfConfigDecl - This class represents #if/#else/#endif blocks. /// Active and inactive block members are stored separately, with the intention /// being that active members will be handed back to the enclosing context. class IfConfigDecl : public Decl { /// An array of clauses controlling each of the #if/#elseif/#else conditions. /// The array is ASTContext allocated. ArrayRef<IfConfigClause> Clauses; SourceLoc EndLoc; SourceLoc getLocFromSource() const { return Clauses[0].Loc; } friend class Decl; public: IfConfigDecl(DeclContext *Parent, ArrayRef<IfConfigClause> Clauses, SourceLoc EndLoc, bool HadMissingEnd) : Decl(DeclKind::IfConfig, Parent), Clauses(Clauses), EndLoc(EndLoc) { Bits.IfConfigDecl.HadMissingEnd = HadMissingEnd; } ArrayRef<IfConfigClause> getClauses() const { return Clauses; } /// Return the active clause, or null if there is no active one. const IfConfigClause *getActiveClause() const { for (auto &Clause : Clauses) if (Clause.isActive) return &Clause; return nullptr; } const ArrayRef<ASTNode> getActiveClauseElements() const { if (auto *Clause = getActiveClause()) return Clause->Elements; return {}; } SourceLoc getEndLoc() const { return EndLoc; } bool hadMissingEnd() const { return Bits.IfConfigDecl.HadMissingEnd; } SourceRange getSourceRange() const; static bool classof(const Decl *D) { return D->getKind() == DeclKind::IfConfig; } }; class StringLiteralExpr; class PoundDiagnosticDecl : public Decl { SourceLoc StartLoc; SourceLoc EndLoc; StringLiteralExpr *Message; SourceLoc getLocFromSource() const { return StartLoc; } friend class Decl; public: PoundDiagnosticDecl(DeclContext *Parent, bool IsError, SourceLoc StartLoc, SourceLoc EndLoc, StringLiteralExpr *Message) : Decl(DeclKind::PoundDiagnostic, Parent), StartLoc(StartLoc), EndLoc(EndLoc), Message(Message) { Bits.PoundDiagnosticDecl.IsError = IsError; Bits.PoundDiagnosticDecl.HasBeenEmitted = false; } DiagnosticKind getKind() const { return isError() ? DiagnosticKind::Error : DiagnosticKind::Warning; } StringLiteralExpr *getMessage() const { return Message; } bool isError() const { return Bits.PoundDiagnosticDecl.IsError; } bool hasBeenEmitted() const { return Bits.PoundDiagnosticDecl.HasBeenEmitted; } void markEmitted() { Bits.PoundDiagnosticDecl.HasBeenEmitted = true; } SourceLoc getEndLoc() const { return EndLoc; }; SourceRange getSourceRange() const { return SourceRange(StartLoc, EndLoc); } static bool classof(const Decl *D) { return D->getKind() == DeclKind::PoundDiagnostic; } }; class OpaqueTypeDecl; /// ValueDecl - All named decls that are values in the language. These can /// have a type, etc. class ValueDecl : public Decl { DeclName Name; SourceLoc NameLoc; llvm::PointerIntPair<Type, 3, OptionalEnum<AccessLevel>> TypeAndAccess; unsigned LocalDiscriminator = 0; struct { /// Whether the "IsObjC" bit has been computed yet. unsigned isObjCComputed : 1; /// Whether this declaration is exposed to Objective-C. unsigned isObjC : 1; /// Whether the "overridden" declarations have been computed already. unsigned hasOverriddenComputed : 1; /// Whether there are any "overridden" declarations. The actual overridden /// declarations are kept in a side table in the ASTContext. unsigned hasOverridden : 1; /// Whether the "isDynamic" bit has been computed yet. unsigned isDynamicComputed : 1; /// Whether this declaration is 'dynamic', meaning that all uses of /// the declaration will go through an extra level of indirection that /// allows the entity to be replaced at runtime. unsigned isDynamic : 1; /// Whether the "isFinal" bit has been computed yet. unsigned isFinalComputed : 1; /// Whether this declaration is 'final'. A final class can't be subclassed, /// a final class member can't be overriden. unsigned isFinal : 1; /// Whether the "isIUO" bit" has been computed yet. unsigned isIUOComputed : 1; /// Whether this declaration produces an implicitly unwrapped /// optional result. unsigned isIUO : 1; } LazySemanticInfo = { }; friend class DynamicallyReplacedDeclRequest; friend class OverriddenDeclsRequest; friend class IsObjCRequest; friend class IsFinalRequest; friend class IsDynamicRequest; friend class IsImplicitlyUnwrappedOptionalRequest; friend class InterfaceTypeRequest; friend class CheckRedeclarationRequest; friend class Decl; SourceLoc getLocFromSource() const { return NameLoc; } protected: ValueDecl(DeclKind K, llvm::PointerUnion<DeclContext *, ASTContext *> context, DeclName name, SourceLoc NameLoc) : Decl(K, context), Name(name), NameLoc(NameLoc) { Bits.ValueDecl.AlreadyInLookupTable = false; Bits.ValueDecl.CheckedRedeclaration = false; Bits.ValueDecl.IsUserAccessible = true; Bits.ValueDecl.Synthesized = false; } // MemberLookupTable borrows a bit from this type friend class MemberLookupTable; bool isAlreadyInLookupTable() { return Bits.ValueDecl.AlreadyInLookupTable; } void setAlreadyInLookupTable(bool value = true) { Bits.ValueDecl.AlreadyInLookupTable = value; } /// Determine whether we have already checked whether this /// declaration is a redeclaration. bool alreadyCheckedRedeclaration() const { return Bits.ValueDecl.CheckedRedeclaration; } /// Set whether we have already checked this declaration as a /// redeclaration. void setCheckedRedeclaration() { Bits.ValueDecl.CheckedRedeclaration = true; } public: /// Return true if this protocol member is a protocol requirement. /// /// Asserts if this is not a member of a protocol. bool isProtocolRequirement() const; void setUserAccessible(bool Accessible) { Bits.ValueDecl.IsUserAccessible = Accessible; } bool isUserAccessible() const { return Bits.ValueDecl.IsUserAccessible; } bool isSynthesized() const { return Bits.ValueDecl.Synthesized; } void setSynthesized(bool value = true) { Bits.ValueDecl.Synthesized = value; } bool hasName() const { return bool(Name); } bool isOperator() const { return Name.isOperator(); } /// Retrieve the full name of the declaration. DeclName getName() const { return Name; } void setName(DeclName name) { Name = name; } /// Retrieve the base name of the declaration, ignoring any argument /// names. DeclBaseName getBaseName() const { return Name.getBaseName(); } Identifier getBaseIdentifier() const { return Name.getBaseIdentifier(); } /// Generates a DeclNameRef referring to this declaration with as much /// specificity as possible. DeclNameRef createNameRef() const { return DeclNameRef(Name); } /// Retrieve the name to use for this declaration when interoperating /// with the Objective-C runtime. /// /// \returns A "selector" containing the runtime name. For non-method /// entities (classes, protocols, properties), this operation will /// return a zero-parameter selector with the appropriate name in its /// first slot. Optional<ObjCSelector> getObjCRuntimeName( bool skipIsObjCResolution = false) const; /// Determine whether the given declaration can infer @objc, or the /// Objective-C name, if used to satisfy the given requirement. bool canInferObjCFromRequirement(ValueDecl *requirement); SourceLoc getNameLoc() const { return NameLoc; } bool isUsableFromInline() const; /// Returns \c true if this declaration is *not* intended to be used directly /// by application developers despite the visibility. bool shouldHideFromEditor() const; bool hasAccess() const { return TypeAndAccess.getInt().hasValue(); } /// Access control is done by Requests. friend class AccessLevelRequest; /// Returns the access level specified explicitly by the user, or provided by /// default according to language rules. /// /// Most of the time this is not the interesting value to check; access is /// limited by enclosing scopes per SE-0025. Use #getFormalAccessScope to /// check if access control is being used consistently, and to take features /// such as \c \@testable and \c \@usableFromInline into account. /// /// \sa getFormalAccessScope /// \sa hasOpenAccess AccessLevel getFormalAccess() const; /// Determine whether this Decl has either Private or FilePrivate access, /// and its DeclContext does not. bool isOutermostPrivateOrFilePrivateScope() const; /// Returns the outermost DeclContext from which this declaration can be /// accessed, or null if the declaration is public. /// /// This is used when calculating if access control is being used /// consistently. If \p useDC is provided (the location where the value is /// being used), features that affect formal access such as \c \@testable are /// taken into account. /// /// \invariant /// <code>value.isAccessibleFrom( /// value.getFormalAccessScope().getDeclContext())</code> /// /// If \p treatUsableFromInlineAsPublic is true, declarations marked with the /// \c \@usableFromInline attribute are treated as public. This is normally /// false for name lookup and other source language concerns, but true when /// computing the linkage of generated functions. /// /// \sa getFormalAccess /// \sa isAccessibleFrom /// \sa hasOpenAccess AccessScope getFormalAccessScope(const DeclContext *useDC = nullptr, bool treatUsableFromInlineAsPublic = false) const; /// Copy the formal access level and @usableFromInline attribute from /// \p source. /// /// If \p sourceIsParentContext is true, an access level of \c private will /// be copied as \c fileprivate, to ensure that this declaration will be /// available everywhere \p source is. void copyFormalAccessFrom(const ValueDecl *source, bool sourceIsParentContext = false); /// Returns the access level that actually controls how a declaration should /// be emitted and may be used. /// /// This is the access used when making optimization and code generation /// decisions. It should not be used at the AST or semantic level. AccessLevel getEffectiveAccess() const; void setAccess(AccessLevel access) { assert(!hasAccess() && "access already set"); overwriteAccess(access); } /// Overwrite the access of this declaration. /// /// This is needed in the LLDB REPL. void overwriteAccess(AccessLevel access) { TypeAndAccess.setInt(access); } /// Returns true if this declaration is accessible from the given context. /// /// A private declaration is accessible from any DeclContext within the same /// source file. /// /// An internal declaration is accessible from any DeclContext within the same /// module. /// /// A public declaration is accessible everywhere. /// /// If \p DC is null, returns true only if this declaration is public. /// /// If \p forConformance is true, we ignore the visibility of the protocol /// when evaluating protocol extension members. This language rule allows a /// protocol extension of a private protocol to provide default /// implementations for the requirements of a public protocol, even when /// the default implementations are not visible to name lookup. bool isAccessibleFrom(const DeclContext *DC, bool forConformance = false, bool allowUsableFromInline = false) const; /// Returns whether this declaration should be treated as \c open from /// \p useDC. This is very similar to #getFormalAccess, but takes /// \c \@testable into account. /// /// This is mostly only useful when considering requirements on an override: /// if the base declaration is \c open, the override might have to be too. bool hasOpenAccess(const DeclContext *useDC) const; /// FIXME: This is deprecated. bool isRecursiveValidation() const; /// Retrieve the "interface" type of this value, which uses /// GenericTypeParamType if the declaration is generic. For a generic /// function, this will have a GenericFunctionType with a /// GenericSignature inside the type. Type getInterfaceType() const; bool hasInterfaceType() const; /// Set the interface type for the given value. void setInterfaceType(Type type); /// isInstanceMember - Determine whether this value is an instance member /// of an enum or protocol. bool isInstanceMember() const; /// Retrieve the context discriminator for this local value, which /// is the index of this declaration in the sequence of /// discriminated declarations with the same name in the current /// context. Only local functions and variables with getters and /// setters have discriminators. unsigned getLocalDiscriminator() const; void setLocalDiscriminator(unsigned index); /// Retrieve the declaration that this declaration overrides, if any. ValueDecl *getOverriddenDecl() const; /// Retrieve the declarations that this declaration overrides, if any. llvm::TinyPtrVector<ValueDecl *> getOverriddenDecls() const; /// Set the declaration that this declaration overrides. void setOverriddenDecl(ValueDecl *overridden) { setOverriddenDecls(overridden); } /// Set the declarations that this declaration overrides. void setOverriddenDecls(ArrayRef<ValueDecl *> overridden); /// Whether the overridden declarations have already been computed. bool overriddenDeclsComputed() const; /// Compute the untyped overload signature for this declaration. OverloadSignature getOverloadSignature() const; /// Retrieve the type used to describe this entity for the purposes of /// overload resolution. CanType getOverloadSignatureType() const; /// Returns true if the decl requires Objective-C interop. /// /// This can be true even if there is no 'objc' attribute on the declaration. /// In that case it was inferred by the type checker and set with a call to /// markAsObjC(). bool isObjC() const; /// Note whether this declaration is known to be exposed to Objective-C. void setIsObjC(bool Value); /// Is this declaration semantically 'final', meaning that the type checker /// should treat it as final even if the ABI does not? bool isSemanticallyFinal() const; /// Is this declaration 'final'? bool isFinal() const; /// Is this declaration marked with 'dynamic'? bool isDynamic() const; bool isDistributedActorIndependent() const; private: bool isObjCDynamic() const { return isObjC() && isDynamic(); } bool isNativeDynamic() const { return !isObjC() && isDynamic(); } bool isObjCDynamicInGenericClass() const; public: /// Should we use Objective-C method dispatch for this decl. bool shouldUseObjCDispatch() const { return isObjCDynamic(); } /// Should we use native dynamic function replacement dispatch for this decl. bool shouldUseNativeDynamicDispatch() const { return isNativeDynamic(); } /// Should we use Objective-C category based function replacement for this /// decl. /// This is all `@objc dynamic` methods except for such methods in native /// generic classes. We can't use a category for generic classes so we use /// native replacement instead (this behavior is only enabled with /// -enable-implicit-dynamic). bool shouldUseObjCMethodReplacement() const; /// Should we use native dynamic function replacement mechanism for this decl. /// This is all native dynamic methods except for `@objc dynamic` methods in /// generic classes (see above). bool shouldUseNativeMethodReplacement() const; /// Is this a native dynamic function replacement based replacement. /// This is all @_dynamicReplacement(for:) of native functions and @objc /// dynamic methods on generic classes (see above). bool isNativeMethodReplacement() const; /// Returns if this declaration has more visible formal access than 'other'. bool isMoreVisibleThan(ValueDecl *other) const; /// Set whether this type is 'dynamic' or not. void setIsDynamic(bool value); /// Whether the 'dynamic' bit has been computed already. bool isDynamicComputed() const { return LazySemanticInfo.isDynamicComputed; } /// Returns true if this decl can be found by id-style dynamic lookup. bool canBeAccessedByDynamicLookup() const; /// Returns true if this declaration has an implicitly unwrapped optional /// result. The precise meaning depends on the declaration kind: /// - for properties, the value is IUO /// - for subscripts, the element type is IUO /// - for functions, the result type is IUO /// - for constructors, the failability kind is IUO bool isImplicitlyUnwrappedOptional() const; /// Should only be set on imported and deserialized declarations; parsed /// declarations compute this lazily via a request. void setImplicitlyUnwrappedOptional(bool isIUO) { LazySemanticInfo.isIUOComputed = 1; LazySemanticInfo.isIUO = isIUO; } /// Returns the protocol requirements that this decl conforms to. ArrayRef<ValueDecl *> getSatisfiedProtocolRequirements(bool Sorted = false) const; /// Determines the kind of access that should be performed by a /// DeclRefExpr or MemberRefExpr use of this value in the specified /// context. /// /// \param DC The declaration context. /// /// \param isAccessOnSelf Whether this is a member access on the implicit /// 'self' declaration of the declaration context. AccessSemantics getAccessSemanticsFromContext(const DeclContext *DC, bool isAccessOnSelf) const; /// Determines if a reference to this declaration from a nested function /// should be treated like a capture of a local value. bool isLocalCapture() const; /// Print a reference to the given declaration. std::string printRef() const; /// Dump a reference to the given declaration. void dumpRef(raw_ostream &os) const; /// Dump a reference to the given declaration. SWIFT_DEBUG_DUMPER(dumpRef()); /// Returns true if the declaration is a static member of a type. /// /// This is not necessarily the opposite of "isInstanceMember()". Both /// predicates will be false for declarations that either categorically /// can't be "static" or are in a context where "static" doesn't make sense. bool isStatic() const; /// Retrieve the location at which we should insert a new attribute or /// modifier. SourceLoc getAttributeInsertionLoc(bool forModifier) const; static bool classof(const Decl *D) { return D->getKind() >= DeclKind::First_ValueDecl && D->getKind() <= DeclKind::Last_ValueDecl; } /// True if this is a C function that was imported as a member of a type in /// Swift. bool isImportAsMember() const; /// Returns true if the declaration's interface type is a function type with a /// curried self parameter. bool hasCurriedSelf() const; /// Returns true if the declaration has a parameter list associated with it. /// /// Note that not all declarations with function interface types have /// parameter lists, for example an enum element without associated values. bool hasParameterList() const; /// Returns the number of curry levels in the declaration's interface type. unsigned getNumCurryLevels() const; /// Get the decl for this value's opaque result type, if it has one. OpaqueTypeDecl *getOpaqueResultTypeDecl() const; /// Get the representative for this value's opaque result type, if it has one. OpaqueReturnTypeRepr *getOpaqueResultTypeRepr() const; /// Retrieve the attribute associating this declaration with a /// result builder, if there is one. CustomAttr *getAttachedResultBuilder() const; /// Retrieve the @resultBuilder type attached to this declaration, /// if there is one. Type getResultBuilderType() const; /// If this value or its backing storage is annotated /// @_dynamicReplacement(for: ...), compute the original declaration /// that this declaration dynamically replaces. ValueDecl *getDynamicallyReplacedDecl() const; }; /// This is a common base class for declarations which declare a type. class TypeDecl : public ValueDecl { ArrayRef<InheritedEntry> Inherited; protected: TypeDecl(DeclKind K, llvm::PointerUnion<DeclContext *, ASTContext *> context, Identifier name, SourceLoc NameLoc, ArrayRef<InheritedEntry> inherited) : ValueDecl(K, context, name, NameLoc), Inherited(inherited) {} public: Identifier getName() const { return getBaseIdentifier(); } /// Returns the string for the base name, or "_" if this is unnamed. StringRef getNameStr() const { return hasName() ? getBaseIdentifier().str() : "_"; } /// The type of this declaration's values. For the type of the /// declaration itself, use getInterfaceType(), which returns a /// metatype. Type getDeclaredInterfaceType() const; /// Retrieve the set of protocols that this type inherits (i.e, /// explicitly conforms to). ArrayRef<InheritedEntry> getInherited() const { return Inherited; } void setInherited(ArrayRef<InheritedEntry> i) { Inherited = i; } static bool classof(const Decl *D) { return D->getKind() >= DeclKind::First_TypeDecl && D->getKind() <= DeclKind::Last_TypeDecl; } /// Compute an ordering between two type declarations that is ABI-stable. static int compare(const TypeDecl *type1, const TypeDecl *type2); /// Compute an ordering between two type declarations that is ABI-stable. /// This version takes a pointer-to-a-pointer for use with /// llvm::array_pod_sort() and similar. template<typename T> static int compare(T * const* type1, T * const* type2) { return compare(*type1, *type2); } }; /// A type declaration that can have generic parameters attached to it. Because /// it has these generic parameters, it is always a DeclContext. class GenericTypeDecl : public GenericContext, public TypeDecl { public: GenericTypeDecl(DeclKind K, DeclContext *DC, Identifier name, SourceLoc nameLoc, ArrayRef<InheritedEntry> inherited, GenericParamList *GenericParams); // Resolve ambiguity due to multiple base classes. using TypeDecl::getASTContext; using DeclContext::operator new; using TypeDecl::getDeclaredInterfaceType; static bool classof(const DeclContext *C) { if (auto D = C->getAsDecl()) return classof(D); return false; } static bool classof(const Decl *D) { return D->getKind() >= DeclKind::First_GenericTypeDecl && D->getKind() <= DeclKind::Last_GenericTypeDecl; } }; /// OpaqueTypeDecl - This is a declaration of an opaque type. The opaque type /// is formally equivalent to its underlying type, but abstracts it away from /// clients of the opaque type, only exposing the type as something conforming /// to a given set of constraints. /// /// Currently, opaque types do not normally have an explicit spelling in source /// code. One is formed implicitly when a declaration is written with an opaque /// result type, as in: /// /// func foo() -> some SignedInteger { return 1 } /// /// The declared type is a special kind of ArchetypeType representing the /// abstracted underlying type. class OpaqueTypeDecl : public GenericTypeDecl { /// The original declaration that "names" the opaque type. Although a specific /// opaque type cannot be explicitly named, oapque types can propagate /// arbitrarily through expressions, so we need to know *which* opaque type is /// propagated. ValueDecl *NamingDecl; /// The generic signature of the opaque interface to the type. This is the /// outer generic signature with an added generic parameter representing the /// underlying type. GenericSignature OpaqueInterfaceGenericSignature; /// The generic parameter that represents the underlying type. GenericTypeParamType *UnderlyingInterfaceType; /// If known, the underlying type and conformances of the opaque type, /// expressed as a SubstitutionMap for the opaque interface generic signature. /// This maps types in the interface generic signature to the outer generic /// signature of the original declaration. Optional<SubstitutionMap> UnderlyingTypeSubstitutions; mutable Identifier OpaqueReturnTypeIdentifier; public: OpaqueTypeDecl(ValueDecl *NamingDecl, GenericParamList *GenericParams, DeclContext *DC, GenericSignature OpaqueInterfaceGenericSignature, GenericTypeParamType *UnderlyingInterfaceType); ValueDecl *getNamingDecl() const { return NamingDecl; } void setNamingDecl(ValueDecl *D) { assert(!NamingDecl && "already have naming decl"); NamingDecl = D; } /// Is this opaque type the opaque return type of the given function? /// /// This is more complex than just checking `getNamingDecl` because the /// function could also be the getter of a storage declaration. bool isOpaqueReturnTypeOfFunction(const AbstractFunctionDecl *func) const; GenericSignature getOpaqueInterfaceGenericSignature() const { return OpaqueInterfaceGenericSignature; } GenericTypeParamType *getUnderlyingInterfaceType() const { return UnderlyingInterfaceType; } Optional<SubstitutionMap> getUnderlyingTypeSubstitutions() const { return UnderlyingTypeSubstitutions; } void setUnderlyingTypeSubstitutions(SubstitutionMap subs) { assert(!UnderlyingTypeSubstitutions.hasValue() && "resetting underlying type?!"); UnderlyingTypeSubstitutions = subs; } // Opaque type decls are currently always implicit SourceRange getSourceRange() const { return SourceRange(); } // Get the identifier string that can be used to cross-reference unnamed // opaque return types across files. Identifier getOpaqueReturnTypeIdentifier() const; static bool classof(const Decl *D) { return D->getKind() == DeclKind::OpaqueType; } static bool classof(const GenericTypeDecl *D) { return D->getKind() == DeclKind::OpaqueType; } static bool classof(const DeclContext *C) { if (auto D = C->getAsDecl()) return classof(D); return false; } }; /// TypeAliasDecl - This is a declaration of a typealias, for example: /// /// typealias Foo = Int /// /// TypeAliasDecl's always have 'MetatypeType' type. /// class TypeAliasDecl : public GenericTypeDecl { friend class UnderlyingTypeRequest; /// The location of the 'typealias' keyword SourceLoc TypeAliasLoc; /// The location of the equal '=' token SourceLoc EqualLoc; /// The end of the type, valid even when the type cannot be parsed SourceLoc TypeEndLoc; /// The location of the right-hand side of the typealias binding TypeLoc UnderlyingTy; public: TypeAliasDecl(SourceLoc TypeAliasLoc, SourceLoc EqualLoc, Identifier Name, SourceLoc NameLoc, GenericParamList *GenericParams, DeclContext *DC); SourceLoc getStartLoc() const { return TypeAliasLoc; } SourceRange getSourceRange() const; /// Returns the location of the equal '=' token SourceLoc getEqualLoc() const { return EqualLoc; } void setTypeEndLoc(SourceLoc e) { TypeEndLoc = e; } /// Retrieve the TypeRepr corresponding to the parsed underlying type. TypeRepr *getUnderlyingTypeRepr() const { return UnderlyingTy.getTypeRepr(); } void setUnderlyingTypeRepr(TypeRepr *repr) { UnderlyingTy = repr; } /// Retrieve the interface type of the underlying type. Type getUnderlyingType() const; void setUnderlyingType(Type type); /// Returns the interface type of the underlying type if computed, null /// otherwise. Should only be used for dumping. Type getCachedUnderlyingType() const { return UnderlyingTy.getType(); } /// For generic typealiases, return the unbound generic type. /// /// Since UnboundGenericType is on its way out, so is this method. Try to /// avoid introducing new callers if possible. Instead of passing around /// an UnboundGenericType, considering passing around the Decl itself /// instead. UnboundGenericType *getUnboundGenericType() const; /// Retrieve a sugared interface type containing the structure of the interface /// type before any semantic validation has occurred. Type getStructuralType() const; /// Whether the typealias forwards perfectly to its underlying type. /// /// If true, this typealias was created by ClangImporter to preserve source /// compatibility with a previous language version's name for a type. Many /// checks in Sema look through compatibility aliases even when they would /// operate on other typealiases. /// /// \warning This has absolutely nothing to do with the Objective-C /// \c compatibility_alias keyword. bool isCompatibilityAlias() const { return Bits.TypeAliasDecl.IsCompatibilityAlias; } /// Sets whether the typealias forwards perfectly to its underlying type. /// /// Marks this typealias as having been created by ClangImporter to preserve /// source compatibility with a previous language version's name for a type. /// Many checks in Sema look through compatibility aliases even when they /// would operate on other typealiases. /// /// \warning This has absolutely nothing to do with the Objective-C /// \c compatibility_alias keyword. void markAsCompatibilityAlias(bool newValue = true) { Bits.TypeAliasDecl.IsCompatibilityAlias = newValue; } /// Is this a special debugger variable? bool isDebuggerAlias() const { return Bits.TypeAliasDecl.IsDebuggerAlias; } void markAsDebuggerAlias(bool isDebuggerAlias) { Bits.TypeAliasDecl.IsDebuggerAlias = isDebuggerAlias; } static bool classof(const Decl *D) { return D->getKind() == DeclKind::TypeAlias; } static bool classof(const GenericTypeDecl *D) { return D->getKind() == DeclKind::TypeAlias; } static bool classof(const DeclContext *C) { if (auto D = C->getAsDecl()) return classof(D); return false; } }; /// Abstract class describing generic type parameters and associated types, /// whose common purpose is to anchor the abstract type parameter and specify /// requirements for any corresponding type argument. class AbstractTypeParamDecl : public TypeDecl { protected: AbstractTypeParamDecl(DeclKind kind, DeclContext *dc, Identifier name, SourceLoc NameLoc) : TypeDecl(kind, dc, name, NameLoc, { }) { } public: /// Return the superclass of the generic parameter. Type getSuperclass() const; /// Retrieve the set of protocols to which this abstract type /// parameter conforms. ArrayRef<ProtocolDecl *> getConformingProtocols() const; static bool classof(const Decl *D) { return D->getKind() >= DeclKind::First_AbstractTypeParamDecl && D->getKind() <= DeclKind::Last_AbstractTypeParamDecl; } }; /// A declaration of a generic type parameter. /// /// A generic type parameter introduces a new, named type parameter along /// with some set of requirements on any type argument used to realize this /// type parameter. The requirements involve conformances to specific /// protocols or inheritance from a specific class type. /// /// In the following example, 'T' is a generic type parameter with the /// requirement that the type argument conform to the 'Comparable' protocol. /// /// \code /// func min<T : Comparable>(x : T, y : T) -> T { ... } /// \endcode class GenericTypeParamDecl : public AbstractTypeParamDecl { public: static const unsigned InvalidDepth = 0xFFFF; /// Construct a new generic type parameter. /// /// \param dc The DeclContext in which the generic type parameter's owner /// occurs. This should later be overwritten with the actual declaration /// context that owns the type parameter. /// /// \param name The name of the generic parameter. /// \param nameLoc The location of the name. GenericTypeParamDecl(DeclContext *dc, Identifier name, SourceLoc nameLoc, unsigned depth, unsigned index); /// The depth of this generic type parameter, i.e., the number of outer /// levels of generic parameter lists that enclose this type parameter. /// /// \code /// struct X<T> { /// func f<U>() { } /// } /// \endcode /// /// Here 'T' has depth 0 and 'U' has depth 1. Both have index 0. unsigned getDepth() const { return Bits.GenericTypeParamDecl.Depth; } /// Set the depth of this generic type parameter. /// /// \sa getDepth void setDepth(unsigned depth) { Bits.GenericTypeParamDecl.Depth = depth; assert(Bits.GenericTypeParamDecl.Depth == depth && "Truncation"); } /// The index of this generic type parameter within its generic parameter /// list. /// /// \code /// struct X<T, U> { /// func f<V>() { } /// } /// \endcode /// /// Here 'T' and 'U' have indexes 0 and 1, respectively. 'V' has index 0. unsigned getIndex() const { return Bits.GenericTypeParamDecl.Index; } SourceLoc getStartLoc() const { return getNameLoc(); } SourceRange getSourceRange() const; static bool classof(const Decl *D) { return D->getKind() == DeclKind::GenericTypeParam; } }; /// A declaration of an associated type. /// /// An associated type introduces a new, named type in a protocol that /// can vary from one conforming type to the next. Associated types have a /// set of requirements to which the type that replaces it much realize, /// described via conformance to specific protocols, or inheritance from a /// specific class type. /// /// In the following example, 'Element' is an associated type with no /// requirements. /// /// \code /// protocol Enumerator { /// typealias Element /// func getNext() -> Element? /// } /// \endcode class AssociatedTypeDecl : public AbstractTypeParamDecl { /// The location of the initial keyword. SourceLoc KeywordLoc; /// The default definition. TypeRepr *DefaultDefinition; /// The where clause attached to the associated type. TrailingWhereClause *TrailingWhere; LazyMemberLoader *Resolver = nullptr; uint64_t ResolverContextData; friend class DefaultDefinitionTypeRequest; public: AssociatedTypeDecl(DeclContext *dc, SourceLoc keywordLoc, Identifier name, SourceLoc nameLoc, TypeRepr *defaultDefinition, TrailingWhereClause *trailingWhere); AssociatedTypeDecl(DeclContext *dc, SourceLoc keywordLoc, Identifier name, SourceLoc nameLoc, TrailingWhereClause *trailingWhere, LazyMemberLoader *definitionResolver, uint64_t resolverData); /// Get the protocol in which this associated type is declared. ProtocolDecl *getProtocol() const { return cast<ProtocolDecl>(getDeclContext()); } /// Check if we have a default definition type. bool hasDefaultDefinitionType() const { // If we have a TypeRepr, return true immediately without kicking off // a request. return DefaultDefinition || getDefaultDefinitionType(); } /// Retrieve the default definition type. Type getDefaultDefinitionType() const; /// Retrieve the default definition as written in the source. TypeRepr *getDefaultDefinitionTypeRepr() const { return DefaultDefinition; } /// Retrieve the trailing where clause for this associated type, if any. TrailingWhereClause *getTrailingWhereClause() const { return TrailingWhere; } /// Set the trailing where clause for this associated type. void setTrailingWhereClause(TrailingWhereClause *trailingWhereClause) { TrailingWhere = trailingWhereClause; } /// Retrieve the associated type "anchor", which is the associated type /// declaration that will be used to describe this associated type in the /// ABI. /// /// The associated type "anchor" is an associated type that does not /// override any other associated type. There may be several such associated /// types; select one deterministically. AssociatedTypeDecl *getAssociatedTypeAnchor() const; /// Retrieve the (first) overridden associated type declaration, if any. AssociatedTypeDecl *getOverriddenDecl() const { return cast_or_null<AssociatedTypeDecl>( AbstractTypeParamDecl::getOverriddenDecl()); } /// Retrieve the set of associated types overridden by this associated /// type. llvm::TinyPtrVector<AssociatedTypeDecl *> getOverriddenDecls() const; SourceLoc getStartLoc() const { return KeywordLoc; } SourceRange getSourceRange() const; static bool classof(const Decl *D) { return D->getKind() == DeclKind::AssociatedType; } }; class MemberLookupTable; class ConformanceLookupTable; // Kinds of pointer types. enum PointerTypeKind : unsigned { PTK_UnsafeMutableRawPointer, PTK_UnsafeRawPointer, PTK_UnsafeMutablePointer, PTK_UnsafePointer, PTK_AutoreleasingUnsafeMutablePointer, }; static inline bool isRawPointerKind(PointerTypeKind PTK) { switch (PTK) { case PTK_UnsafeMutableRawPointer: case PTK_UnsafeRawPointer: return true; case PTK_UnsafeMutablePointer: case PTK_UnsafePointer: case PTK_AutoreleasingUnsafeMutablePointer: return false; } llvm_unreachable("Unhandled PointerTypeKind in switch."); } // Kinds of buffer pointer types. enum BufferPointerTypeKind : unsigned { BPTK_UnsafeMutableRawBufferPointer, BPTK_UnsafeRawBufferPointer, BPTK_UnsafeMutableBufferPointer, BPTK_UnsafeBufferPointer, }; enum KeyPathTypeKind : unsigned char { KPTK_AnyKeyPath, KPTK_PartialKeyPath, KPTK_KeyPath, KPTK_WritableKeyPath, KPTK_ReferenceWritableKeyPath }; /// NominalTypeDecl - a declaration of a nominal type, like a struct. class NominalTypeDecl : public GenericTypeDecl, public IterableDeclContext { SourceRange Braces; /// The first extension of this type. ExtensionDecl *FirstExtension = nullptr; /// The last extension of this type, used solely for efficient /// insertion of new extensions. ExtensionDecl *LastExtension = nullptr; /// The generation at which we last loaded extensions. unsigned ExtensionGeneration; /// Prepare to traverse the list of extensions. void prepareExtensions(); /// Retrieve the conformance loader (if any), and removing it in the /// same operation. The caller is responsible for loading the /// conformances. std::pair<LazyMemberLoader *, uint64_t> takeConformanceLoader() { if (!Bits.NominalTypeDecl.HasLazyConformances) return { nullptr, 0 }; return takeConformanceLoaderSlow(); } /// Slow path for \c takeConformanceLoader(). std::pair<LazyMemberLoader *, uint64_t> takeConformanceLoaderSlow(); /// A lookup table containing all of the members of this type and /// its extensions. /// /// The table itself is lazily constructed and updated when /// lookupDirect() is called. MemberLookupTable *LookupTable = nullptr; /// Prepare the lookup table to make it ready for lookups. void prepareLookupTable(); /// Note that we have added a member into the iterable declaration context, /// so that it can also be added to the lookup table (if needed). void addedMember(Decl *member); /// Note that we have added an extension into the nominal type, /// so that its members can eventually be added to the lookup table. void addedExtension(ExtensionDecl *ext); /// A lookup table used to find the protocol conformances of /// a given nominal type. mutable ConformanceLookupTable *ConformanceTable = nullptr; /// Prepare the conformance table. void prepareConformanceTable() const; /// Returns the protocol requirements that \c Member conforms to. ArrayRef<ValueDecl *> getSatisfiedProtocolRequirementsForMember(const ValueDecl *Member, bool Sorted) const; friend class ASTContext; friend class MemberLookupTable; friend class ConformanceLookupTable; friend class ExtensionDecl; friend class DeclContext; friend class IterableDeclContext; friend class DirectLookupRequest; friend class LookupAllConformancesInContextRequest; friend ArrayRef<ValueDecl *> ValueDecl::getSatisfiedProtocolRequirements(bool Sorted) const; protected: Type DeclaredTy; Type DeclaredInterfaceTy; NominalTypeDecl(DeclKind K, DeclContext *DC, Identifier name, SourceLoc NameLoc, ArrayRef<InheritedEntry> inherited, GenericParamList *GenericParams) : GenericTypeDecl(K, DC, name, NameLoc, inherited, GenericParams), IterableDeclContext(IterableDeclContextKind::NominalTypeDecl) { Bits.NominalTypeDecl.AddedImplicitInitializers = false; ExtensionGeneration = 0; Bits.NominalTypeDecl.HasLazyConformances = false; Bits.NominalTypeDecl.IsComputingSemanticMembers = false; } friend class ProtocolType; public: using GenericTypeDecl::getASTContext; SourceRange getBraces() const { return Braces; } void setBraces(SourceRange braces) { Braces = braces; } /// Should this declaration behave as if it must be accessed /// resiliently, even when we're building a non-resilient module? /// /// This is used for diagnostics, because we do not want a behavior /// change between builds with resilience enabled and disabled. bool isFormallyResilient() const; /// Do we need to use resilient access patterns outside of this type's /// resilience domain? bool isResilient() const; /// Do we need to use resilient access patterns when accessing this /// type from the given module? bool isResilient(ModuleDecl *M, ResilienceExpansion expansion) const; /// Determine whether we have already attempted to add any /// implicitly-defined initializers to this declaration. bool addedImplicitInitializers() const { return Bits.NominalTypeDecl.AddedImplicitInitializers; } /// Note that we have attempted to add implicit initializers. void setAddedImplicitInitializers() { Bits.NominalTypeDecl.AddedImplicitInitializers = true; } /// getDeclaredType - Retrieve the type declared by this entity, without /// any generic parameters bound if this is a generic type. /// /// Since UnboundGenericType is on its way out, so is this method. Try to /// avoid introducing new callers if possible. Instead of passing around /// an UnboundGenericType, considering passing around the Decl itself /// instead. Type getDeclaredType() const; /// getDeclaredInterfaceType - Retrieve the type declared by this entity, with /// generic parameters bound if this is a generic type. Type getDeclaredInterfaceType() const; /// Add a new extension to this nominal type. void addExtension(ExtensionDecl *extension); /// Retrieve the set of extensions of this type. ExtensionRange getExtensions(); /// Special-behaviour flags passed to lookupDirect() enum class LookupDirectFlags { /// Whether to include @_implements members. /// Used by conformance-checking to find special @_implements members. IncludeAttrImplements = 1 << 0, }; /// Find all of the declarations with the given name within this nominal type /// and its extensions. /// /// This routine does not look into superclasses, nor does it consider /// protocols to which the nominal type conforms. Furthermore, the resulting /// set of declarations has not been filtered for visibility, nor have /// overridden declarations been removed. TinyPtrVector<ValueDecl *> lookupDirect(DeclName name, OptionSet<LookupDirectFlags> flags = OptionSet<LookupDirectFlags>()); /// Find the '_remote_<...>' counterpart function to a 'distributed func'. /// /// If the passed in function is not distributed this function returns null. AbstractFunctionDecl* lookupDirectRemoteFunc(AbstractFunctionDecl *func); /// Collect the set of protocols to which this type should implicitly /// conform, such as AnyObject (for classes). void getImplicitProtocols(SmallVectorImpl<ProtocolDecl *> &protocols); /// Look for conformances of this nominal type to the given /// protocol. /// /// \param module The module from which we initiate the search. /// FIXME: This is currently unused. /// /// \param protocol The protocol whose conformance is requested. /// \param conformances Will be populated with the set of protocol /// conformances found for this protocol. /// /// \returns true if any conformances were found. bool lookupConformance( ModuleDecl *module, ProtocolDecl *protocol, SmallVectorImpl<ProtocolConformance *> &conformances) const; /// Retrieve all of the protocols that this nominal type conforms to. SmallVector<ProtocolDecl *, 2> getAllProtocols() const; /// Retrieve all of the protocol conformances for this nominal type. SmallVector<ProtocolConformance *, 2> getAllConformances( bool sorted = false) const; /// Register an externally-created protocol conformance in the /// conformance lookup table. /// /// This is used by deserialization of module files to report /// conformances. void registerProtocolConformance(ProtocolConformance *conformance); void setConformanceLoader(LazyMemberLoader *resolver, uint64_t contextData); /// Is this the decl for Optional<T>? bool isOptionalDecl() const; /// Is this a key path type? Optional<KeyPathTypeKind> getKeyPathTypeKind() const; /// Retrieve information about this type as a property wrapper. PropertyWrapperTypeInfo getPropertyWrapperTypeInfo() const; /// Return a collection of the stored member variables of this type. ArrayRef<VarDecl *> getStoredProperties() const; /// Return a collection of the stored member variables of this type, along /// with placeholders for unimportable stored properties. ArrayRef<Decl *> getStoredPropertiesAndMissingMemberPlaceholders() const; /// Whether this nominal type qualifies as an actor, meaning that it is /// either an actor type or a protocol whose `Self` type conforms to the /// `Actor` protocol. bool isActor() const; /// Whether this nominal type qualifies as a distributed actor, meaning that /// it is either a distributed actor. bool isDistributedActor() const; /// Whether this nominal type qualifies as any actor (plain or distributed). bool isAnyActor() const; /// Return the range of semantics attributes attached to this NominalTypeDecl. auto getSemanticsAttrs() const -> decltype(getAttrs().getSemanticsAttrs()) { return getAttrs().getSemanticsAttrs(); } bool hasSemanticsAttr(StringRef attrValue) const { return getAttrs().hasSemanticsAttr(attrValue); } /// Returns true if we should emit assembly vision remarks on all methods of /// this nominal type. bool shouldEmitAssemblyVisionRemarksOnMethods() const { return getAttrs().hasAttribute<EmitAssemblyVisionRemarksAttr>(); } /// Whether this declaration has a synthesized memberwise initializer. bool hasMemberwiseInitializer() const; /// Retrieves the synthesized memberwise initializer for this declaration, /// or \c nullptr if it does not have one. ConstructorDecl *getMemberwiseInitializer() const; /// Retrieves the effective memberwise initializer for this declaration, or /// \c nullptr if it does not have one. /// /// An effective memberwise initializer is either a synthesized memberwise /// initializer or a user-defined initializer with the same type. /// /// The access level of the memberwise initializer is set to the minimum of: /// - Public, by default. This enables public nominal types to have public /// memberwise initializers. /// - The `public` default is important for synthesized member types, e.g. /// `TangentVector` structs synthesized during `Differentiable` derived /// conformances. Manually extending these types to define a public /// memberwise initializer causes a redeclaration error. /// - The minimum access level of memberwise-initialized properties in the /// nominal type declaration. /// /// Effective memberwise initializers are used only by derived conformances /// for `Self`-returning protocol requirements like `AdditiveArithmetic.+`. /// Such derived conformances require memberwise initialization. ConstructorDecl *getEffectiveMemberwiseInitializer(); /// Whether this declaration has a synthesized zero parameter default /// initializer. bool hasDefaultInitializer() const; bool isTypeErasedGenericClass() const; /// Retrieves the synthesized zero parameter default initializer for this /// declaration, or \c nullptr if it doesn't have one. ConstructorDecl *getDefaultInitializer() const; /// Force the synthesis of all members named \c member requiring semantic /// analysis and install them in the member list of this nominal type. /// /// \Note The use of this method in the compiler signals an architectural /// problem with the caller. Use \c TypeChecker::lookup* instead of /// introducing new usages. /// /// FIXME: This method presents a problem with respect to the consistency /// and idempotency of lookups in the compiler. If we instead had a model /// where lookup requests would explicitly return semantic members or parsed /// members this function could disappear. void synthesizeSemanticMembersIfNeeded(DeclName member); /// Retrieves the static 'shared' property of a global actor type, which /// is used to extract the actor instance. /// /// \returns the static 'shared' property for a global actor, or \c nullptr /// for types that are not global actors. VarDecl *getGlobalActorInstance() const; bool hasDistributedActorLocalInitializer() const; /// Whether this type is a global actor, which can be used as an /// attribute to decorate declarations for inclusion in the actor-isolated /// state denoted by this type. bool isGlobalActor() const { return getGlobalActorInstance() != nullptr; } // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() >= DeclKind::First_NominalTypeDecl && D->getKind() <= DeclKind::Last_NominalTypeDecl; } static bool classof(const GenericTypeDecl *D) { return D->getKind() >= DeclKind::First_NominalTypeDecl && D->getKind() <= DeclKind::Last_NominalTypeDecl; } static bool classof(const DeclContext *C) { if (auto D = C->getAsDecl()) return classof(D); return false; } static bool classof(const IterableDeclContext *C) { return C->getIterableContextKind() == IterableDeclContextKind::NominalTypeDecl; } static bool classof(const NominalTypeDecl *D) { return true; } static bool classof(const ExtensionDecl *D) { return false; } }; /// This is the declaration of an enum. /// /// For example: /// /// \code /// enum Bool { /// case false /// case true /// } /// /// enum Optional<T> { /// case none /// case some(T) /// } /// \endcode /// /// The type of the decl itself is a MetatypeType; use getDeclaredType() /// to get the declared type ("Bool" or "Optional" in the above example). class EnumDecl final : public NominalTypeDecl { SourceLoc EnumLoc; enum SemanticInfoFlags : uint8_t { // Is the raw type valid? HasComputedRawType = 1 << 0, // Is the complete set of (auto-incremented) raw values available? HasFixedRawValues = 1 << 1, // Is the complete set of raw values type checked? HasFixedRawValuesAndTypes = 1 << 2, }; OptionSet<SemanticInfoFlags> SemanticFlags; friend class EnumRawValuesRequest; friend class EnumRawTypeRequest; public: EnumDecl(SourceLoc EnumLoc, Identifier Name, SourceLoc NameLoc, ArrayRef<InheritedEntry> Inherited, GenericParamList *GenericParams, DeclContext *DC); SourceLoc getStartLoc() const { return EnumLoc; } SourceRange getSourceRange() const { return SourceRange(EnumLoc, getBraces().End); } public: /// A range for iterating the elements of an enum. using ElementRange = DowncastFilterRange<EnumElementDecl, DeclRange>; /// A range for iterating the cases of an enum. using CaseRange = DowncastFilterRange<EnumCaseDecl, DeclRange>; /// Return a range that iterates over all the elements of an enum. ElementRange getAllElements() const { return ElementRange(getMembers()); } unsigned getNumElements() const { auto eltRange = getAllElements(); return std::distance(eltRange.begin(), eltRange.end()); } /// If this enum has a unique element, return it. A unique element can /// either hold a value or not, and the existence of one unique element does /// not imply the existence or non-existence of the opposite unique element. EnumElementDecl *getUniqueElement(bool hasValue) const; /// Return a range that iterates over all the cases of an enum. CaseRange getAllCases() const { return CaseRange(getMembers()); } /// Insert all of the 'case' element declarations into a DenseSet. void getAllElements(llvm::DenseSet<EnumElementDecl*> &elements) const { for (auto elt : getAllElements()) elements.insert(elt); } /// Whether this enum has a raw value type that recursively references itself. bool hasCircularRawValue() const; /// Record that this enum has had all of its raw values computed. void setHasFixedRawValues(); // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == DeclKind::Enum; } static bool classof(const GenericTypeDecl *D) { return D->getKind() == DeclKind::Enum; } static bool classof(const NominalTypeDecl *D) { return D->getKind() == DeclKind::Enum; } static bool classof(const DeclContext *C) { if (auto D = C->getAsDecl()) return classof(D); return false; } static bool classof(const IterableDeclContext *C) { auto NTD = dyn_cast<NominalTypeDecl>(C); return NTD && classof(NTD); } /// Determine whether this enum declares a raw type in its inheritance clause. bool hasRawType() const { return (bool)getRawType(); } /// Retrieve the declared raw type of the enum from its inheritance clause, /// or null if it has none. Type getRawType() const; /// Set the raw type of the enum from its inheritance clause. void setRawType(Type rawType); /// True if none of the enum cases have associated values. /// /// Note that this is true for enums with absolutely no cases. bool hasOnlyCasesWithoutAssociatedValues() const; /// True if any of the enum cases have availability annotations. /// /// Note that this is false for enums with absolutely no cases. bool hasPotentiallyUnavailableCaseValue() const; /// True if the enum has cases. bool hasCases() const { return !getAllElements().empty(); } /// True if the enum is marked 'indirect'. bool isIndirect() const { return getAttrs().hasAttribute<IndirectAttr>(); } /// True if the enum can be exhaustively switched within \p useDC. /// /// Note that this property is \e not necessarily true for all children of /// \p useDC. In particular, an inlinable function does not get to switch /// exhaustively over a non-exhaustive enum declared in the same module. /// /// This is the predicate used when deciding if a switch statement needs a /// default case. It should not be used for optimization or code generation. /// /// \sa isEffectivelyExhaustive bool isFormallyExhaustive(const DeclContext *useDC) const; /// True if the enum can be exhaustively switched within a function defined /// within \p M, with \p expansion specifying whether the function is /// inlinable. /// /// This is the predicate used when making optimization and code generation /// decisions. It should not be used at the AST or semantic level. /// /// \sa isFormallyExhaustive bool isEffectivelyExhaustive(ModuleDecl *M, ResilienceExpansion expansion) const; }; /// StructDecl - This is the declaration of a struct, for example: /// /// struct Complex { var R : Double, I : Double } /// /// The type of the decl itself is a MetatypeType; use getDeclaredType() /// to get the declared type ("Complex" in the above example). class StructDecl final : public NominalTypeDecl { SourceLoc StructLoc; // We import C++ class templates as generic structs. Then when in Swift code // we want to substitute generic parameters with actual arguments, we // convert the arguments to C++ equivalents and ask Clang to instantiate the // C++ template. Then we import the C++ class template instantiation // as a non-generic structs with a name prefixed with `__CxxTemplateInst`. // // To reiterate: // 1) We need to have a C++ class template declaration in the Clang AST. This // declaration is simply imported from a Clang module. // 2) We need a Swift generic struct in the Swift AST. This will provide // template arguments to Clang. // 3) We produce a C++ class template instantiation in the Clang AST // using 1) and 2). This declaration does not exist in the Clang module // AST initially in the general case, it's added there on instantiation. // 4) We import the instantiation as a Swift struct, with the name prefixed // with `__CxxTemplateInst`. // // This causes a problem for serialization/deserialization of the Swift // module. Imagine the Swift struct from 4) is used in the function return // type. We cannot just serialize the non generic Swift struct, because on // deserialization we would need to find its backing Clang declaration // (the C++ class template instantiation), and it won't be found in the // general case. Only the C++ class template from step 1) is in the Clang // AST. // // What we need is to serialize enough information to be // able to instantiate C++ class template on deserialization. It turns out // that all that information is conveniently covered by the BoundGenericType, // which we store in this field. The field is set during the typechecking at // the time when we instantiate the C++ class template. // // Alternative, and likely better solution long term, is to serialize the // C++ class template instantiation into a synthetic Clang module, and load // this Clang module on deserialization. Type TemplateInstantiationType = Type(); public: StructDecl(SourceLoc StructLoc, Identifier Name, SourceLoc NameLoc, ArrayRef<InheritedEntry> Inherited, GenericParamList *GenericParams, DeclContext *DC); SourceLoc getStartLoc() const { return StructLoc; } SourceRange getSourceRange() const { return SourceRange(StructLoc, getBraces().End); } // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == DeclKind::Struct; } static bool classof(const GenericTypeDecl *D) { return D->getKind() == DeclKind::Struct; } static bool classof(const NominalTypeDecl *D) { return D->getKind() == DeclKind::Struct; } static bool classof(const DeclContext *C) { if (auto D = C->getAsDecl()) return classof(D); return false; } static bool classof(const IterableDeclContext *C) { auto NTD = dyn_cast<NominalTypeDecl>(C); return NTD && classof(NTD); } /// Does this struct contain unreferenceable storage, such as C fields that /// cannot be represented in Swift? bool hasUnreferenceableStorage() const { return Bits.StructDecl.HasUnreferenceableStorage; } void setHasUnreferenceableStorage(bool v) { Bits.StructDecl.HasUnreferenceableStorage = v; } bool isCxxNonTrivial() const { return Bits.StructDecl.IsCxxNonTrivial; } void setIsCxxNonTrivial(bool v) { Bits.StructDecl.IsCxxNonTrivial = v; } Type getTemplateInstantiationType() const { return TemplateInstantiationType; } void setTemplateInstantiationType(Type t) { TemplateInstantiationType = t; } }; /// This is the base type for AncestryOptions. Each flag describes possible /// interesting kinds of superclasses that a class may have. enum class AncestryFlags : uint8_t { /// The class or one of its superclasses is @objc. ObjC = (1<<0), /// The class or one of its superclasses is @objcMembers. ObjCMembers = (1<<1), /// The class or one of its superclasses is generic. Generic = (1<<2), /// The class or one of its superclasses is resilient. Resilient = (1<<3), /// The class or one of its superclasses has resilient metadata and is in a /// different resilience domain. ResilientOther = (1<<4), /// The class or one of its superclasses is imported from Clang. ClangImported = (1<<5), /// The class or one of its superclasses requires stored property initializers. RequiresStoredPropertyInits = (1<<6), /// The class uses the ObjC object model (reference counting, /// isa encoding, etc.). ObjCObjectModel = (1<<7), }; /// Return type of ClassDecl::checkAncestry(). Describes a set of interesting /// kinds of superclasses that a class may have. using AncestryOptions = OptionSet<AncestryFlags>; /// ClassDecl - This is the declaration of a class, for example: /// /// class Complex { var R : Double, I : Double } /// /// The type of the decl itself is a MetatypeType; use getDeclaredType() /// to get the declared type ("Complex" in the above example). class ClassDecl final : public NominalTypeDecl { class ObjCMethodLookupTable; SourceLoc ClassLoc; ObjCMethodLookupTable *ObjCMethodLookup = nullptr; /// Create the Objective-C member lookup table. void createObjCMethodLookup(); struct { /// The superclass decl and a bit to indicate whether the /// superclass was computed yet or not. llvm::PointerIntPair<ClassDecl *, 1, bool> SuperclassDecl; /// The superclass type and a bit to indicate whether the /// superclass was computed yet or not. llvm::PointerIntPair<Type, 1, bool> SuperclassType; } LazySemanticInfo; Optional<bool> getCachedInheritsSuperclassInitializers() const { if (Bits.ClassDecl.ComputedInheritsSuperclassInits) return Bits.ClassDecl.InheritsSuperclassInits; return None; } Optional<bool> getCachedHasMissingDesignatedInitializers() const { if (!Bits.ClassDecl.ComputedHasMissingDesignatedInitializers) { // Force loading all the members, which will add this attribute if any of // members are determined to be missing while loading. auto mutableThis = const_cast<ClassDecl *>(this); (void)mutableThis->lookupDirect(DeclBaseName::createConstructor()); } if (Bits.ClassDecl.ComputedHasMissingDesignatedInitializers) return Bits.ClassDecl.HasMissingDesignatedInitializers; return None; } void setHasMissingDesignatedInitializers(bool value) { Bits.ClassDecl.HasMissingDesignatedInitializers = value; Bits.ClassDecl.ComputedHasMissingDesignatedInitializers = true; } /// Marks that this class inherits convenience initializers from its /// superclass. void setInheritsSuperclassInitializers(bool value) { Bits.ClassDecl.InheritsSuperclassInits = value; Bits.ClassDecl.ComputedInheritsSuperclassInits = true; } friend class SuperclassDeclRequest; friend class SuperclassTypeRequest; friend class ABIMembersRequest; friend class HasMissingDesignatedInitializersRequest; friend class InheritsSuperclassInitializersRequest; public: ClassDecl(SourceLoc ClassLoc, Identifier Name, SourceLoc NameLoc, ArrayRef<InheritedEntry> Inherited, GenericParamList *GenericParams, DeclContext *DC, bool isActor); SourceLoc getStartLoc() const { return ClassLoc; } SourceRange getSourceRange() const { return SourceRange(ClassLoc, getBraces().End); } /// Determine whether the member area of this class's metadata (which consists /// of field offsets and vtable entries) is to be considered opaque by clients. /// /// Note that even @_fixed_layout classes have resilient metadata if they are /// in a resilient module. bool hasResilientMetadata() const; /// Determine whether this class has resilient metadata when accessed from the /// given module and resilience expansion. bool hasResilientMetadata(ModuleDecl *M, ResilienceExpansion expansion) const; /// Determine whether this class has a superclass. bool hasSuperclass() const { return (bool)getSuperclassDecl(); } /// Retrieve the superclass of this class, or null if there is no superclass. Type getSuperclass() const; /// Retrieve the ClassDecl for the superclass of this class, or null if there /// is no superclass. ClassDecl *getSuperclassDecl() const; /// Check if this class is a superclass or equal to the given class. bool isSuperclassOf(ClassDecl *other) const; /// Set the superclass of this class. void setSuperclass(Type superclass); /// Walk this class and all of the superclasses of this class, transitively, /// invoking the callback function for each class. /// /// \param fn The callback function that will be invoked for each superclass. /// It can return \c Continue to continue the traversal. Returning /// \c SkipChildren halts the search and returns \c false, while returning /// \c Stop halts the search and returns \c true. /// /// \returns \c true if \c fn returned \c Stop for any class, \c false /// otherwise. bool walkSuperclasses( llvm::function_ref<TypeWalker::Action(ClassDecl *)> fn) const; //// Whether this class requires all of its stored properties to //// have initializers in the class definition. bool requiresStoredPropertyInits() const { return checkAncestry(AncestryFlags::RequiresStoredPropertyInits); } /// \see getForeignClassKind enum class ForeignKind : uint8_t { /// A normal Swift or Objective-C class. Normal = 0, /// An imported Core Foundation type. These are AnyObject-compatible but /// do not have runtime metadata. CFType, /// An imported Objective-C type whose class and metaclass symbols are not /// both available at link-time but can be accessed through the Objective-C /// runtime. RuntimeOnly }; /// Whether this class is "foreign", meaning that it is implemented /// by a runtime that Swift does not have first-class integration /// with. This generally means that: /// - class data is either abstracted or cannot be made to /// fit with Swift's metatype schema, and/or /// - there is no facility for subclassing or adding polymorphic /// methods to the class. /// /// We may find ourselves wanting to break this bit into more /// precise chunks later. ForeignKind getForeignClassKind() const { return static_cast<ForeignKind>(Bits.ClassDecl.RawForeignKind); } void setForeignClassKind(ForeignKind kind) { Bits.ClassDecl.RawForeignKind = static_cast<unsigned>(kind); } /// Returns true if this class is any kind of "foreign class". /// /// \see getForeignClassKind bool isForeign() const { return getForeignClassKind() != ForeignKind::Normal; } /// Whether the class is (known to be) a default actor. bool isDefaultActor() const; bool isDefaultActor(ModuleDecl *M, ResilienceExpansion expansion) const; /// Whether the class is known to be a *root* default actor, /// i.e. the first class in its hierarchy that is a default actor. bool isRootDefaultActor() const; bool isRootDefaultActor(ModuleDecl *M, ResilienceExpansion expansion) const; /// Whether the class was explicitly declared with the `actor` keyword. bool isExplicitActor() const { return Bits.ClassDecl.IsActor; } /// Whether the class was explicitly declared with the `distributed actor` keywords. bool isExplicitDistributedActor() const { return isExplicitActor() && getAttrs().hasAttribute<DistributedActorAttr>(); } /// Get the closest-to-root superclass that's an actor class. const ClassDecl *getRootActorClass() const; /// Fetch this class's unownedExecutor property, if it has one. const VarDecl *getUnownedExecutorProperty() const; /// Is this the NSObject class type? bool isNSObject() const; /// Whether the class directly inherits from NSObject but should use /// Swift's native object model. bool isNativeNSObjectSubclass() const; /// Whether the class uses the ObjC object model (reference counting, /// allocation, etc.) instead of the Swift model. bool usesObjCObjectModel() const { return checkAncestry(AncestryFlags::ObjCObjectModel); } /// Returns true if the class has designated initializers that are not listed /// in its members. /// /// This can occur, for example, if the class is an Objective-C class with /// initializers that cannot be represented in Swift. bool hasMissingDesignatedInitializers() const; /// Returns true if the class has missing members that require vtable entries. /// /// In this case, the class cannot be subclassed, because we cannot construct /// the vtable for the subclass. bool hasMissingVTableEntries() const; void setHasMissingVTableEntries(bool newValue = true) { Bits.ClassDecl.ComputedHasMissingVTableEntries = 1; Bits.ClassDecl.HasMissingVTableEntries = newValue; } /// Returns true if this class cannot be used with weak or unowned /// references. /// /// Note that this is true if this class or any of its ancestor classes /// are marked incompatible. bool isIncompatibleWithWeakReferences() const; void setIsIncompatibleWithWeakReferences(bool newValue = true) { Bits.ClassDecl.IsIncompatibleWithWeakReferences = newValue; } /// Find a method of a class that overrides a given method. /// Return nullptr, if no such method exists. AbstractFunctionDecl *findOverridingDecl( const AbstractFunctionDecl *method) const; /// Find a method implementation which will be used when a given method /// is invoked on an instance of this class. This implementation may stem /// either from a class itself or its direct or indirect superclasses. AbstractFunctionDecl *findImplementingMethod( const AbstractFunctionDecl *method) const; /// Retrieve the destructor for this class. DestructorDecl *getDestructor() const; /// Determine whether this class inherits the convenience initializers /// from its superclass. bool inheritsSuperclassInitializers() const; /// Walks the class hierarchy starting from this class, checking various /// conditions. AncestryOptions checkAncestry() const; /// Check if the class has ancestry of the given kind. bool checkAncestry(AncestryFlags flag) const { return checkAncestry().contains(flag); } /// The type of metaclass to use for a class. enum class MetaclassKind : uint8_t { ObjC, SwiftStub, }; /// Determine which sort of metaclass to use for this class MetaclassKind getMetaclassKind() const; /// Retrieve the name to use for this class when interoperating with /// the Objective-C runtime. StringRef getObjCRuntimeName(llvm::SmallVectorImpl<char> &buffer) const; using NominalTypeDecl::lookupDirect; /// Look in this class and its extensions (but not any of its protocols or /// superclasses) for declarations with a given Objective-C selector. /// /// Note that this can find methods, initializers, deinitializers, /// getters, and setters. /// /// \param selector The Objective-C selector of the method we're /// looking for. /// /// \param isInstance Whether we are looking for an instance method /// (vs. a class method). TinyPtrVector<AbstractFunctionDecl *> lookupDirect(ObjCSelector selector, bool isInstance); /// Record the presence of an @objc method with the given selector. void recordObjCMethod(AbstractFunctionDecl *method, ObjCSelector selector); // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == DeclKind::Class; } static bool classof(const GenericTypeDecl *D) { return D->getKind() == DeclKind::Class; } static bool classof(const NominalTypeDecl *D) { return D->getKind() == DeclKind::Class; } static bool classof(const DeclContext *C) { if (auto D = C->getAsDecl()) return classof(D); return false; } static bool classof(const IterableDeclContext *C) { auto NTD = dyn_cast<NominalTypeDecl>(C); return NTD && classof(NTD); } /// Returns true if the decl uses the Objective-C generics model. /// /// This is true of imported Objective-C classes. bool isTypeErasedGenericClass() const { return hasClangNode() && isGenericContext() && isObjC(); } /// True if the class is known to be implemented in Swift. bool hasKnownSwiftImplementation() const { return !hasClangNode(); } }; /// A convenience wrapper around the \c SelfReferencePosition::Kind enum. struct SelfReferencePosition final { enum Kind : uint8_t { None, Covariant, Contravariant, Invariant }; private: Kind kind; public: SelfReferencePosition(Kind kind) : kind(kind) {} SelfReferencePosition flipped() const { switch (kind) { case None: case Invariant: return *this; case Covariant: return Contravariant; case Contravariant: return Covariant; } llvm_unreachable("unhandled self reference position!"); } explicit operator bool() const { return kind > None; } operator Kind() const { return kind; } }; /// Describes the least favorable positions at which a requirement refers /// to 'Self' in terms of variance, for use in the is-inheritable and /// is-available-existential checks. struct SelfReferenceInfo final { using Position = SelfReferencePosition; bool hasCovariantSelfResult; Position selfRef; Position assocTypeRef; /// A reference to 'Self'. static SelfReferenceInfo forSelfRef(Position position) { assert(position); return SelfReferenceInfo(false, position, Position::None); } /// A reference to 'Self' through an associated type. static SelfReferenceInfo forAssocTypeRef(Position position) { assert(position); return SelfReferenceInfo(false, Position::None, position); } SelfReferenceInfo operator|=(const SelfReferenceInfo &pos) { hasCovariantSelfResult |= pos.hasCovariantSelfResult; if (pos.selfRef > selfRef) { selfRef = pos.selfRef; } if (pos.assocTypeRef > assocTypeRef) { assocTypeRef = pos.assocTypeRef; } return *this; } explicit operator bool() const { return hasCovariantSelfResult || selfRef || assocTypeRef; } SelfReferenceInfo() : hasCovariantSelfResult(false), selfRef(Position::None), assocTypeRef(Position::None) {} private: SelfReferenceInfo(bool hasCovariantSelfResult, Position selfRef, Position assocTypeRef) : hasCovariantSelfResult(hasCovariantSelfResult), selfRef(selfRef), assocTypeRef(assocTypeRef) {} }; /// The set of known protocols for which derived conformances are supported. enum class KnownDerivableProtocolKind : uint8_t { RawRepresentable, OptionSet, CaseIterable, Comparable, Equatable, Hashable, BridgedNSError, CodingKey, Encodable, Decodable, AdditiveArithmetic, Differentiable, Actor, DistributedActor, }; /// ProtocolDecl - A declaration of a protocol, for example: /// /// protocol Drawable { /// func draw() /// } /// /// Every protocol has an implicitly-created 'Self' generic parameter that /// stands for a type that conforms to the protocol. For example, /// /// protocol Cloneable { /// func clone() -> Self /// } /// class ProtocolDecl final : public NominalTypeDecl { SourceLoc ProtocolLoc; ArrayRef<ProtocolDecl *> InheritedProtocols; struct { /// The superclass decl and a bit to indicate whether the /// superclass was computed yet or not. llvm::PointerIntPair<ClassDecl *, 1, bool> SuperclassDecl; /// The superclass type and a bit to indicate whether the /// superclass was computed yet or not. llvm::PointerIntPair<Type, 1, bool> SuperclassType; } LazySemanticInfo; /// The generic signature representing exactly the new requirements introduced /// by this protocol. const Requirement *RequirementSignature = nullptr; /// Returns the cached result of \c requiresClass or \c None if it hasn't yet /// been computed. Optional<bool> getCachedRequiresClass() const { if (Bits.ProtocolDecl.RequiresClassValid) return Bits.ProtocolDecl.RequiresClass; return None; } /// Caches the result of \c requiresClass void setCachedRequiresClass(bool requiresClass) { Bits.ProtocolDecl.RequiresClassValid = true; Bits.ProtocolDecl.RequiresClass = requiresClass; } /// Returns the cached result of \c existentialConformsToSelf or \c None if it /// hasn't yet been computed. Optional<bool> getCachedExistentialConformsToSelf() const { if (Bits.ProtocolDecl.ExistentialConformsToSelfValid) return Bits.ProtocolDecl.ExistentialConformsToSelf; return None; } /// Caches the result of \c existentialConformsToSelf void setCachedExistentialConformsToSelf(bool result) { Bits.ProtocolDecl.ExistentialConformsToSelfValid = true; Bits.ProtocolDecl.ExistentialConformsToSelf = result; } /// Returns the cached result of \c existentialTypeSupported or \c None if it /// hasn't yet been computed. Optional<bool> getCachedExistentialTypeSupported() { if (Bits.ProtocolDecl.ExistentialTypeSupportedValid) return Bits.ProtocolDecl.ExistentialTypeSupported; return None; } /// Caches the result of \c existentialTypeSupported void setCachedExistentialTypeSupported(bool supported) { Bits.ProtocolDecl.ExistentialTypeSupportedValid = true; Bits.ProtocolDecl.ExistentialTypeSupported = supported; } bool hasLazyRequirementSignature() const { return Bits.ProtocolDecl.HasLazyRequirementSignature; } friend class SuperclassDeclRequest; friend class SuperclassTypeRequest; friend class RequirementSignatureRequest; friend class ProtocolRequiresClassRequest; friend class ExistentialConformsToSelfRequest; friend class ExistentialTypeSupportedRequest; friend class InheritedProtocolsRequest; public: ProtocolDecl(DeclContext *DC, SourceLoc ProtocolLoc, SourceLoc NameLoc, Identifier Name, ArrayRef<InheritedEntry> Inherited, TrailingWhereClause *TrailingWhere); using Decl::getASTContext; /// Retrieve the set of protocols inherited from this protocol. ArrayRef<ProtocolDecl *> getInheritedProtocols() const; /// Determine whether this protocol has a superclass. bool hasSuperclass() const { return (bool)getSuperclassDecl(); } /// Retrieve the superclass of this protocol, or null if there is no superclass. Type getSuperclass() const; /// Retrieve the ClassDecl for the superclass of this protocol, or null if there /// is no superclass. ClassDecl *getSuperclassDecl() const; /// Set the superclass of this protocol. void setSuperclass(Type superclass); /// Retrieve the set of AssociatedTypeDecl members of this protocol; this /// saves loading the set of members in cases where there's no possibility of /// a protocol having nested types (ObjC protocols). llvm::TinyPtrVector<AssociatedTypeDecl *> getAssociatedTypeMembers() const; /// Returns a protocol requirement with the given name, or nullptr if the /// name has multiple overloads, or no overloads at all. ValueDecl *getSingleRequirement(DeclName name) const; /// Returns an associated type with the given name, or nullptr if one does /// not exist. AssociatedTypeDecl *getAssociatedType(Identifier name) const; /// Walk this protocol and all of the protocols inherited by this protocol, /// transitively, invoking the callback function for each protocol. /// /// \param fn The callback function that will be invoked for each inherited /// protocol. It can return \c Continue to continue the traversal, /// \c SkipChildren to avoid visiting the children of the given protocol /// but continue the search, and \c Stop to halt the search. /// /// \returns \c true if \c fn returned \c Stop for any protocol, \c false /// otherwise. bool walkInheritedProtocols( llvm::function_ref<TypeWalker::Action(ProtocolDecl *)> fn) const; /// Determine whether this protocol inherits from the given ("super") /// protocol. bool inheritsFrom(const ProtocolDecl *Super) const; SourceLoc getStartLoc() const { return ProtocolLoc; } SourceRange getSourceRange() const { return SourceRange(ProtocolLoc, getBraces().End); } /// True if this protocol can only be conformed to by class types. bool requiresClass() const; /// Determine whether an existential conforming to this protocol can be /// matched with a generic type parameter constrained to this protocol. /// This is only permitted if there is nothing "non-trivial" that we /// can do with the metatype, which means the protocol must not have /// any static methods and must be declared @objc. bool existentialConformsToSelf() const; /// Does this protocol require a self-conformance witness table? bool requiresSelfConformanceWitnessTable() const; /// Find direct Self references within the given requirement. /// /// \param treatNonResultCovariantSelfAsInvariant If true, 'Self' is only /// assumed to be covariant in a top-level non-function type, or in the /// eventual result type of a top-level function type. SelfReferenceInfo findProtocolSelfReferences(const ValueDecl *decl, bool treatNonResultCovariantSelfAsInvariant) const; /// Determine whether we are allowed to refer to an existential type /// conforming to this protocol. This is only permitted if the type of /// the member does not contain any associated types, and does not /// contain 'Self' in 'parameter' or 'other' position. bool isAvailableInExistential(const ValueDecl *decl) const; /// Determine whether we are allowed to refer to an existential type /// conforming to this protocol. This is only permitted if the types of /// all the members do not contain any associated types, and do not /// contain 'Self' in 'parameter' or 'other' position. bool existentialTypeSupported() const; /// Returns a list of protocol requirements that must be assessed to /// determine a concrete's conformance effect polymorphism kind. PolymorphicEffectRequirementList getPolymorphicEffectRequirements( EffectKind kind) const; bool hasPolymorphicEffect(EffectKind kind) const; /// Determine whether this is a "marker" protocol, meaning that is indicates /// semantics but has no corresponding witness table. bool isMarkerProtocol() const; /// Is a protocol that can only be conformed by distributed actors. /// Such protocols are allowed to contain distributed functions. bool inheritsFromDistributedActor() const; private: void computeKnownProtocolKind() const; bool areInheritedProtocolsValid() const { return Bits.ProtocolDecl.InheritedProtocolsValid; } void setInheritedProtocolsValid() { Bits.ProtocolDecl.InheritedProtocolsValid = true; } public: /// If this is known to be a compiler-known protocol, returns the kind. /// Otherwise returns None. Optional<KnownProtocolKind> getKnownProtocolKind() const { if (Bits.ProtocolDecl.KnownProtocol == 0) computeKnownProtocolKind(); if (Bits.ProtocolDecl.KnownProtocol == 1) return None; return static_cast<KnownProtocolKind>(Bits.ProtocolDecl.KnownProtocol - 2); } Optional<KnownDerivableProtocolKind> getKnownDerivableProtocolKind() const; /// Check whether this protocol is of a specific, known protocol kind. bool isSpecificProtocol(KnownProtocolKind kind) const { if (auto knownKind = getKnownProtocolKind()) return *knownKind == kind; return false; } /// Whether this protocol has a circular reference in its list of inherited /// protocols. bool hasCircularInheritedProtocols() const; /// Returns true if the protocol has requirements that are not listed in its /// members. /// /// This can occur, for example, if the protocol is an Objective-C protocol /// with requirements that cannot be represented in Swift. bool hasMissingRequirements() const { (void)getMembers(); return Bits.ProtocolDecl.HasMissingRequirements; } void setHasMissingRequirements(bool newValue) { Bits.ProtocolDecl.HasMissingRequirements = newValue; } /// Returns the default type witness for an associated type, or a null /// type if there is no default. Type getDefaultTypeWitness(AssociatedTypeDecl *assocType) const; /// Set the default type witness for an associated type. void setDefaultTypeWitness(AssociatedTypeDecl *assocType, Type witness); /// Returns the default witness for a requirement, or nullptr if there is /// no default. Witness getDefaultWitness(ValueDecl *requirement) const; /// Record the default witness for a requirement. void setDefaultWitness(ValueDecl *requirement, Witness witness); /// Returns the default associated conformance witness for an associated /// type, or \c None if there is no default. ProtocolConformanceRef getDefaultAssociatedConformanceWitness(CanType association, ProtocolDecl *requirement) const; /// Set the default associated conformance witness for the given /// associated conformance. void setDefaultAssociatedConformanceWitness( CanType association, ProtocolDecl *requirement, ProtocolConformanceRef conformance); /// Retrieve the name to use for this protocol when interoperating /// with the Objective-C runtime. StringRef getObjCRuntimeName(llvm::SmallVectorImpl<char> &buffer) const; /// Retrieve the requirements that describe this protocol. /// /// These are the requirements including any inherited protocols /// and conformances for associated types that are introduced in this /// protocol. Requirements implied via any other protocol (e.g., inherited /// protocols of the inherited protocols) are not mentioned. The conformance /// requirements listed here become entries in the witness table. ArrayRef<Requirement> getRequirementSignature() const; /// Is the requirement signature currently being computed? bool isComputingRequirementSignature() const; /// Has the requirement signature been computed yet? bool isRequirementSignatureComputed() const { return RequirementSignature != nullptr; } void setRequirementSignature(ArrayRef<Requirement> requirements); void setLazyRequirementSignature(LazyMemberLoader *lazyLoader, uint64_t requirementSignatureData); private: ArrayRef<Requirement> getCachedRequirementSignature() const; public: // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == DeclKind::Protocol; } static bool classof(const GenericTypeDecl *D) { return D->getKind() == DeclKind::Protocol; } static bool classof(const NominalTypeDecl *D) { return D->getKind() == DeclKind::Protocol; } static bool classof(const DeclContext *C) { if (auto D = C->getAsDecl()) return classof(D); return false; } static bool classof(const IterableDeclContext *C) { auto NTD = dyn_cast<NominalTypeDecl>(C); return NTD && classof(NTD); } }; /// AbstractStorageDecl - This is the common superclass for VarDecl and /// SubscriptDecl, representing potentially settable memory locations. class AbstractStorageDecl : public ValueDecl { friend class SetterAccessLevelRequest; friend class IsGetterMutatingRequest; friend class IsSetterMutatingRequest; friend class OpaqueReadOwnershipRequest; friend class StorageImplInfoRequest; friend class RequiresOpaqueAccessorsRequest; friend class RequiresOpaqueModifyCoroutineRequest; friend class SynthesizeAccessorRequest; public: static const size_t MaxNumAccessors = 255; private: /// A record of the accessors for the declaration. class alignas(1 << 3) AccessorRecord final : private llvm::TrailingObjects<AccessorRecord, AccessorDecl*> { friend TrailingObjects; using AccessorIndex = uint8_t; static const AccessorIndex InvalidIndex = 0; /// The range of the braces around the accessor clause. SourceRange Braces; /// The number of accessors currently stored in this record. AccessorIndex NumAccessors; /// The storage capacity of this record for accessors. Always includes /// enough space for adding opaque accessors to the record, which are the /// only accessors that should ever be added retroactively; hence this /// field is only here for the purposes of safety checks. AccessorIndex AccessorsCapacity; /// Either 0, meaning there is no registered accessor of the given kind, /// or the index+1 of the accessor in the accessors array. AccessorIndex AccessorIndices[NumAccessorKinds]; AccessorRecord(SourceRange braces, ArrayRef<AccessorDecl*> accessors, AccessorIndex accessorsCapacity); public: static AccessorRecord *create(ASTContext &ctx, SourceRange braces, ArrayRef<AccessorDecl*> accessors); SourceRange getBracesRange() const { return Braces; } inline AccessorDecl *getAccessor(AccessorKind kind) const; ArrayRef<AccessorDecl *> getAllAccessors() const { return { getTrailingObjects<AccessorDecl*>(), NumAccessors }; } void addOpaqueAccessor(AccessorDecl *accessor); private: MutableArrayRef<AccessorDecl *> getAccessorsBuffer() { return { getTrailingObjects<AccessorDecl*>(), NumAccessors }; } bool registerAccessor(AccessorDecl *accessor, AccessorIndex index); }; llvm::PointerIntPair<AccessorRecord*, 3, OptionalEnum<AccessLevel>> Accessors; struct { unsigned IsGetterMutatingComputed : 1; unsigned IsGetterMutating : 1; unsigned IsSetterMutatingComputed : 1; unsigned IsSetterMutating : 1; unsigned OpaqueReadOwnershipComputed : 1; unsigned OpaqueReadOwnership : 2; unsigned ImplInfoComputed : 1; unsigned RequiresOpaqueAccessorsComputed : 1; unsigned RequiresOpaqueAccessors : 1; unsigned RequiresOpaqueModifyCoroutineComputed : 1; unsigned RequiresOpaqueModifyCoroutine : 1; } LazySemanticInfo = { }; /// The implementation info for the accessors. StorageImplInfo ImplInfo; /// Add a synthesized accessor. void setSynthesizedAccessor(AccessorKind kind, AccessorDecl *getter); protected: AbstractStorageDecl(DeclKind Kind, bool IsStatic, DeclContext *DC, DeclName Name, SourceLoc NameLoc, StorageIsMutable_t supportsMutation) : ValueDecl(Kind, DC, Name, NameLoc), ImplInfo(StorageImplInfo::getSimpleStored(supportsMutation)) { Bits.AbstractStorageDecl.IsStatic = IsStatic; } public: /// Should this declaration be treated as if annotated with transparent /// attribute. bool isTransparent() const; /// Is this a type ('static') variable? bool isStatic() const { return Bits.AbstractStorageDecl.IsStatic; } void setStatic(bool IsStatic) { Bits.AbstractStorageDecl.IsStatic = IsStatic; } /// \returns the way 'static'/'class' should be spelled for this declaration. StaticSpellingKind getCorrectStaticSpelling() const; /// Return the interface type of the stored value. Type getValueInterfaceType() const; /// Determine how this storage is implemented. StorageImplInfo getImplInfo() const; /// Overwrite the registered implementation-info. This should be /// used carefully. void setImplInfo(StorageImplInfo implInfo) { LazySemanticInfo.ImplInfoComputed = 1; ImplInfo = implInfo; } ReadImplKind getReadImpl() const { return getImplInfo().getReadImpl(); } WriteImplKind getWriteImpl() const { return getImplInfo().getWriteImpl(); } ReadWriteImplKind getReadWriteImpl() const { return getImplInfo().getReadWriteImpl(); } /// Return true if this is a VarDecl that has storage associated with /// it. bool hasStorage() const { return getImplInfo().hasStorage(); } /// Return true if this storage has the basic accessors/capability /// to be mutated. This is generally constant after the accessors are /// installed by the parser/importer/whatever. /// /// Note that this is different from the mutability of the declaration /// in the user language: sometimes we can assign to declarations that /// don't support mutation (e.g. to initialize them), and sometimes we /// can't mutate things that do support mutation (e.g. because their /// setter is private). StorageIsMutable_t supportsMutation() const { return getImplInfo().supportsMutation(); } /// isSettable - Determine whether references to this decl may appear /// on the left-hand side of an assignment or as the operand of a /// `&` or 'inout' operator. bool isSettable(const DeclContext *UseDC, const DeclRefExpr *base = nullptr) const; /// Does this storage declaration have explicitly-defined accessors /// written in the source? bool hasParsedAccessors() const; /// Return the ownership of values opaquely read from this storage. OpaqueReadOwnership getOpaqueReadOwnership() const; void setOpaqueReadOwnership(OpaqueReadOwnership ownership) { LazySemanticInfo.OpaqueReadOwnership = unsigned(ownership); LazySemanticInfo.OpaqueReadOwnershipComputed = true; } /// Return true if reading this storage requires the ability to /// modify the base value. bool isGetterMutating() const; void setIsGetterMutating(bool isMutating) { LazySemanticInfo.IsGetterMutating = isMutating; LazySemanticInfo.IsGetterMutatingComputed = true; } /// Return true if modifying this storage requires the ability to /// modify the base value. bool isSetterMutating() const; void setIsSetterMutating(bool isMutating) { LazySemanticInfo.IsSetterMutating = isMutating; LazySemanticInfo.IsSetterMutatingComputed = true; } AccessorDecl *getAccessor(AccessorKind kind) const { if (auto info = Accessors.getPointer()) return info->getAccessor(kind); return nullptr; } ArrayRef<AccessorDecl*> getAllAccessors() const { if (const auto *info = Accessors.getPointer()) return info->getAllAccessors(); return {}; } /// This is the primary mechanism by which we can easily determine whether /// this storage decl has any effects. /// /// \returns the getter decl iff this decl has only one accessor that is /// a 'get' with an effect (i.e., 'async', 'throws', or both). /// Otherwise returns nullptr. AccessorDecl *getEffectfulGetAccessor() const; /// Performs a "limit check" on an effect possibly exhibited by this storage /// decl with respect to some other storage decl that serves as the "limit." /// This check says that \c this is less effectful than \c other if /// \c this either does not exhibit the effect, or if it does, then \c other /// also exhibits the effect. Thus, it is conceptually equivalent to /// a less-than-or-equal (≤) check like so: /// /// \verbatim /// /// this->hasEffect(E) ≤ other->hasEffect(E) /// /// \endverbatim /// /// \param kind the single effect we are performing a check for. /// /// \returns true iff \c this decl either does not exhibit the effect, /// or \c other also exhibits the effect. bool isLessEffectfulThan(AbstractStorageDecl const* other, EffectKind kind) const; /// Return an accessor that this storage is expected to have, synthesizing /// one if necessary. Note that will always synthesize one, even if the /// accessor is not part of the expected opaque set for the storage, so use /// with caution. AccessorDecl *getSynthesizedAccessor(AccessorKind kind) const; /// Return an accessor part of the set of opaque accessors dictated by the /// requirements of the ABI. /// /// This will synthesize the accessor if one is required but not specified /// in source; for example, most of the time a mutable property is required /// to have a 'modify' accessor, but if the property was only written with /// 'get' and 'set' accessors, 'modify' will be synthesized to call 'get' /// followed by 'set'. /// /// If the accessor is not needed for ABI reasons, this returns nullptr. /// To ensure an accessor is always returned, use getSynthesizedAccessor(). AccessorDecl *getOpaqueAccessor(AccessorKind kind) const; /// Collect all opaque accessors. ArrayRef<AccessorDecl*> getOpaqueAccessors(llvm::SmallVectorImpl<AccessorDecl*> &scratch) const; /// Return an accessor that was written in source. Returns null if the /// accessor was not explicitly defined by the user. AccessorDecl *getParsedAccessor(AccessorKind kind) const; /// Visit all parsed accessors. void visitParsedAccessors(llvm::function_ref<void (AccessorDecl*)>) const; /// Visit all opaque accessor kinds. void visitExpectedOpaqueAccessors( llvm::function_ref<void (AccessorKind)>) const; /// Visit all opaque accessors. void visitOpaqueAccessors(llvm::function_ref<void (AccessorDecl*)>) const; /// Visit all eagerly emitted accessors. /// /// This is the union of the parsed and opaque sets. void visitEmittedAccessors(llvm::function_ref<void (AccessorDecl*)>) const; void setAccessors(SourceLoc lbraceLoc, ArrayRef<AccessorDecl*> accessors, SourceLoc rbraceLoc); /// Add a setter to an existing Computed var. /// /// This should only be used by the ClangImporter. void setComputedSetter(AccessorDecl *Set); /// Does this storage require opaque accessors of any kind? bool requiresOpaqueAccessors() const; /// Does this storage require an opaque accessor of the given kind? bool requiresOpaqueAccessor(AccessorKind kind) const; /// Does this storage require a 'get' accessor in its opaque-accessors set? bool requiresOpaqueGetter() const { return getOpaqueReadOwnership() != OpaqueReadOwnership::Borrowed; } /// Does this storage require a 'read' accessor in its opaque-accessors set? bool requiresOpaqueReadCoroutine() const { return getOpaqueReadOwnership() != OpaqueReadOwnership::Owned; } /// Does this storage require a 'set' accessor in its opaque-accessors set? bool requiresOpaqueSetter() const { return supportsMutation(); } /// Does this storage require a 'modify' accessor in its opaque-accessors set? bool requiresOpaqueModifyCoroutine() const; /// Does this storage have any explicit observers (willSet or didSet) attached /// to it? bool hasObservers() const { return getParsedAccessor(AccessorKind::WillSet) || getParsedAccessor(AccessorKind::DidSet); } SourceRange getBracesRange() const { if (auto info = Accessors.getPointer()) return info->getBracesRange(); return SourceRange(); } AccessLevel getSetterFormalAccess() const; AccessScope getSetterFormalAccessScope(const DeclContext *useDC = nullptr, bool treatUsableFromInlineAsPublic = false) const; void setSetterAccess(AccessLevel accessLevel) { assert(!Accessors.getInt().hasValue()); overwriteSetterAccess(accessLevel); } void overwriteSetterAccess(AccessLevel accessLevel); /// Given that this is an Objective-C property or subscript declaration, /// produce its getter selector. ObjCSelector getObjCGetterSelector(Identifier preferredName = Identifier()) const; /// Given that this is an Objective-C property or subscript declaration, /// produce its setter selector. ObjCSelector getObjCSetterSelector(Identifier preferredName = Identifier()) const; AbstractStorageDecl *getOverriddenDecl() const { return cast_or_null<AbstractStorageDecl>(ValueDecl::getOverriddenDecl()); } /// Returns the location of 'override' keyword, if any. SourceLoc getOverrideLoc() const; /// Returns true if this declaration has a setter accessible from the given /// context. /// /// If \p DC is null, returns true only if the setter is public. /// /// See \c isAccessibleFrom for a discussion of the \p forConformance /// parameter. bool isSetterAccessibleFrom(const DeclContext *DC, bool forConformance=false) const; /// Determine how this storage declaration should actually be accessed. AccessStrategy getAccessStrategy(AccessSemantics semantics, AccessKind accessKind, ModuleDecl *module, ResilienceExpansion expansion) const; /// Should this declaration behave as if it must be accessed /// resiliently, even when we're building a non-resilient module? /// /// This is used for diagnostics, because we do not want a behavior /// change between builds with resilience enabled and disabled. bool isFormallyResilient() const; /// Do we need to use resilient access patterns outside of this /// property's resilience domain? bool isResilient() const; /// Do we need to use resilient access patterns when accessing this /// property from the given module? bool isResilient(ModuleDecl *M, ResilienceExpansion expansion) const; /// True if the storage can be referenced by a keypath directly. /// Otherwise, its override must be referenced. bool isValidKeyPathComponent() const; /// True if the storage exports a property descriptor for key paths in /// other modules. bool exportsPropertyDescriptor() const; /// True if any of the accessors to the storage is private or fileprivate. bool hasPrivateAccessor() const; bool hasDidSetOrWillSetDynamicReplacement() const; bool hasAnyNativeDynamicAccessors() const; bool isDistributedActorIndependent() const; // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() >= DeclKind::First_AbstractStorageDecl && D->getKind() <= DeclKind::Last_AbstractStorageDecl; } }; /// Describes which synthesized property for a property with an attached /// wrapper is being referenced. enum class PropertyWrapperSynthesizedPropertyKind { /// The backing storage property, which is a stored property of the /// wrapper type. Backing, /// A projection (e.g., `$foo`), which is a computed property to access the /// wrapper instance's \c projectedValue property. Projection, }; /// VarDecl - 'var' and 'let' declarations. class VarDecl : public AbstractStorageDecl { friend class NamingPatternRequest; NamedPattern *NamingPattern = nullptr; public: enum class Introducer : uint8_t { Let = 0, Var = 1 }; protected: PointerUnion<PatternBindingDecl *, Stmt *, VarDecl *, CaptureListExpr *> Parent; VarDecl(DeclKind kind, bool isStatic, Introducer introducer, SourceLoc nameLoc, Identifier name, DeclContext *dc, StorageIsMutable_t supportsMutation); public: VarDecl(bool isStatic, Introducer introducer, SourceLoc nameLoc, Identifier name, DeclContext *dc) : VarDecl(DeclKind::Var, isStatic, introducer, nameLoc, name, dc, StorageIsMutable_t(introducer == Introducer::Var)) {} SourceRange getSourceRange() const; Identifier getName() const { return getBaseIdentifier(); } /// Returns the string for the base name, or "_" if this is unnamed. StringRef getNameStr() const { return hasName() ? getBaseIdentifier().str() : "_"; } /// Get the type of the variable within its context. If the context is generic, /// this will use archetypes. Type getType() const; /// Retrieve the source range of the variable type, or an invalid range if the /// variable's type is not explicitly written in the source. /// /// Only for use in diagnostics. It is not always possible to always /// precisely point to the variable type because of type aliases. SourceRange getTypeSourceRangeForDiagnostics() const; /// Returns whether the var is settable in the specified context: this /// is either because it is a stored var, because it has a custom setter, or /// is a let member in an initializer. /// /// Pass a null context and null base to check if it's always settable. bool isSettable(const DeclContext *UseDC, const DeclRefExpr *base = nullptr) const; /// Return the parent pattern binding that may provide an initializer for this /// VarDecl. This returns null if there is none associated with the VarDecl. PatternBindingDecl *getParentPatternBinding() const { if (!Parent) return nullptr; return Parent.dyn_cast<PatternBindingDecl *>(); } void setParentPatternBinding(PatternBindingDecl *PBD) { assert(PBD); Parent = PBD; } /// Return the Pattern involved in initializing this VarDecl. However, recall /// that the Pattern may be involved in initializing more than just this one /// vardecl. For example, if this is a VarDecl for "x", the pattern may be /// "(x, y)" and the initializer on the PatternBindingDecl may be "(1,2)" or /// "foo()". /// /// If this has no parent pattern binding decl or statement associated, it /// returns null. /// Pattern *getParentPattern() const; /// Returns the parsed type of this variable declaration. For parameters, this /// is the parsed type the user explicitly wrote. For variables, this is the /// type the user wrote in the typed pattern that binds this variable. /// /// Note that there are many cases where the user may elide types. This will /// return null in those cases. TypeRepr *getTypeReprOrParentPatternTypeRepr() const; /// Return the statement that owns the pattern associated with this VarDecl, /// if one exists. /// /// NOTE: After parsing and before type checking, all VarDecls from /// CaseLabelItem's Patterns return their CaseStmt. After type checking, we /// will have constructed the CaseLabelItem VarDecl linked list implying this /// will return nullptr. After type checking, if one wishes to find a parent /// pattern of a VarDecl of a CaseStmt, \see getRecursiveParentPatternStmt /// instead. Stmt *getParentPatternStmt() const { if (!Parent) return nullptr; return Parent.dyn_cast<Stmt *>(); } void setParentPatternStmt(Stmt *s) { assert(s); Parent = s; } /// Look for the parent pattern stmt of this var decl, recursively /// looking through var decl pointers and then through any /// fallthroughts. Stmt *getRecursiveParentPatternStmt() const; /// Returns the var decl that this var decl is an implicit reference to if /// such a var decl exists. VarDecl *getParentVarDecl() const { if (!Parent) return nullptr; return Parent.dyn_cast<VarDecl *>(); } /// Set \p v to be the pattern produced VarDecl that is the parent of this /// var decl. void setParentVarDecl(VarDecl *v) { assert(v && v != this); Parent = v; } NamedPattern *getNamingPattern() const; void setNamingPattern(NamedPattern *Pat); /// If this is a VarDecl that does not belong to a CaseLabelItem's pattern, /// return this. Otherwise, this VarDecl must belong to a CaseStmt's /// CaseLabelItem. In that case, return the first case label item of the first /// case stmt in a sequence of case stmts that fallthrough into each other. /// /// NOTE: During type checking, we emit an error if we have a single case /// label item with a pattern that has multiple var decls of the same /// name. This means that during type checking and before type checking, we /// may have a _malformed_ switch stmt var decl linked list since var decls in /// the same case label item that have the same name will point at the same /// canonical var decl, namely the first var decl with the name in the /// canonical case label item's var decl list. This is ok, since we are going /// to emit the error, but it requires us to be more careful/cautious before /// type checking has been complete when relying on canonical var decls /// matching up. VarDecl *getCanonicalVarDecl() const; /// If this is a case stmt var decl, return the var decl that corresponds to /// this var decl in the first case label item of the case stmt. Returns /// nullptr if this isn't a VarDecl that is part of a case stmt. NullablePtr<VarDecl> getCorrespondingFirstCaseLabelItemVarDecl() const; /// If this is a case stmt var decl, return the case body var decl that this /// var decl maps to. NullablePtr<VarDecl> getCorrespondingCaseBodyVariable() const; /// Return true if this var decl is an implicit var decl belonging to a case /// stmt's body. bool isCaseBodyVariable() const; /// True if the global stored property requires lazy initialization. bool isLazilyInitializedGlobal() const; /// Return the initializer involved in this VarDecl. Recall that the /// initializer may be involved in initializing more than just this one /// vardecl though. For example, if this is a VarDecl for "x", the pattern /// may be "(x, y)" and the initializer on the PatternBindingDecl may be /// "(1,2)" or "foo()". /// /// If this has no parent pattern binding decl associated, or if that pattern /// binding has no initial value, this returns null. /// Expr *getParentInitializer() const { if (auto *PBD = getParentPatternBinding()) { const auto i = PBD->getPatternEntryIndexForVarDecl(this); return PBD->getInit(i); } return nullptr; } /// Whether there exists an initializer for this \c VarDecl. bool isParentInitialized() const { if (auto *PBD = getParentPatternBinding()) { const auto i = PBD->getPatternEntryIndexForVarDecl(this); return PBD->isInitialized(i); } return false; } // Return whether this VarDecl has an initial value, either by checking // if it has an initializer in its parent pattern binding or if it has // the @_hasInitialValue attribute. bool hasInitialValue() const { return getAttrs().hasAttribute<HasInitialValueAttr>() || isParentInitialized(); } VarDecl *getOverriddenDecl() const { return cast_or_null<VarDecl>(AbstractStorageDecl::getOverriddenDecl()); } /// Is this an immutable 'let' property? /// /// If this is a ParamDecl, isLet() is true iff /// getSpecifier() == Specifier::Default. bool isLet() const { return getIntroducer() == Introducer::Let; } /// Is this an "async let" property? bool isAsyncLet() const; Introducer getIntroducer() const { return Introducer(Bits.VarDecl.Introducer); } void setIntroducer(Introducer value) { Bits.VarDecl.Introducer = uint8_t(value); } CaptureListExpr *getParentCaptureList() const { if (!Parent) return nullptr; return Parent.dyn_cast<CaptureListExpr *>(); } /// Set \p v to be the pattern produced VarDecl that is the parent of this /// var decl. void setParentCaptureList(CaptureListExpr *expr) { assert(expr != nullptr); Parent = expr; } /// Is this an element in a capture list? bool isCaptureList() const { return getParentCaptureList() != nullptr; } /// Is this a capture of the self param? bool isSelfParamCapture() const { return Bits.VarDecl.IsSelfParamCapture; } void setIsSelfParamCapture(bool IsSelfParamCapture = true) { Bits.VarDecl.IsSelfParamCapture = IsSelfParamCapture; } /// Determines if this var has an initializer expression that should be /// exposed to clients. /// /// There's a very narrow case when we would: if the decl is an instance /// member with an initializer expression and the parent type is /// @frozen and resides in a resilient module. bool isInitExposedToClients() const; /// Determines if this var is exposed as part of the layout of a /// @frozen struct. /// /// From the standpoint of access control and exportability checking, this /// var will behave as if it was public, even if it is internal or private. bool isLayoutExposedToClients() const; /// Is this a special debugger variable? bool isDebuggerVar() const { return Bits.VarDecl.IsDebuggerVar; } void setDebuggerVar(bool IsDebuggerVar) { Bits.VarDecl.IsDebuggerVar = IsDebuggerVar; } /// Is this the synthesized storage for a 'lazy' property? bool isLazyStorageProperty() const { return Bits.VarDecl.IsLazyStorageProperty; } void setLazyStorageProperty(bool IsLazyStorage) { Bits.VarDecl.IsLazyStorageProperty = IsLazyStorage; } /// True if this is a top-level global variable from the main source file. bool isTopLevelGlobal() const { return Bits.VarDecl.IsTopLevelGlobal; } void setTopLevelGlobal(bool b) { Bits.VarDecl.IsTopLevelGlobal = b; } /// Retrieve the custom attributes that attach property wrappers to this /// property. The returned list contains all of the attached property wrapper /// attributes in source order, which means the outermost wrapper attribute /// is provided first. llvm::TinyPtrVector<CustomAttr *> getAttachedPropertyWrappers() const; /// Whether this property has any attached property wrappers. bool hasAttachedPropertyWrapper() const; /// Whether this var has an implicit property wrapper attribute. bool hasImplicitPropertyWrapper() const; /// Whether this var is a parameter with an attached property wrapper /// that has an external effect on the function. bool hasExternalPropertyWrapper() const; /// Whether all of the attached property wrappers have an init(wrappedValue:) /// initializer. bool allAttachedPropertyWrappersHaveWrappedValueInit() const; /// Retrieve the type of the attached property wrapper as a contextual /// type. /// /// \param index Which property wrapper type is being computed, where 0 /// indicates the first (outermost) attached property wrapper. /// /// \returns a NULL type for properties without attached wrappers, /// an error type when the property wrapper type itself is erroneous, /// or the wrapper type itself, which may involve unbound generic /// types. Type getAttachedPropertyWrapperType(unsigned index) const; /// Retrieve information about the attached property wrapper type. /// /// \param i Which attached property wrapper type is being queried, where 0 is the outermost (first) /// attached property wrapper type. PropertyWrapperTypeInfo getAttachedPropertyWrapperTypeInfo(unsigned i) const; /// Retrieve the fully resolved attached property wrapper type. /// /// This type will be the fully-resolved form of /// \c getAttachedPropertyWrapperType(0), which will not contain any /// unbound generic types. It will be the type of the backing property. Type getPropertyWrapperBackingPropertyType() const; /// If there is an attached property wrapper, retrieve the synthesized /// auxiliary variables. PropertyWrapperAuxiliaryVariables getPropertyWrapperAuxiliaryVariables() const; /// If there is an attached property wrapper, retrieve information about /// how to initialize the backing property. PropertyWrapperInitializerInfo getPropertyWrapperInitializerInfo() const; /// Retrieve information about the mutability of the composed /// property wrappers. Optional<PropertyWrapperMutability> getPropertyWrapperMutability() const; /// Returns whether this property is the backing storage property or a storage /// wrapper for wrapper instance's projectedValue. If this property is /// neither, then it returns `None`. Optional<PropertyWrapperSynthesizedPropertyKind> getPropertyWrapperSynthesizedPropertyKind() const; /// Retrieve the backing storage property for a property that has an /// attached property wrapper. /// /// The backing storage property will be a stored property of the /// wrapper's type. This will be equivalent to /// \c getAttachedPropertyWrapperType(0) when it is fully-specified; /// if \c getAttachedPropertyWrapperType(0) involves an unbound /// generic type, the backing storage property will be the appropriate /// bound generic version. VarDecl *getPropertyWrapperBackingProperty() const; /// Retreive the projection var for a property that has an attached /// property wrapper with a \c projectedValue . VarDecl *getPropertyWrapperProjectionVar() const; /// Retrieve the local wrapped value var for for a parameter that has /// an attached property wrapper. VarDecl *getPropertyWrapperWrappedValueVar() const; /// Visit all auxiliary declarations to this VarDecl. /// /// An auxiliary declaration is a declaration synthesized by the compiler to support /// this VarDecl, such as synthesized property wrapper variables. /// /// \note this function only visits auxiliary decls that are not part of the AST. void visitAuxiliaryDecls(llvm::function_ref<void(VarDecl *)>) const; /// Retrieve the backing storage property for a lazy property. VarDecl *getLazyStorageProperty() const; /// Whether the memberwise initializer parameter for a property with a /// property wrapper type uses the wrapped type. This will occur, for example, /// when there is an explicitly-specified initializer like: /// /// \code /// @Lazy var i = 17 /// \endcode /// /// Or when there is no initializer but each composed property wrapper has /// a suitable `init(wrappedValue:)`. bool isPropertyMemberwiseInitializedWithWrappedType() const; /// Return the interface type of the value used for the 'wrappedValue:' /// parameter when initializing a property wrapper. /// /// If the property has an attached property wrapper and the 'wrappedValue:' /// parameter is an autoclosure, return a function type returning the stored /// value. Otherwise, return the interface type of the stored value. Type getPropertyWrapperInitValueInterfaceType() const; /// If this property is the backing storage for a property with an attached /// property wrapper, return the original property. /// /// \param kind If not \c None, only returns the original property when /// \c this property is the specified synthesized property. VarDecl *getOriginalWrappedProperty( Optional<PropertyWrapperSynthesizedPropertyKind> kind = None) const; /// Set the property that wraps to this property as it's backing /// property. void setOriginalWrappedProperty(VarDecl *originalProperty); /// Return the Objective-C runtime name for this property. Identifier getObjCPropertyName() const; /// Retrieve the default Objective-C selector for the getter of a /// property of the given name. static ObjCSelector getDefaultObjCGetterSelector(ASTContext &ctx, Identifier propertyName); /// Retrieve the default Objective-C selector for the setter of a /// property of the given name. static ObjCSelector getDefaultObjCSetterSelector(ASTContext &ctx, Identifier propertyName); /// If this is a simple 'let' constant, emit a note with a fixit indicating /// that it can be rewritten to a 'var'. This is used in situations where the /// compiler detects obvious attempts to mutate a constant. void emitLetToVarNoteIfSimple(DeclContext *UseDC) const; /// Returns true if the name is the self identifier and is implicit. bool isSelfParameter() const; /// Determine whether this property will be part of the implicit memberwise /// initializer. /// /// \param preferDeclaredProperties When encountering a `lazy` property /// or a property that has an attached property wrapper, prefer the /// actual declared property (which may or may not be considered "stored" /// as the moment) to the backing storage property. Otherwise, the stored /// backing property will be treated as the member-initialized property. bool isMemberwiseInitialized(bool preferDeclaredProperties) const; /// Return the range of semantics attributes attached to this VarDecl. auto getSemanticsAttrs() const -> decltype(getAttrs().getAttributes<SemanticsAttr>()) { return getAttrs().getAttributes<SemanticsAttr>(); } /// Returns true if this VarDecl has the string \p attrValue as a semantics /// attribute. bool hasSemanticsAttr(StringRef attrValue) const { return llvm::any_of(getSemanticsAttrs(), [&](const SemanticsAttr *attr) { return attrValue.equals(attr->Value); }); } // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == DeclKind::Var || D->getKind() == DeclKind::Param; } }; enum class ParamSpecifier : uint8_t { Default = 0, InOut = 1, Shared = 2, Owned = 3, }; /// A function parameter declaration. class ParamDecl : public VarDecl { friend class DefaultArgumentInitContextRequest; friend class DefaultArgumentExprRequest; llvm::PointerIntPair<Identifier, 1, bool> ArgumentNameAndDestructured; SourceLoc ParameterNameLoc; SourceLoc ArgumentNameLoc; SourceLoc SpecifierLoc; TypeRepr *TyRepr = nullptr; struct alignas(1 << DeclAlignInBits) StoredDefaultArgument { PointerUnion<Expr *, VarDecl *> DefaultArg; /// Stores the context for the default argument as well as a bit to /// indicate whether the default expression has been type-checked. llvm::PointerIntPair<Initializer *, 1, bool> InitContextAndIsTypeChecked; StringRef StringRepresentation; CaptureInfo Captures; }; /// Retrieve the cached initializer context for the parameter's default /// argument without triggering a request. Optional<Initializer *> getCachedDefaultArgumentInitContext() const; enum class Flags : uint8_t { /// Whether or not this parameter is vargs. IsVariadic = 1 << 0, /// Whether or not this parameter is `@autoclosure`. IsAutoClosure = 1 << 1, /// Whether or not this parameter is 'isolated'. IsIsolated = 1 << 2, }; /// The default value, if any, along with flags. llvm::PointerIntPair<StoredDefaultArgument *, 3, OptionSet<Flags>> DefaultValueAndFlags; friend class ParamSpecifierRequest; public: ParamDecl(SourceLoc specifierLoc, SourceLoc argumentNameLoc, Identifier argumentName, SourceLoc parameterNameLoc, Identifier parameterName, DeclContext *dc); /// Create a new ParamDecl identical to the first except without the interface type. static ParamDecl *cloneWithoutType(const ASTContext &Ctx, ParamDecl *PD); /// Create a an identical copy of this ParamDecl. static ParamDecl *clone(const ASTContext &Ctx, ParamDecl *PD); /// Retrieve the argument (API) name for this function parameter. Identifier getArgumentName() const { return ArgumentNameAndDestructured.getPointer(); } /// Retrieve the parameter (local) name for this function parameter. Identifier getParameterName() const { return getName(); } /// Retrieve the source location of the argument (API) name. /// /// The resulting source location will be valid if the argument name /// was specified separately from the parameter name. SourceLoc getArgumentNameLoc() const { return ArgumentNameLoc; } SourceLoc getParameterNameLoc() const { return ParameterNameLoc; } SourceLoc getSpecifierLoc() const { return SpecifierLoc; } /// Retrieve the TypeRepr corresponding to the parsed type of the parameter, if it exists. TypeRepr *getTypeRepr() const { return TyRepr; } void setTypeRepr(TypeRepr *repr) { TyRepr = repr; } bool isDestructured() const { return ArgumentNameAndDestructured.getInt(); } void setDestructured(bool repr) { ArgumentNameAndDestructured.setInt(repr); } DefaultArgumentKind getDefaultArgumentKind() const { return static_cast<DefaultArgumentKind>(Bits.ParamDecl.defaultArgumentKind); } bool isDefaultArgument() const { return getDefaultArgumentKind() != DefaultArgumentKind::None; } void setDefaultArgumentKind(DefaultArgumentKind K) { Bits.ParamDecl.defaultArgumentKind = static_cast<unsigned>(K); } /// Whether this parameter has a default argument expression available. /// /// Note that this will return false for deserialized declarations, which only /// have a textual representation of their default expression. bool hasDefaultExpr() const; /// Whether this parameter has a caller-side default argument expression /// such as the magic literal \c #function. bool hasCallerSideDefaultExpr() const; /// Retrieve the fully type-checked default argument expression for this /// parameter, or \c nullptr if there is no default expression. /// /// Note that while this will produce a type-checked expression for /// caller-side default arguments such as \c #function, this is done purely to /// check whether the code is valid. Such default arguments get re-created /// at the call site in order to have the correct context information. Expr *getTypeCheckedDefaultExpr() const; /// Retrieve the potentially un-type-checked default argument expression for /// this parameter, which can be queried for information such as its source /// range and textual representation. Returns \c nullptr if there is no /// default expression. Expr *getStructuralDefaultExpr() const { if (auto stored = DefaultValueAndFlags.getPointer()) return stored->DefaultArg.dyn_cast<Expr *>(); return nullptr; } VarDecl *getStoredProperty() const { if (auto stored = DefaultValueAndFlags.getPointer()) return stored->DefaultArg.dyn_cast<VarDecl *>(); return nullptr; } /// Sets a new default argument expression for this parameter. This should /// only be called internally by ParamDecl and AST walkers. /// /// \param E The new default argument. /// \param isTypeChecked Whether this argument should be used as the /// parameter's fully type-checked default argument. void setDefaultExpr(Expr *E, bool isTypeChecked); void setStoredProperty(VarDecl *var); /// Retrieve the initializer context for the parameter's default argument. Initializer *getDefaultArgumentInitContext() const; void setDefaultArgumentInitContext(Initializer *initContext); CaptureInfo getDefaultArgumentCaptureInfo() const { assert(DefaultValueAndFlags.getPointer()); return DefaultValueAndFlags.getPointer()->Captures; } void setDefaultArgumentCaptureInfo(CaptureInfo captures); /// Extracts the text of the default argument attached to the provided /// ParamDecl, removing all inactive #if clauses and providing only the /// text of active #if clauses. /// /// For example, the default argument: /// ``` /// { /// #if false /// print("false") /// #else /// print("true") /// #endif /// } /// ``` /// will return /// ``` /// { /// print("true") /// } /// ``` /// \sa getDefaultValue StringRef getDefaultValueStringRepresentation( SmallVectorImpl<char> &scratch) const; void setDefaultValueStringRepresentation(StringRef stringRepresentation); /// Whether or not this parameter is varargs. bool isVariadic() const { return DefaultValueAndFlags.getInt().contains(Flags::IsVariadic); } void setVariadic(bool value = true) { auto flags = DefaultValueAndFlags.getInt(); DefaultValueAndFlags.setInt(value ? flags | Flags::IsVariadic : flags - Flags::IsVariadic); } /// Whether or not this parameter is marked with `@autoclosure`. bool isAutoClosure() const { return DefaultValueAndFlags.getInt().contains(Flags::IsAutoClosure); } void setAutoClosure(bool value = true) { auto flags = DefaultValueAndFlags.getInt(); DefaultValueAndFlags.setInt(value ? flags | Flags::IsAutoClosure : flags - Flags::IsAutoClosure); } /// Whether or not this parameter is marked with 'isolated'. bool isIsolated() const { return DefaultValueAndFlags.getInt().contains(Flags::IsIsolated); } void setIsolated(bool value = true) { auto flags = DefaultValueAndFlags.getInt(); DefaultValueAndFlags.setInt(value ? flags | Flags::IsIsolated : flags - Flags::IsIsolated); } /// Does this parameter reject temporary pointer conversions? bool isNonEphemeral() const; /// Attempt to apply an implicit `@_nonEphemeral` attribute to this parameter. void setNonEphemeralIfPossible(); /// Remove the type of this varargs element designator, without the array /// type wrapping it. A parameter like "Int..." will have formal parameter /// type of "[Int]" and this returns "Int". static Type getVarargBaseTy(Type VarArgT); /// Remove the type of this varargs element designator, without the array /// type wrapping it. Type getVarargBaseTy() const { assert(isVariadic()); return getVarargBaseTy(getInterfaceType()); } /// Determine whether this declaration is an anonymous closure parameter. bool isAnonClosureParam() const; using Specifier = ParamSpecifier; Optional<Specifier> getCachedSpecifier() const { if (Bits.ParamDecl.SpecifierComputed) return Specifier(Bits.ParamDecl.Specifier); return None; } /// Return the raw specifier value for this parameter. Specifier getSpecifier() const; void setSpecifier(Specifier Spec); /// Is the type of this parameter 'inout'? bool isInOut() const { return getSpecifier() == Specifier::InOut; } /// Is this an immutable 'shared' property? bool isShared() const { return getSpecifier() == Specifier::Shared; } /// Is this an immutable 'owned' property? bool isOwned() const { return getSpecifier() == Specifier::Owned; } bool isImmutable() const { return isImmutableSpecifier(getSpecifier()); } static bool isImmutableSpecifier(Specifier sp) { switch (sp) { case Specifier::Default: case Specifier::Shared: case Specifier::Owned: return true; case Specifier::InOut: return false; } llvm_unreachable("unhandled specifier"); } ValueOwnership getValueOwnership() const { return getValueOwnershipForSpecifier(getSpecifier()); } static ValueOwnership getValueOwnershipForSpecifier(Specifier specifier) { switch (specifier) { case Specifier::Default: return ValueOwnership::Default; case Specifier::InOut: return ValueOwnership::InOut; case Specifier::Shared: return ValueOwnership::Shared; case Specifier::Owned: return ValueOwnership::Owned; } llvm_unreachable("unhandled specifier"); } static Specifier getParameterSpecifierForValueOwnership(ValueOwnership ownership) { switch (ownership) { case ValueOwnership::Default: return Specifier::Default; case ValueOwnership::Shared: return Specifier::Shared; case ValueOwnership::InOut: return Specifier::InOut; case ValueOwnership::Owned: return Specifier::Owned; } llvm_unreachable("unhandled ownership"); } SourceRange getSourceRange() const; AnyFunctionType::Param toFunctionParam(Type type = Type()) const; // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return D->getKind() == DeclKind::Param; } }; /// Describes the kind of subscripting used in Objective-C. enum class ObjCSubscriptKind { /// Objective-C indexed subscripting, which is based on an integral /// index. Indexed, /// Objective-C keyed subscripting, which is based on an object /// argument or metatype thereof. Keyed }; /// Declares a subscripting operator for a type. /// /// A subscript declaration is defined as a get/set pair that produces a /// specific type. For example: /// /// \code /// subscript (i : Int) -> String { /// get { /* return ith String */ } /// set { /* set ith string to value */ } /// } /// \endcode /// /// A type with a subscript declaration can be used as the base of a subscript /// expression a[i], where a is of the subscriptable type and i is the type /// of the index. A subscript can have multiple indices: /// /// \code /// struct Matrix { /// subscript (i : Int, j : Int) -> Double { /// get { /* return element at position (i, j) */ } /// set { /* set element at position (i, j) */ } /// } /// } /// \endcode /// /// A given type can have multiple subscript declarations, so long as the /// signatures (indices and element type) are distinct. /// class SubscriptDecl : public GenericContext, public AbstractStorageDecl { friend class ResultTypeRequest; SourceLoc StaticLoc; SourceLoc ArrowLoc; SourceLoc EndLoc; ParameterList *Indices; TypeLoc ElementTy; void setElementInterfaceType(Type type); SubscriptDecl(DeclName Name, SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, SourceLoc SubscriptLoc, ParameterList *Indices, SourceLoc ArrowLoc, TypeRepr *ElementTyR, DeclContext *Parent, GenericParamList *GenericParams) : GenericContext(DeclContextKind::SubscriptDecl, Parent, GenericParams), AbstractStorageDecl(DeclKind::Subscript, StaticSpelling != StaticSpellingKind::None, Parent, Name, SubscriptLoc, /*will be overwritten*/ StorageIsNotMutable), StaticLoc(StaticLoc), ArrowLoc(ArrowLoc), Indices(nullptr), ElementTy(ElementTyR) { Bits.SubscriptDecl.StaticSpelling = static_cast<unsigned>(StaticSpelling); setIndices(Indices); } public: /// Factory function only for use by deserialization. static SubscriptDecl *createDeserialized(ASTContext &Context, DeclName Name, StaticSpellingKind StaticSpelling, Type ElementTy, DeclContext *Parent, GenericParamList *GenericParams); static SubscriptDecl *create(ASTContext &Context, DeclName Name, SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, SourceLoc SubscriptLoc, ParameterList *Indices, SourceLoc ArrowLoc, TypeRepr *ElementTyR, DeclContext *Parent, GenericParamList *GenericParams); static SubscriptDecl *createImported(ASTContext &Context, DeclName Name, SourceLoc SubscriptLoc, ParameterList *Indices, SourceLoc ArrowLoc, Type ElementTy, DeclContext *Parent, ClangNode ClangN); /// \returns the way 'static'/'class' was spelled in the source. StaticSpellingKind getStaticSpelling() const { return static_cast<StaticSpellingKind>(Bits.SubscriptDecl.StaticSpelling); } SourceLoc getStaticLoc() const { return StaticLoc; } SourceLoc getSubscriptLoc() const { return getNameLoc(); } SourceLoc getStartLoc() const { return getStaticLoc().isValid() ? getStaticLoc() : getSubscriptLoc(); } SourceLoc getEndLoc() const { return EndLoc; } void setEndLoc(SourceLoc sl) { EndLoc = sl; } SourceRange getSourceRange() const; SourceRange getSignatureSourceRange() const; /// Retrieve the indices for this subscript operation. ParameterList *getIndices() { return Indices; } const ParameterList *getIndices() const { return Indices; } void setIndices(ParameterList *p); /// Retrieve the type of the element referenced by a subscript /// operation. Type getElementInterfaceType() const; TypeRepr *getElementTypeRepr() const { return ElementTy.getTypeRepr(); } SourceRange getElementTypeSourceRange() const { return ElementTy.getSourceRange(); } /// Determine the kind of Objective-C subscripting this declaration /// implies. ObjCSubscriptKind getObjCSubscriptKind() const; SubscriptDecl *getOverriddenDecl() const { return cast_or_null<SubscriptDecl>( AbstractStorageDecl::getOverriddenDecl()); } static bool classof(const Decl *D) { return D->getKind() == DeclKind::Subscript; } static bool classof(const DeclContext *DC) { if (auto D = DC->getAsDecl()) return classof(D); return false; } using DeclContext::operator new; using Decl::getASTContext; }; /// Encodes imported-as-member status for C functions that get imported /// as methods. class ImportAsMemberStatus { friend class AbstractFunctionDecl; // non-0 denotes import-as-member. 1 denotes no self index. n+2 denotes self // index of n uint8_t rawValue; public: ImportAsMemberStatus(uint8_t rawValue = 0) : rawValue(rawValue) {} uint8_t getRawValue() const { return rawValue; } bool isImportAsMember() const { return rawValue != 0; } bool isInstance() const { return rawValue >= 2; } bool isStatic() const { return rawValue == 1; } uint8_t getSelfIndex() const { assert(isInstance() && "not set"); return rawValue - 2; } void setStatic() { assert(!isStatic() && "already set"); rawValue = 1; } void setSelfIndex(uint8_t idx) { assert(!isImportAsMember() && "already set"); assert(idx <= UINT8_MAX-2 && "out of bounds"); rawValue = idx + 2; } }; /// Base class for function-like declarations. class AbstractFunctionDecl : public GenericContext, public ValueDecl { friend class NeedsNewVTableEntryRequest; public: enum class BodyKind { /// The function did not have a body in the source code file. None, /// Function body is delayed, to be parsed later. Unparsed, /// Function body is parsed and available as an AST subtree. Parsed, /// Function body is not available, although it was written in the source. Skipped, /// Function body will be synthesized on demand. Synthesize, /// Function body is present and type-checked. TypeChecked, /// This is a memberwise initializer that will be synthesized by SILGen. MemberwiseInitializer, /// Function body text was deserialized from a .swiftmodule. Deserialized // This enum currently needs to fit in a 3-bit bitfield. }; BodyKind getBodyKind() const { return BodyKind(Bits.AbstractFunctionDecl.BodyKind); } struct BodySynthesizer { std::pair<BraceStmt *, bool> (* Fn)(AbstractFunctionDecl *, void *); void *Context; }; private: ParameterList *Params; private: /// The generation at which we last loaded derivative function configurations. unsigned DerivativeFunctionConfigGeneration = 0; /// Prepare to traverse the list of derivative function configurations. void prepareDerivativeFunctionConfigurations(); /// A uniqued list of derivative function configurations. /// - `@differentiable` and `@derivative` attribute type-checking is /// responsible for populating derivative function configurations specified /// in the current module. /// - Module loading is responsible for populating derivative function /// configurations from imported modules. struct DerivativeFunctionConfigurationList; DerivativeFunctionConfigurationList *DerivativeFunctionConfigs = nullptr; public: /// Get all derivative function configurations. ArrayRef<AutoDiffConfig> getDerivativeFunctionConfigurations(); /// Add the given derivative function configuration. void addDerivativeFunctionConfiguration(const AutoDiffConfig &config); protected: // If a function has a body at all, we have either a parsed body AST node or // we have saved the end location of the unparsed body. union { /// This enum member is active if getBodyKind() is BodyKind::Parsed or /// BodyKind::TypeChecked. BraceStmt *Body; /// This enum member is active if getBodyKind() is BodyKind::Deserialized. StringRef BodyStringRepresentation; /// This enum member is active if getBodyKind() == BodyKind::Synthesize. BodySynthesizer Synthesizer; /// The location of the function body when the body is delayed or skipped. /// /// This enum member is active if getBodyKind() is BodyKind::Unparsed or /// BodyKind::Skipped. SourceRange BodyRange; }; friend class ParseAbstractFunctionBodyRequest; friend class TypeCheckFunctionBodyRequest; CaptureInfo Captures; /// Location of the 'async' token. SourceLoc AsyncLoc; /// Location of the 'throws' token. SourceLoc ThrowsLoc; struct { unsigned NeedsNewVTableEntryComputed : 1; unsigned NeedsNewVTableEntry : 1; } LazySemanticInfo = { }; AbstractFunctionDecl(DeclKind Kind, DeclContext *Parent, DeclName Name, SourceLoc NameLoc, bool Async, SourceLoc AsyncLoc, bool Throws, SourceLoc ThrowsLoc, bool HasImplicitSelfDecl, GenericParamList *GenericParams) : GenericContext(DeclContextKind::AbstractFunctionDecl, Parent, GenericParams), ValueDecl(Kind, Parent, Name, NameLoc), Body(nullptr), AsyncLoc(AsyncLoc), ThrowsLoc(ThrowsLoc) { setBodyKind(BodyKind::None); Bits.AbstractFunctionDecl.HasImplicitSelfDecl = HasImplicitSelfDecl; Bits.AbstractFunctionDecl.Overridden = false; Bits.AbstractFunctionDecl.Async = Async; Bits.AbstractFunctionDecl.Throws = Throws; Bits.AbstractFunctionDecl.HasSingleExpressionBody = false; Bits.AbstractFunctionDecl.HasNestedTypeDeclarations = false; } void setBodyKind(BodyKind K) { Bits.AbstractFunctionDecl.BodyKind = unsigned(K); } public: void setHasSingleExpressionBody(bool Has = true) { Bits.AbstractFunctionDecl.HasSingleExpressionBody = Has; } bool hasSingleExpressionBody() const { return Bits.AbstractFunctionDecl.HasSingleExpressionBody; } Expr *getSingleExpressionBody() const; void setSingleExpressionBody(Expr *NewBody); /// Returns the string for the base name, or "_" if this is unnamed. StringRef getNameStr() const { assert(!getName().isSpecial() && "Cannot get string for special names"); return hasName() ? getBaseIdentifier().str() : "_"; } /// Should this declaration be treated as if annotated with transparent /// attribute. bool isTransparent() const; // Expose our import as member status ImportAsMemberStatus getImportAsMemberStatus() const { return ImportAsMemberStatus(Bits.AbstractFunctionDecl.IAMStatus); } bool isImportAsMember() const { return getImportAsMemberStatus().isImportAsMember(); } bool isImportAsInstanceMember() const { return getImportAsMemberStatus().isInstance(); } bool isImportAsStaticMember() const { return getImportAsMemberStatus().isStatic(); } uint8_t getSelfIndex() const { return getImportAsMemberStatus().getSelfIndex(); } void setImportAsStaticMember() { auto newValue = getImportAsMemberStatus(); newValue.setStatic(); Bits.AbstractFunctionDecl.IAMStatus = newValue.getRawValue(); } void setSelfIndex(uint8_t idx) { auto newValue = getImportAsMemberStatus(); newValue.setSelfIndex(idx); Bits.AbstractFunctionDecl.IAMStatus = newValue.getRawValue(); } /// Retrieve the location of the 'async' keyword, if present. SourceLoc getAsyncLoc() const { return AsyncLoc; } /// Retrieve the location of the 'throws' keyword, if present. SourceLoc getThrowsLoc() const { return ThrowsLoc; } /// Returns true if the function is marked as `async`. The /// type of the function will be `async` as well. bool hasAsync() const { return Bits.AbstractFunctionDecl.Async; } /// Determine whether the given function is concurrent. /// /// A function is concurrent if it has the @Sendable attribute. bool isSendable() const; /// Returns true if the function is a suitable 'async' context. /// /// Functions that are an 'async' context can make calls to 'async' functions. bool isAsyncContext() const { return hasAsync(); } /// Returns true if the function body throws. bool hasThrows() const { return Bits.AbstractFunctionDecl.Throws; } /// Returns if the function throws or is async. bool hasEffect(EffectKind kind) const; /// Returns if the function is 'rethrows' or 'reasync'. bool hasPolymorphicEffect(EffectKind kind) const; /// Returns 'true' if the function is distributed. bool isDistributed() const; PolymorphicEffectKind getPolymorphicEffectKind(EffectKind kind) const; // FIXME: Hack that provides names with keyword arguments for accessors. DeclName getEffectiveFullName() const; /// Returns true if the function has a body written in the source file. /// /// Note that a true return value does not imply that the body was actually /// parsed. bool hasBody() const { return getBodyKind() != BodyKind::None && getBodyKind() != BodyKind::Skipped; } /// Returns true if the text of this function's body can be retrieved either /// by extracting the text from the source buffer or reading the inlinable /// body from a deserialized swiftmodule. bool hasInlinableBodyText() const; /// Returns the function body, if it was parsed, or nullptr otherwise. /// /// Note that a null return value does not imply that the source code did not /// have a body for this function. /// /// \sa hasBody() BraceStmt *getBody(bool canSynthesize = true) const; /// Retrieve the type-checked body of the given function, or \c nullptr if /// there's no body available. BraceStmt *getTypecheckedBody() const; /// Set a new body for the function. void setBody(BraceStmt *S, BodyKind NewBodyKind); /// Note that the body was skipped for this function. Function body /// cannot be attached after this call. void setBodySkipped(SourceRange bodyRange) { // FIXME: Remove 'Parsed' from this list once we can always delay // parsing bodies. The -experimental-skip-*-function-bodies options // do currently skip parsing, unless disabled through other means in // SourceFile::hasDelayedBodyParsing (eg. needing to build the full // syntax tree due to -verify-syntax-tree). assert(getBodyKind() == BodyKind::None || getBodyKind() == BodyKind::Unparsed || getBodyKind() == BodyKind::Parsed); assert(bodyRange.isValid()); BodyRange = bodyRange; setBodyKind(BodyKind::Skipped); } /// Note that parsing for the body was delayed. void setBodyDelayed(SourceRange bodyRange) { assert(getBodyKind() == BodyKind::None); assert(bodyRange.isValid()); BodyRange = bodyRange; setBodyKind(BodyKind::Unparsed); } void setBodyToBeReparsed(SourceRange bodyRange); /// Provide the parsed body for the function. void setBodyParsed(BraceStmt *S) { setBody(S, BodyKind::Parsed); } /// Was there a nested type declaration detected when parsing this /// function was skipped? bool hasNestedTypeDeclarations() const { return Bits.AbstractFunctionDecl.HasNestedTypeDeclarations; } void setHasNestedTypeDeclarations(bool value) { Bits.AbstractFunctionDecl.HasNestedTypeDeclarations = value; } /// Note that parsing for the body was delayed. /// /// The function should return the body statement and a flag indicating /// whether that body is already type-checked. void setBodySynthesizer( std::pair<BraceStmt *, bool> (* fn)(AbstractFunctionDecl *, void *), void *context = nullptr) { assert(getBodyKind() == BodyKind::None); Synthesizer = {fn, context}; setBodyKind(BodyKind::Synthesize); } /// Note that this is a memberwise initializer and thus the body will be /// generated by SILGen. void setIsMemberwiseInitializer() { assert(getBodyKind() == BodyKind::None); assert(isa<ConstructorDecl>(this)); setBodyKind(BodyKind::MemberwiseInitializer); } /// Gets the body of this function, stripping the unused portions of #if /// configs inside the body. If this function was not deserialized from a /// .swiftmodule, this body is reconstructed from the original /// source buffer. StringRef getInlinableBodyText(SmallVectorImpl<char> &scratch) const; void setBodyStringRepresentation(StringRef body) { assert(getBodyKind() == BodyKind::None); setBodyKind(BodyKind::Deserialized); BodyStringRepresentation = body; } bool isBodyTypeChecked() const { return getBodyKind() == BodyKind::TypeChecked; } bool isBodySkipped() const { return getBodyKind() == BodyKind::Skipped; } bool isMemberwiseInitializer() const { return getBodyKind() == BodyKind::MemberwiseInitializer; } /// For a method of a class, checks whether it will require a new entry in the /// vtable. bool needsNewVTableEntry() const; public: /// Retrieve the source range of the function body. SourceRange getBodySourceRange() const; /// Keep current \c getBodySourceRange() as the "original" body source range /// iff the this method hasn't been called on this object. The current body /// source range must be in the same buffer as the location of the declaration /// itself. void keepOriginalBodySourceRange(); /// Retrieve the source range of the *original* function body. /// /// This may be different from \c getBodySourceRange() that returns the source /// range of the *current* body. It happens when the body is parsed from other /// source buffers for e.g. code-completion. SourceRange getOriginalBodySourceRange() const; /// Retrieve the source range of the function declaration name + patterns. SourceRange getSignatureSourceRange() const; CaptureInfo getCaptureInfo() const { return Captures; } void setCaptureInfo(CaptureInfo captures) { Captures = captures; } /// Retrieve the Objective-C selector that names this method. ObjCSelector getObjCSelector(DeclName preferredName = DeclName(), bool skipIsObjCResolution = false) const; /// Determine whether the given method would produce an Objective-C /// instance method. bool isObjCInstanceMethod() const; /// Determine whether the name of an argument is an API name by default /// depending on the function context. bool argumentNameIsAPIByDefault() const; /// Retrieve the function's parameter list, not including 'self' if present. ParameterList *getParameters() { return Params; } const ParameterList *getParameters() const { return Params; } void setParameters(ParameterList *Params); bool hasImplicitSelfDecl() const { return Bits.AbstractFunctionDecl.HasImplicitSelfDecl; } ParamDecl **getImplicitSelfDeclStorage(); /// Retrieve the implicit 'self' parameter for methods. Returns nullptr for /// free functions. const ParamDecl *getImplicitSelfDecl(bool createIfNeeded=true) const { return const_cast<AbstractFunctionDecl*>(this) ->getImplicitSelfDecl(createIfNeeded); } ParamDecl *getImplicitSelfDecl(bool createIfNeeded=true); /// Retrieve the declaration that this method overrides, if any. AbstractFunctionDecl *getOverriddenDecl() const { return cast_or_null<AbstractFunctionDecl>(ValueDecl::getOverriddenDecl()); } /// Whether the declaration is later overridden in the module /// /// Overrides are resolved during type checking; only query this field after /// the whole module has been checked bool isOverridden() const { return Bits.AbstractFunctionDecl.Overridden; } /// The declaration has been overridden in the module /// /// Resolved during type checking void setIsOverridden() { Bits.AbstractFunctionDecl.Overridden = true; } /// Set information about the foreign error convention used by this /// declaration. void setForeignErrorConvention(const ForeignErrorConvention &convention); /// Get information about the foreign error convention used by this /// declaration, given that it is @objc and 'throws'. Optional<ForeignErrorConvention> getForeignErrorConvention() const; /// If this is a foreign C function imported as a method, get the index of /// the foreign parameter imported as `self`. If the function is imported /// as a static method, `-1` is returned to represent the `self` parameter /// being dropped altogether. `None` is returned for a normal function /// or method. Optional<int> getForeignFunctionAsMethodSelfParameterIndex() const; /// Set information about the foreign async convention used by this /// declaration. void setForeignAsyncConvention(const ForeignAsyncConvention &convention); /// Get information about the foreign async convention used by this /// declaration, given that it is @objc and 'async'. Optional<ForeignAsyncConvention> getForeignAsyncConvention() const; static bool classof(const Decl *D) { return D->getKind() >= DeclKind::First_AbstractFunctionDecl && D->getKind() <= DeclKind::Last_AbstractFunctionDecl; } static bool classof(const DeclContext *DC) { if (auto D = DC->getAsDecl()) return classof(D); return false; } /// True if the declaration is forced to be statically dispatched. bool hasForcedStaticDispatch() const; /// Get the type of this declaration without the Self clause. /// Asserts if not in type context. Type getMethodInterfaceType() const; /// Tests if this is a function returning a DynamicSelfType, or a /// constructor. bool hasDynamicSelfResult() const; /// The async function marked as the alternative to this function, if any. AbstractFunctionDecl *getAsyncAlternative() const; /// If \p asyncAlternative is set, then compare its parameters to this /// (presumed synchronous) function's parameters to find the index of the /// completion handler parameter. This should be the the only missing /// parameter in \p asyncAlternative, ignoring defaulted parameters if they /// have the same label. It must have a void-returning function type and be /// attributed with @escaping but not @autoclosure. /// /// Returns the last index of the parameter that looks like a completion /// handler if \p asyncAlternative is not set (with the same conditions on /// its type as above). Optional<unsigned> findPotentialCompletionHandlerParam( AbstractFunctionDecl *asyncAlternative = nullptr) const; /// Determine whether this function is implicitly known to have its /// parameters of function type be @_unsafeSendable. /// /// This hard-codes knowledge of a number of functions that will /// eventually have @_unsafeSendable and, eventually, @Sendable, /// on their parameters of function type. bool hasKnownUnsafeSendableFunctionParams() const; using DeclContext::operator new; using Decl::getASTContext; }; class OperatorDecl; enum class SelfAccessKind : uint8_t { NonMutating, Mutating, Consuming, }; /// Diagnostic printing of \c SelfAccessKind. llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, SelfAccessKind SAK); /// FuncDecl - 'func' declaration. class FuncDecl : public AbstractFunctionDecl { friend class AbstractFunctionDecl; friend class SelfAccessKindRequest; friend class IsStaticRequest; friend class ResultTypeRequest; SourceLoc StaticLoc; // Location of the 'static' token or invalid. SourceLoc FuncLoc; // Location of the 'func' token. TypeLoc FnRetType; protected: FuncDecl(DeclKind Kind, SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, SourceLoc FuncLoc, DeclName Name, SourceLoc NameLoc, bool Async, SourceLoc AsyncLoc, bool Throws, SourceLoc ThrowsLoc, bool HasImplicitSelfDecl, GenericParamList *GenericParams, DeclContext *Parent) : AbstractFunctionDecl(Kind, Parent, Name, NameLoc, Async, AsyncLoc, Throws, ThrowsLoc, HasImplicitSelfDecl, GenericParams), StaticLoc(StaticLoc), FuncLoc(FuncLoc) { assert(!Name.getBaseName().isSpecial()); Bits.FuncDecl.StaticSpelling = static_cast<unsigned>(StaticSpelling); Bits.FuncDecl.ForcedStaticDispatch = false; Bits.FuncDecl.SelfAccess = static_cast<unsigned>(SelfAccessKind::NonMutating); Bits.FuncDecl.SelfAccessComputed = false; Bits.FuncDecl.IsStaticComputed = false; Bits.FuncDecl.IsStatic = false; Bits.FuncDecl.HasTopLevelLocalContextCaptures = false; } void setResultInterfaceType(Type type); private: static FuncDecl *createImpl(ASTContext &Context, SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, SourceLoc FuncLoc, DeclName Name, SourceLoc NameLoc, bool Async, SourceLoc AsyncLoc, bool Throws, SourceLoc ThrowsLoc, GenericParamList *GenericParams, DeclContext *Parent, ClangNode ClangN); Optional<SelfAccessKind> getCachedSelfAccessKind() const { if (Bits.FuncDecl.SelfAccessComputed) return static_cast<SelfAccessKind>(Bits.FuncDecl.SelfAccess); return None; } Optional<bool> getCachedIsStatic() const { if (Bits.FuncDecl.IsStaticComputed) return Bits.FuncDecl.IsStatic; return None; } public: /// Factory function only for use by deserialization. static FuncDecl *createDeserialized(ASTContext &Context, StaticSpellingKind StaticSpelling, DeclName Name, bool Async, bool Throws, GenericParamList *GenericParams, Type FnRetType, DeclContext *Parent); static FuncDecl *create(ASTContext &Context, SourceLoc StaticLoc, StaticSpellingKind StaticSpelling, SourceLoc FuncLoc, DeclName Name, SourceLoc NameLoc, bool Async, SourceLoc AsyncLoc, bool Throws, SourceLoc ThrowsLoc, GenericParamList *GenericParams, ParameterList *BodyParams, TypeRepr *ResultTyR, DeclContext *Parent); static FuncDecl *createImplicit(ASTContext &Context, StaticSpellingKind StaticSpelling, DeclName Name, SourceLoc NameLoc, bool Async, bool Throws, GenericParamList *GenericParams, ParameterList *BodyParams, Type FnRetType, DeclContext *Parent); static FuncDecl *createImported(ASTContext &Context, SourceLoc FuncLoc, DeclName Name, SourceLoc NameLoc, bool Async, bool Throws, ParameterList *BodyParams, Type FnRetType, GenericParamList *GenericParams, DeclContext *Parent, ClangNode ClangN); bool isStatic() const; /// \returns the way 'static'/'class' was spelled in the source. StaticSpellingKind getStaticSpelling() const { return static_cast<StaticSpellingKind>(Bits.FuncDecl.StaticSpelling); } /// \returns the way 'static'/'class' should be spelled for this declaration. StaticSpellingKind getCorrectStaticSpelling() const; void setStatic(bool IsStatic = true) { Bits.FuncDecl.IsStaticComputed = true; Bits.FuncDecl.IsStatic = IsStatic; } bool isMutating() const { return getSelfAccessKind() == SelfAccessKind::Mutating; } bool isNonMutating() const { return getSelfAccessKind() == SelfAccessKind::NonMutating; } bool isConsuming() const { return getSelfAccessKind() == SelfAccessKind::Consuming; } bool isCallAsFunctionMethod() const; bool isMainTypeMainMethod() const; SelfAccessKind getSelfAccessKind() const; void setSelfAccessKind(SelfAccessKind mod) { Bits.FuncDecl.SelfAccess = static_cast<unsigned>(mod); Bits.FuncDecl.SelfAccessComputed = true; } SourceLoc getStaticLoc() const { return StaticLoc; } SourceLoc getFuncLoc() const { return FuncLoc; } SourceLoc getStartLoc() const { return StaticLoc.isValid() && !isa<AccessorDecl>(this) ? StaticLoc : FuncLoc; } SourceRange getSourceRange() const; TypeRepr *getResultTypeRepr() const { return FnRetType.getTypeRepr(); } SourceRange getResultTypeSourceRange() const { return FnRetType.getSourceRange(); } /// Retrieve the result interface type of this function. Type getResultInterfaceType() const; /// isUnaryOperator - Determine whether this is a unary operator /// implementation. This check is a syntactic rather than type-based check, /// which looks at the number of parameters specified, in order to allow /// for the definition of unary operators on tuples, as in: /// /// prefix func + (param : (a:Int, b:Int)) /// /// This also allows the unary-operator-ness of a func decl to be determined /// prior to type checking. bool isUnaryOperator() const; /// isBinaryOperator - Determine whether this is a binary operator /// implementation. This check is a syntactic rather than type-based check, /// which looks at the number of parameters specified, in order to allow /// distinguishing a binary operator from a unary operator on tuples, as in: /// /// prefix func + (_:(a:Int, b:Int)) // unary operator +(1,2) /// infix func + (a:Int, b:Int) // binary operator 1 + 2 /// /// This also allows the binary-operator-ness of a func decl to be determined /// prior to type checking. bool isBinaryOperator() const; void getLocalCaptures(SmallVectorImpl<CapturedValue> &Result) const { return getCaptureInfo().getLocalCaptures(Result); } ParamDecl **getImplicitSelfDeclStorage(); /// Get the supertype method this method overrides, if any. FuncDecl *getOverriddenDecl() const { return cast_or_null<FuncDecl>(AbstractFunctionDecl::getOverriddenDecl()); } OperatorDecl *getOperatorDecl() const; /// Returns true if the function is forced to be statically dispatched. bool hasForcedStaticDispatch() const { return Bits.FuncDecl.ForcedStaticDispatch; } void setForcedStaticDispatch(bool flag) { Bits.FuncDecl.ForcedStaticDispatch = flag; } static bool classof(const Decl *D) { return D->getKind() == DeclKind::Func || D->getKind() == DeclKind::Accessor; } static bool classof(const AbstractFunctionDecl *D) { return classof(static_cast<const Decl*>(D)); } static bool classof(const DeclContext *DC) { if (auto D = DC->getAsDecl()) return classof(D); return false; } /// True if the function is a defer body. bool isDeferBody() const; /// Perform basic checking to determine whether the @IBAction or /// @IBSegueAction attribute can be applied to this function. bool isPotentialIBActionTarget() const; bool hasTopLevelLocalContextCaptures() const { return Bits.FuncDecl.HasTopLevelLocalContextCaptures; } void setHasTopLevelLocalContextCaptures(bool hasCaptures=true); }; /// This represents an accessor function, such as a getter or setter. class AccessorDecl final : public FuncDecl { /// Location of the accessor keyword, e.g. 'set'. SourceLoc AccessorKeywordLoc; AbstractStorageDecl *Storage; AccessorDecl(SourceLoc declLoc, SourceLoc accessorKeywordLoc, AccessorKind accessorKind, AbstractStorageDecl *storage, SourceLoc staticLoc, StaticSpellingKind staticSpelling, bool async, SourceLoc asyncLoc, bool throws, SourceLoc throwsLoc, bool hasImplicitSelfDecl, GenericParamList *genericParams, DeclContext *parent) : FuncDecl(DeclKind::Accessor, staticLoc, staticSpelling, /*func loc*/ declLoc, /*name*/ Identifier(), /*name loc*/ declLoc, async, asyncLoc, throws, throwsLoc, hasImplicitSelfDecl, genericParams, parent), AccessorKeywordLoc(accessorKeywordLoc), Storage(storage) { assert(!async || accessorKind == AccessorKind::Get && "only get accessors can be async"); Bits.AccessorDecl.AccessorKind = unsigned(accessorKind); } static AccessorDecl *createImpl(ASTContext &ctx, SourceLoc declLoc, SourceLoc accessorKeywordLoc, AccessorKind accessorKind, AbstractStorageDecl *storage, SourceLoc staticLoc, StaticSpellingKind staticSpelling, bool async, SourceLoc asyncLoc, bool throws, SourceLoc throwsLoc, GenericParamList *genericParams, DeclContext *parent, ClangNode clangNode); Optional<bool> getCachedIsTransparent() const { if (Bits.AccessorDecl.IsTransparentComputed) return Bits.AccessorDecl.IsTransparent; return None; } friend class IsAccessorTransparentRequest; public: static AccessorDecl *createDeserialized(ASTContext &ctx, AccessorKind accessorKind, AbstractStorageDecl *storage, StaticSpellingKind staticSpelling, bool async, bool throws, GenericParamList *genericParams, Type fnRetType, DeclContext *parent); static AccessorDecl *create(ASTContext &ctx, SourceLoc declLoc, SourceLoc accessorKeywordLoc, AccessorKind accessorKind, AbstractStorageDecl *storage, SourceLoc staticLoc, StaticSpellingKind staticSpelling, bool async, SourceLoc asyncLoc, bool throws, SourceLoc throwsLoc, GenericParamList *genericParams, ParameterList *parameterList, Type fnRetType, DeclContext *parent, ClangNode clangNode = ClangNode()); SourceLoc getAccessorKeywordLoc() const { return AccessorKeywordLoc; } AbstractStorageDecl *getStorage() const { return Storage; } AccessorKind getAccessorKind() const { return AccessorKind(Bits.AccessorDecl.AccessorKind); } bool isGetter() const { return getAccessorKind() == AccessorKind::Get; } bool isSetter() const { return getAccessorKind() == AccessorKind::Set; } bool isAnyAddressor() const { auto kind = getAccessorKind(); return kind == AccessorKind::Address || kind == AccessorKind::MutableAddress; } /// isGetterOrSetter - Determine whether this is specifically a getter or /// a setter, as opposed to some other kind of accessor. /// /// For example, only getters and setters can be exposed to Objective-C. bool isGetterOrSetter() const { return isGetter() || isSetter(); } bool isObservingAccessor() const { switch (getAccessorKind()) { #define OBSERVING_ACCESSOR(ID, KEYWORD) \ case AccessorKind::ID: return true; #define ACCESSOR(ID) \ case AccessorKind::ID: return false; #include "swift/AST/AccessorKinds.def" } llvm_unreachable("bad accessor kind"); } /// \returns true if this is non-mutating due to applying a 'mutating' /// attribute. For example a "mutating set" accessor. bool isExplicitNonMutating() const; /// Is the accesor one of the kinds that's assumed nonmutating by default? bool isAssumedNonMutating() const; /// Is this accessor one of the kinds that's implicitly a coroutine? bool isCoroutine() const { switch (getAccessorKind()) { #define COROUTINE_ACCESSOR(ID, KEYWORD) \ case AccessorKind::ID: return true; #define ACCESSOR(ID) \ case AccessorKind::ID: return false; #include "swift/AST/AccessorKinds.def" } llvm_unreachable("bad accessor kind"); } bool isImplicitGetter() const { return isGetter() && getAccessorKeywordLoc().isInvalid(); } /// Is this accessor a "simple" didSet? A "simple" didSet does not /// use the implicit oldValue parameter in its body or does not have /// an explicit parameter in its parameter list. bool isSimpleDidSet() const; void setIsTransparent(bool transparent) { Bits.AccessorDecl.IsTransparent = transparent; Bits.AccessorDecl.IsTransparentComputed = 1; } static bool classof(const Decl *D) { return D->getKind() == DeclKind::Accessor; } static bool classof(const AbstractFunctionDecl *D) { return classof(static_cast<const Decl*>(D)); } static bool classof(const DeclContext *DC) { if (auto D = DC->getAsDecl()) return classof(D); return false; } }; inline AccessorDecl * AbstractStorageDecl::AccessorRecord::getAccessor(AccessorKind kind) const { if (auto optIndex = AccessorIndices[unsigned(kind)]) { auto accessor = getAllAccessors()[optIndex - 1]; assert(accessor && accessor->getAccessorKind() == kind); return accessor; } return nullptr; } /// This represents a 'case' declaration in an 'enum', which may declare /// one or more individual comma-separated EnumElementDecls. class EnumCaseDecl final : public Decl, private llvm::TrailingObjects<EnumCaseDecl, EnumElementDecl *> { friend TrailingObjects; friend class Decl; SourceLoc CaseLoc; EnumCaseDecl(SourceLoc CaseLoc, ArrayRef<EnumElementDecl *> Elements, DeclContext *DC) : Decl(DeclKind::EnumCase, DC), CaseLoc(CaseLoc) { Bits.EnumCaseDecl.NumElements = Elements.size(); std::uninitialized_copy(Elements.begin(), Elements.end(), getTrailingObjects<EnumElementDecl *>()); } SourceLoc getLocFromSource() const { return CaseLoc; } public: static EnumCaseDecl *create(SourceLoc CaseLoc, ArrayRef<EnumElementDecl*> Elements, DeclContext *DC); /// Get the list of elements declared in this case. ArrayRef<EnumElementDecl *> getElements() const { return {getTrailingObjects<EnumElementDecl *>(), Bits.EnumCaseDecl.NumElements}; } SourceRange getSourceRange() const; static bool classof(const Decl *D) { return D->getKind() == DeclKind::EnumCase; } }; /// This represents a single case of an 'enum' declaration. /// /// For example, the X, Y, and Z in this enum: /// /// \code /// enum V { /// case X(Int), Y(Int) /// case Z /// } /// \endcode /// /// The type of an EnumElementDecl is always the EnumType for the containing /// enum. EnumElementDecls are represented in the AST as members of their /// parent EnumDecl, although syntactically they are subordinate to the /// EnumCaseDecl. class EnumElementDecl : public DeclContext, public ValueDecl { friend class EnumRawValuesRequest; /// This is the type specified with the enum element, for /// example 'Int' in 'case Y(Int)'. This is null if there is no type /// associated with this element, as in 'case Z' or in all elements of enum /// definitions. ParameterList *Params; SourceLoc EqualsLoc; /// The raw value literal for the enum element, or null. LiteralExpr *RawValueExpr; public: EnumElementDecl(SourceLoc IdentifierLoc, DeclName Name, ParameterList *Params, SourceLoc EqualsLoc, LiteralExpr *RawValueExpr, DeclContext *DC); /// Returns the string for the base name, or "_" if this is unnamed. StringRef getNameStr() const { assert(!getName().isSpecial() && "Cannot get string for special names"); return hasName() ? getBaseIdentifier().str() : "_"; } Type getArgumentInterfaceType() const; void setParameterList(ParameterList *params); ParameterList *getParameterList() const { return Params; } /// Retrieves a fully typechecked raw value expression associated /// with this enum element, if it exists. LiteralExpr *getRawValueExpr() const; /// Retrieves a "structurally" checked raw value expression associated /// with this enum element, if it exists. /// /// The structural raw value may or may not have a type set, but it is /// guaranteed to be suitable for retrieving any non-semantic information /// like digit text for an integral raw value or user text for a string raw value. LiteralExpr *getStructuralRawValueExpr() const; /// Reset the raw value expression. void setRawValueExpr(LiteralExpr *e); /// Return the containing EnumDecl. EnumDecl *getParentEnum() const { return cast<EnumDecl>(getDeclContext()); } /// Return the containing EnumCaseDecl. EnumCaseDecl *getParentCase() const; SourceLoc getStartLoc() const { return getNameLoc(); } SourceRange getSourceRange() const; bool hasAssociatedValues() const { return getParameterList() != nullptr; } /// True if the case is marked 'indirect'. bool isIndirect() const { return getAttrs().hasAttribute<IndirectAttr>(); } /// Do not call this! /// It exists to let the AST walkers get the raw value without forcing a request. LiteralExpr *getRawValueUnchecked() const { return RawValueExpr; } static bool classof(const Decl *D) { return D->getKind() == DeclKind::EnumElement; } static bool classof(const DeclContext *DC) { if (auto D = DC->getAsDecl()) return classof(D); return false; } using DeclContext::operator new; using Decl::getASTContext; }; inline SourceRange EnumCaseDecl::getSourceRange() const { auto subRange = getElements().back()->getSourceRange(); if (subRange.isValid()) return {CaseLoc, subRange.End}; return {}; } /// Describes the kind of initializer. enum class CtorInitializerKind { /// A designated initializer is an initializer responsible for initializing /// the stored properties of the current class and chaining to a superclass's /// designated initializer (for non-root classes). /// /// Designated initializers are never inherited. Designated, /// A convenience initializer is an initializer that initializes a complete /// object by delegating to another initializer (eventually reaching a /// designated initializer). /// /// Convenience initializers are inherited into subclasses that override /// all of their superclass's designated initializers. Convenience, /// A convenience factory initializer is a convenience initializer introduced /// by an imported Objective-C factory method. /// /// Convenience factory initializers cannot be expressed directly in /// Swift; rather, they are produced by the Clang importer when importing /// an instancetype factory method from Objective-C. ConvenienceFactory, /// A factory initializer is an initializer that is neither designated nor /// convenience: it can be used to create an object of the given type, but /// cannot be chained to via "super.init" nor is it inherited. /// /// A factory initializer is written with a return type of the class name /// itself. FIXME: However, this is only a presentation form, and at present /// the only factory initializers are produced by importing an Objective-C /// factory method that does not return instancetype. /// /// FIXME: Arguably, structs and enums only have factory initializers, and /// using designated initializers for them is a misnomer. Factory }; /// Specifies the kind of initialization call performed within the body /// of the constructor, e.g., self.init or super.init. enum class BodyInitKind { /// There are no calls to self.init or super.init. None, /// There is a call to self.init, which delegates to another (peer) /// initializer. Delegating, /// There is a call to super.init, which chains to a superclass initializer. Chained, /// There are no calls to self.init or super.init explicitly in the body of /// the constructor, but a 'super.init' call will be implicitly added /// by semantic analysis. ImplicitChained }; struct BodyInitKindAndExpr { BodyInitKind initKind; ApplyExpr *initExpr; BodyInitKindAndExpr() : initKind(BodyInitKind::None), initExpr(nullptr) {} BodyInitKindAndExpr(BodyInitKind initKind, ApplyExpr *initExpr) : initKind(initKind), initExpr(initExpr) {} friend bool operator==(BodyInitKindAndExpr lhs, BodyInitKindAndExpr rhs) { return (lhs.initKind == rhs.initKind && lhs.initExpr == rhs.initExpr); } }; /// ConstructorDecl - Declares a constructor for a type. For example: /// /// \code /// struct X { /// var x : Int /// init(i : Int) { /// x = i /// } /// } /// \endcode class ConstructorDecl : public AbstractFunctionDecl { /// The location of the '!' or '?' for a failable initializer. SourceLoc FailabilityLoc; ParamDecl *SelfDecl; /// The interface type of the initializing constructor. Type InitializerInterfaceType; /// The typechecked call to super.init expression, which needs to be /// inserted at the end of the initializer by SILGen. Expr *CallToSuperInit = nullptr; public: ConstructorDecl(DeclName Name, SourceLoc ConstructorLoc, bool Failable, SourceLoc FailabilityLoc, bool Async, SourceLoc AsyncLoc, bool Throws, SourceLoc ThrowsLoc, ParameterList *BodyParams, GenericParamList *GenericParams, DeclContext *Parent); static ConstructorDecl * createImported(ASTContext &ctx, ClangNode clangNode, DeclName name, SourceLoc constructorLoc, bool failable, SourceLoc failabilityLoc, bool async, SourceLoc asyncLoc, bool throws, SourceLoc throwsLoc, ParameterList *bodyParams, GenericParamList *genericParams, DeclContext *parent); SourceLoc getConstructorLoc() const { return getNameLoc(); } SourceLoc getStartLoc() const { return getConstructorLoc(); } SourceRange getSourceRange() const; /// Get the interface type of the constructed object. Type getResultInterfaceType() const; /// Get the interface type of the initializing constructor. Type getInitializerInterfaceType(); /// Get the typechecked call to super.init expression, which needs to be /// inserted at the end of the initializer by SILGen. Expr *getSuperInitCall() { return CallToSuperInit; } void setSuperInitCall(Expr *CallExpr) { CallToSuperInit = CallExpr; } ParamDecl **getImplicitSelfDeclStorage() { return &SelfDecl; } /// Determine whether the body of this constructor contains any delegating /// or superclass initializations (\c self.init or \c super.init, /// respectively) within its body. BodyInitKindAndExpr getDelegatingOrChainedInitKind() const; void clearCachedDelegatingOrChainedInitKind(); /// Whether this constructor is required. bool isRequired() const { return getAttrs().hasAttribute<RequiredAttr>(); } /// Determine the kind of initializer this is. CtorInitializerKind getInitKind() const; /// Whether this is a designated initializer. bool isDesignatedInit() const { return getInitKind() == CtorInitializerKind::Designated; } /// Whether this is a convenience initializer. bool isConvenienceInit() const { return getInitKind() == CtorInitializerKind::Convenience || getInitKind() == CtorInitializerKind::ConvenienceFactory; } /// Whether this is a factory initializer. bool isFactoryInit() const { switch (getInitKind()) { case CtorInitializerKind::Designated: case CtorInitializerKind::Convenience: return false; case CtorInitializerKind::Factory: case CtorInitializerKind::ConvenienceFactory: return true; } llvm_unreachable("bad CtorInitializerKind"); } /// Determine whether this initializer is inheritable. bool isInheritable() const { switch (getInitKind()) { case CtorInitializerKind::Designated: case CtorInitializerKind::Factory: return false; case CtorInitializerKind::Convenience: case CtorInitializerKind::ConvenienceFactory: return true; } llvm_unreachable("bad CtorInitializerKind"); } /// Determine if this is a failable initializer. bool isFailable() const { return Bits.ConstructorDecl.Failable; } /// Retrieve the location of the '!' or '?' in a failable initializer. SourceLoc getFailabilityLoc() const { return FailabilityLoc; } /// Whether the implementation of this method is a stub that traps at runtime. bool hasStubImplementation() const { return Bits.ConstructorDecl.HasStubImplementation; } /// Set whether the implementation of this method is a stub that /// traps at runtime. void setStubImplementation(bool stub) { Bits.ConstructorDecl.HasStubImplementation = stub; } ConstructorDecl *getOverriddenDecl() const { return cast_or_null<ConstructorDecl>( AbstractFunctionDecl::getOverriddenDecl()); } /// Determine whether this initializer falls into the special case for /// Objective-C initializers with selectors longer than "init", e.g., /// \c initForMemory. /// /// In such cases, one can write the Swift initializer /// with a single parameter of type '()', e.g, /// /// \code /// @objc init(forMemory: ()) /// \endcode bool isObjCZeroParameterWithLongSelector() const; /// Checks if the initializer is a distributed actor's 'local' initializer: /// ``` /// init(transport: ActorTransport) /// ``` bool isDistributedActorLocalInit() const; /// Checks if the initializer is a distributed actor's 'resolve' initializer: /// ``` /// init(resolve address: ActorAddress, using transport: ActorTransport) /// ``` bool isDistributedActorResolveInit() const; static bool classof(const Decl *D) { return D->getKind() == DeclKind::Constructor; } static bool classof(const AbstractFunctionDecl *D) { return classof(static_cast<const Decl*>(D)); } static bool classof(const DeclContext *DC) { if (auto D = DC->getAsDecl()) return classof(D); return false; } }; /// DestructorDecl - Declares a destructor for a type. For example: /// /// \code /// struct X { /// var fd : Int /// deinit { /// close(fd) /// } /// } /// \endcode class DestructorDecl : public AbstractFunctionDecl { ParamDecl *SelfDecl; public: DestructorDecl(SourceLoc DestructorLoc, DeclContext *Parent); ParamDecl **getImplicitSelfDeclStorage() { return &SelfDecl; } SourceLoc getDestructorLoc() const { return getNameLoc(); } SourceLoc getStartLoc() const { return getDestructorLoc(); } SourceRange getSourceRange() const; /// Retrieve the Objective-C selector for destructors. ObjCSelector getObjCSelector() const; static bool classof(const Decl *D) { return D->getKind() == DeclKind::Destructor; } static bool classof(const AbstractFunctionDecl *D) { return classof(static_cast<const Decl*>(D)); } static bool classof(const DeclContext *DC) { if (auto D = DC->getAsDecl()) return classof(D); return false; } }; /// Declares a precedence group. For example: /// /// \code /// precedencegroup MultiplicativePrecedence { /// associativity: right /// higherThan: AdditivePrecedence /// } /// \endcode class PrecedenceGroupDecl : public Decl { public: struct Relation { SourceLoc NameLoc; Identifier Name; PrecedenceGroupDecl *Group; }; private: SourceLoc PrecedenceGroupLoc, NameLoc, LBraceLoc, RBraceLoc; SourceLoc AssociativityKeywordLoc, AssociativityValueLoc; SourceLoc AssignmentKeywordLoc, AssignmentValueLoc; SourceLoc HigherThanLoc, LowerThanLoc; Identifier Name; unsigned NumHigherThan, NumLowerThan; // Tail-allocated array of Relations Relation *getHigherThanBuffer() { return reinterpret_cast<Relation*>(this + 1); } const Relation *getHigherThanBuffer() const { return reinterpret_cast<const Relation*>(this + 1); } Relation *getLowerThanBuffer() { return getHigherThanBuffer() + NumHigherThan; } const Relation *getLowerThanBuffer() const { return getHigherThanBuffer() + NumHigherThan; } PrecedenceGroupDecl(DeclContext *DC, SourceLoc precedenceGroupLoc, SourceLoc nameLoc, Identifier name, SourceLoc lbraceLoc, SourceLoc associativityKeywordLoc, SourceLoc associativityValueLoc, Associativity associativity, SourceLoc assignmentKeywordLoc, SourceLoc assignmentValueLoc, bool isAssignment, SourceLoc higherThanLoc, ArrayRef<Relation> higherThan, SourceLoc lowerThanLoc, ArrayRef<Relation> lowerThan, SourceLoc rbraceLoc); friend class Decl; SourceLoc getLocFromSource() const { return NameLoc; } public: static PrecedenceGroupDecl *create(DeclContext *dc, SourceLoc precedenceGroupLoc, SourceLoc nameLoc, Identifier name, SourceLoc lbraceLoc, SourceLoc associativityKeywordLoc, SourceLoc associativityValueLoc, Associativity associativity, SourceLoc assignmentKeywordLoc, SourceLoc assignmentValueLoc, bool isAssignment, SourceLoc higherThanLoc, ArrayRef<Relation> higherThan, SourceLoc lowerThanLoc, ArrayRef<Relation> lowerThan, SourceLoc rbraceLoc); SourceRange getSourceRange() const { return { PrecedenceGroupLoc, RBraceLoc }; } /// Return the location of 'precedencegroup' in: /// precedencegroup MultiplicativePrecedence { ... } SourceLoc getPrecedenceGroupLoc() const { return PrecedenceGroupLoc; } /// Return the location of 'MultiplicativePrecedence' in: /// precedencegroup MultiplicativePrecedence { ... } SourceLoc getNameLoc() const { return NameLoc; } Identifier getName() const { return Name; } // This is needed to allow templated code to work with both ValueDecls and // PrecedenceGroupDecls. DeclBaseName getBaseName() const { return Name; } SourceLoc getLBraceLoc() const { return LBraceLoc; } SourceLoc getRBraceLoc() const { return RBraceLoc; } bool isAssociativityImplicit() const { return AssociativityKeywordLoc.isInvalid(); } /// Return the location of 'associativity' in: /// associativity: left SourceLoc getAssociativityKeywordLoc() const { return AssociativityKeywordLoc; } /// Return the location of 'right' in: /// associativity: right SourceLoc getAssociativityValueLoc() const { return AssociativityValueLoc; } Associativity getAssociativity() const { return Associativity(Bits.PrecedenceGroupDecl.Associativity); } bool isLeftAssociative() const { return getAssociativity() == Associativity::Left; } bool isRightAssociative() const { return getAssociativity() == Associativity::Right; } bool isNonAssociative() const { return getAssociativity() == Associativity::None; } bool isAssignmentImplicit() const { return AssignmentKeywordLoc.isInvalid(); } /// Return the location of 'assignment' in: /// assignment: true SourceLoc getAssignmentKeywordLoc() const { return AssignmentKeywordLoc; } /// Return the location of 'assignment' in: /// assignment: true SourceLoc getAssignmentValueLoc() const { return AssignmentValueLoc; } bool isAssignment() const { return Bits.PrecedenceGroupDecl.IsAssignment; } bool isHigherThanImplicit() const { return HigherThanLoc.isInvalid(); } /// Return the location of 'higherThan' in: /// higherThan: AdditivePrecedence SourceLoc getHigherThanLoc() const { return HigherThanLoc; } /// Retrieve the array of \c Relation objects containing those precedence /// groups with higher precedence than this precedence group. /// /// The elements of this array may be invalid, in which case they will have /// null \c PrecedenceGroupDecl elements. ArrayRef<Relation> getHigherThan() const { return { getHigherThanBuffer(), NumHigherThan }; } MutableArrayRef<Relation> getMutableHigherThan() { return { getHigherThanBuffer(), NumHigherThan }; } bool isLowerThanImplicit() const { return LowerThanLoc.isInvalid(); } /// Return the location of 'lowerThan' in: /// lowerThan: MultiplicativePrecedence SourceLoc getLowerThanLoc() const { return LowerThanLoc; } /// Retrieve the array of \c Relation objects containing those precedence /// groups with lower precedence than this precedence group. /// /// The elements of this array may be invalid, in which case they will have /// null \c PrecedenceGroupDecl elements. ArrayRef<Relation> getLowerThan() const { return { getLowerThanBuffer(), NumLowerThan }; } MutableArrayRef<Relation> getMutableLowerThan() { return { getLowerThanBuffer(), NumLowerThan }; } static bool classof(const Decl *D) { return D->getKind() == DeclKind::PrecedenceGroup; } }; /// The fixity of an OperatorDecl. enum class OperatorFixity : uint8_t { Infix, Prefix, Postfix }; inline void simple_display(llvm::raw_ostream &out, OperatorFixity fixity) { switch (fixity) { case OperatorFixity::Infix: out << "infix"; return; case OperatorFixity::Prefix: out << "prefix"; return; case OperatorFixity::Postfix: out << "postfix"; return; } llvm_unreachable("Unhandled case in switch"); } /// Abstract base class of operator declarations. class OperatorDecl : public Decl { SourceLoc OperatorLoc, NameLoc; Identifier name; ArrayRef<Located<Identifier>> Identifiers; ArrayRef<NominalTypeDecl *> DesignatedNominalTypes; SourceLoc getLocFromSource() const { return NameLoc; } friend class Decl; public: OperatorDecl(DeclKind kind, DeclContext *DC, SourceLoc OperatorLoc, Identifier Name, SourceLoc NameLoc, ArrayRef<Located<Identifier>> Identifiers) : Decl(kind, DC), OperatorLoc(OperatorLoc), NameLoc(NameLoc), name(Name), Identifiers(Identifiers) {} OperatorDecl(DeclKind kind, DeclContext *DC, SourceLoc OperatorLoc, Identifier Name, SourceLoc NameLoc, ArrayRef<NominalTypeDecl *> DesignatedNominalTypes) : Decl(kind, DC), OperatorLoc(OperatorLoc), NameLoc(NameLoc), name(Name), DesignatedNominalTypes(DesignatedNominalTypes) {} /// Retrieve the operator's fixity, corresponding to the concrete subclass /// of the OperatorDecl. OperatorFixity getFixity() const { switch (getKind()) { #define DECL(Id, Name) case DeclKind::Id: llvm_unreachable("Not an operator!"); #define OPERATOR_DECL(Id, Name) #include "swift/AST/DeclNodes.def" case DeclKind::InfixOperator: return OperatorFixity::Infix; case DeclKind::PrefixOperator: return OperatorFixity::Prefix; case DeclKind::PostfixOperator: return OperatorFixity::Postfix; } llvm_unreachable("inavlid decl kind"); } SourceLoc getOperatorLoc() const { return OperatorLoc; } SourceLoc getNameLoc() const { return NameLoc; } Identifier getName() const { return name; } // This is needed to allow templated code to work with both ValueDecls and // OperatorDecls. DeclBaseName getBaseName() const { return name; } /// Get the list of identifiers after the colon in the operator declaration. /// /// This list includes the names of designated types. For infix operators, the /// first item in the list is a precedence group instead. /// /// \todo These two purposes really ought to be in separate properties and the /// designated type list should be of TypeReprs instead of Identifiers. ArrayRef<Located<Identifier>> getIdentifiers() const { return Identifiers; } ArrayRef<NominalTypeDecl *> getDesignatedNominalTypes() const { return DesignatedNominalTypes; } void setDesignatedNominalTypes(ArrayRef<NominalTypeDecl *> nominalTypes) { DesignatedNominalTypes = nominalTypes; } static bool classof(const Decl *D) { // Workaround: http://llvm.org/PR35906 if (DeclKind::Last_Decl == DeclKind::Last_OperatorDecl) return D->getKind() >= DeclKind::First_OperatorDecl; return D->getKind() >= DeclKind::First_OperatorDecl && D->getKind() <= DeclKind::Last_OperatorDecl; } }; /// Declares the behavior of an infix operator. For example: /// /// \code /// infix operator /+/ : AdditionPrecedence, Numeric /// \endcode class InfixOperatorDecl : public OperatorDecl { SourceLoc ColonLoc; public: InfixOperatorDecl(DeclContext *DC, SourceLoc operatorLoc, Identifier name, SourceLoc nameLoc, SourceLoc colonLoc, ArrayRef<Located<Identifier>> identifiers) : OperatorDecl(DeclKind::InfixOperator, DC, operatorLoc, name, nameLoc, identifiers), ColonLoc(colonLoc) {} SourceLoc getEndLoc() const { auto identifiers = getIdentifiers(); if (identifiers.empty()) return getNameLoc(); return identifiers.back().Loc; } SourceRange getSourceRange() const { return { getOperatorLoc(), getEndLoc() }; } SourceLoc getColonLoc() const { return ColonLoc; } PrecedenceGroupDecl *getPrecedenceGroup() const; static bool classof(const Decl *D) { return D->getKind() == DeclKind::InfixOperator; } }; /// Declares the behavior of a prefix operator. For example: /// /// \code /// prefix operator /+/ {} /// \endcode class PrefixOperatorDecl : public OperatorDecl { public: PrefixOperatorDecl(DeclContext *DC, SourceLoc OperatorLoc, Identifier Name, SourceLoc NameLoc, ArrayRef<Located<Identifier>> Identifiers) : OperatorDecl(DeclKind::PrefixOperator, DC, OperatorLoc, Name, NameLoc, Identifiers) {} PrefixOperatorDecl(DeclContext *DC, SourceLoc OperatorLoc, Identifier Name, SourceLoc NameLoc, ArrayRef<NominalTypeDecl *> designatedNominalTypes) : OperatorDecl(DeclKind::PrefixOperator, DC, OperatorLoc, Name, NameLoc, designatedNominalTypes) {} SourceRange getSourceRange() const { return { getOperatorLoc(), getNameLoc() }; } static bool classof(const Decl *D) { return D->getKind() == DeclKind::PrefixOperator; } }; /// Declares the behavior of a postfix operator. For example: /// /// \code /// postfix operator /+/ {} /// \endcode class PostfixOperatorDecl : public OperatorDecl { public: PostfixOperatorDecl(DeclContext *DC, SourceLoc OperatorLoc, Identifier Name, SourceLoc NameLoc, ArrayRef<Located<Identifier>> Identifiers) : OperatorDecl(DeclKind::PostfixOperator, DC, OperatorLoc, Name, NameLoc, Identifiers) {} PostfixOperatorDecl(DeclContext *DC, SourceLoc OperatorLoc, Identifier Name, SourceLoc NameLoc, ArrayRef<NominalTypeDecl *> designatedNominalTypes) : OperatorDecl(DeclKind::PostfixOperator, DC, OperatorLoc, Name, NameLoc, designatedNominalTypes) {} SourceRange getSourceRange() const { return { getOperatorLoc(), getNameLoc() }; } static bool classof(const Decl *D) { return D->getKind() == DeclKind::PostfixOperator; } }; /// Represents a hole where a declaration should have been. /// /// Among other things, these are used to keep vtable layout consistent. class MissingMemberDecl : public Decl { DeclName Name; MissingMemberDecl(DeclContext *DC, DeclName name, unsigned vtableEntries, unsigned fieldOffsetVectorEntries) : Decl(DeclKind::MissingMember, DC), Name(name) { Bits.MissingMemberDecl.NumberOfVTableEntries = vtableEntries; assert(getNumberOfVTableEntries() == vtableEntries && "not enough bits"); Bits.MissingMemberDecl.NumberOfFieldOffsetVectorEntries = fieldOffsetVectorEntries; assert(getNumberOfFieldOffsetVectorEntries() == fieldOffsetVectorEntries && "not enough bits"); setImplicit(); } friend class Decl; SourceLoc getLocFromSource() const { return SourceLoc(); } public: static MissingMemberDecl * create(ASTContext &ctx, DeclContext *DC, DeclName name, unsigned numVTableEntries, bool hasStorage) { assert(!numVTableEntries || isa<ProtocolDecl>(DC) || isa<ClassDecl>(DC) && "Only classes and protocols have vtable/witness table entries"); assert(!hasStorage || !isa<ProtocolDecl>(DC) && "Protocols cannot have missing stored properties"); return new (ctx) MissingMemberDecl(DC, name, numVTableEntries, hasStorage); } DeclName getName() const { return Name; } unsigned getNumberOfVTableEntries() const { return Bits.MissingMemberDecl.NumberOfVTableEntries; } unsigned getNumberOfFieldOffsetVectorEntries() const { return Bits.MissingMemberDecl.NumberOfFieldOffsetVectorEntries; } SourceRange getSourceRange() const { return SourceRange(); } static bool classof(const Decl *D) { return D->getKind() == DeclKind::MissingMember; } }; inline bool AbstractStorageDecl::isSettable(const DeclContext *UseDC, const DeclRefExpr *base) const { if (auto vd = dyn_cast<VarDecl>(this)) return vd->isSettable(UseDC, base); auto sd = cast<SubscriptDecl>(this); return sd->supportsMutation(); } inline void AbstractStorageDecl::overwriteSetterAccess(AccessLevel accessLevel) { Accessors.setInt(accessLevel); if (auto setter = getAccessor(AccessorKind::Set)) setter->overwriteAccess(accessLevel); if (auto modify = getAccessor(AccessorKind::Modify)) modify->overwriteAccess(accessLevel); if (auto mutableAddressor = getAccessor(AccessorKind::MutableAddress)) mutableAddressor->overwriteAccess(accessLevel); } /// Constructors and destructors always have a 'self' parameter, /// which is stored in an instance member. Functions only have a /// 'self' if they are declared inside of a nominal type or extension, /// in which case we tail-allocate storage for it. inline ParamDecl **AbstractFunctionDecl::getImplicitSelfDeclStorage() { switch (getKind()) { default: llvm_unreachable("Unknown AbstractFunctionDecl!"); case DeclKind::Constructor: return cast<ConstructorDecl>(this)->getImplicitSelfDeclStorage(); case DeclKind::Destructor: return cast<DestructorDecl>(this)->getImplicitSelfDeclStorage(); case DeclKind::Func: case DeclKind::Accessor: return cast<FuncDecl>(this)->getImplicitSelfDeclStorage(); } } inline ParamDecl **FuncDecl::getImplicitSelfDeclStorage() { if (!hasImplicitSelfDecl()) return nullptr; if (!isa<AccessorDecl>(this)) { assert(getKind() == DeclKind::Func && "no new kinds of functions"); return reinterpret_cast<ParamDecl **>(this+1); } return reinterpret_cast<ParamDecl **>(static_cast<AccessorDecl*>(this)+1); } inline DeclIterator &DeclIterator::operator++() { Current = Current->NextDecl; return *this; } inline bool AbstractFunctionDecl::hasForcedStaticDispatch() const { if (auto func = dyn_cast<FuncDecl>(this)) return func->hasForcedStaticDispatch(); return false; } inline bool ValueDecl::isStatic() const { // Currently, only storage and function decls can be static/class. if (auto storage = dyn_cast<AbstractStorageDecl>(this)) return storage->isStatic(); if (auto func = dyn_cast<FuncDecl>(this)) return func->isStatic(); return false; } inline bool ValueDecl::isImportAsMember() const { if (auto func = dyn_cast<AbstractFunctionDecl>(this)) return func->isImportAsMember(); return false; } inline bool ValueDecl::hasCurriedSelf() const { if (auto *afd = dyn_cast<AbstractFunctionDecl>(this)) return afd->hasImplicitSelfDecl(); if (isa<EnumElementDecl>(this)) return true; return false; } inline bool ValueDecl::hasParameterList() const { if (auto *eed = dyn_cast<EnumElementDecl>(this)) return eed->hasAssociatedValues(); return isa<AbstractFunctionDecl>(this) || isa<SubscriptDecl>(this); } inline unsigned ValueDecl::getNumCurryLevels() const { unsigned curryLevels = 0; if (hasParameterList()) curryLevels++; if (hasCurriedSelf()) curryLevels++; return curryLevels; } inline bool Decl::isPotentiallyOverridable() const { if (isa<VarDecl>(this) || isa<SubscriptDecl>(this) || isa<FuncDecl>(this) || isa<DestructorDecl>(this)) { auto classDecl = getDeclContext()->getSelfClassDecl(); return classDecl && !classDecl->isActor(); } else { return false; } } inline GenericParamKey::GenericParamKey(const GenericTypeParamDecl *d) : Depth(d->getDepth()), Index(d->getIndex()) { } inline const GenericContext *Decl::getAsGenericContext() const { switch (getKind()) { default: return nullptr; #define DECL(Id, Parent) // See previous line #define GENERIC_DECL(Id, Parent) \ case DeclKind::Id: \ return static_cast<const Id##Decl*>(this); #include "swift/AST/DeclNodes.def" } } inline bool DeclContext::classof(const Decl *D) { switch (D->getKind()) { // default: return false; #define DECL(ID, PARENT) // See previous line #define CONTEXT_DECL(ID, PARENT) \ case DeclKind::ID: return true; #include "swift/AST/DeclNodes.def" } } inline DeclContext *DeclContext::castDeclToDeclContext(const Decl *D) { // XXX -- ModuleDecl is not defined in Decl.h, but because DeclContexts // preface decls in memory, any DeclContext type will due. const DeclContext *DC = static_cast<const ExtensionDecl*>(D); switch (D->getKind()) { default: llvm_unreachable("Not a DeclContext"); #define DECL(ID, PARENT) // See previous line #define CONTEXT_DECL(ID, PARENT) \ case DeclKind::ID: #include "swift/AST/DeclNodes.def" return const_cast<DeclContext *>(DC); } } inline EnumElementDecl *EnumDecl::getUniqueElement(bool hasValue) const { EnumElementDecl *result = nullptr; bool found = false; for (auto elt : getAllElements()) { if (elt->hasAssociatedValues() == hasValue) { if (found) return nullptr; found = true; result = elt; } } return result; } /// Retrieve the parameter list for a given declaration, or nullputr if there /// is none. ParameterList *getParameterList(ValueDecl *source); /// Retrieve parameter declaration from the given source at given index, or /// nullptr if the source does not have a parameter list. const ParamDecl *getParameterAt(const ValueDecl *source, unsigned index); void simple_display(llvm::raw_ostream &out, OptionSet<NominalTypeDecl::LookupDirectFlags> options); /// Display Decl subclasses. void simple_display(llvm::raw_ostream &out, const Decl *decl); /// Display ValueDecl subclasses. void simple_display(llvm::raw_ostream &out, const ValueDecl *decl); /// Display ExtensionDecls. inline void simple_display(llvm::raw_ostream &out, const ExtensionDecl *decl) { simple_display(out, static_cast<const Decl *>(decl)); } /// Display NominalTypeDecls. inline void simple_display(llvm::raw_ostream &out, const NominalTypeDecl *decl) { simple_display(out, static_cast<const Decl *>(decl)); } inline void simple_display(llvm::raw_ostream &out, const AssociatedTypeDecl *decl) { simple_display(out, static_cast<const Decl *>(decl)); } /// Display GenericContext. /// /// The template keeps this sorted down in the overload set relative to the /// more concrete overloads with Decl pointers thereby breaking a potential ambiguity. template <typename T> inline typename std::enable_if<std::is_same<T, GenericContext>::value>::type simple_display(llvm::raw_ostream &out, const T *GC) { simple_display(out, GC->getAsDecl()); } /// Display GenericParamList. void simple_display(llvm::raw_ostream &out, const GenericParamList *GPL); /// Extract the source location from the given declaration. SourceLoc extractNearestSourceLoc(const Decl *decl); /// Extract the source location from the given declaration. inline SourceLoc extractNearestSourceLoc(const ExtensionDecl *ext) { return extractNearestSourceLoc(static_cast<const Decl *>(ext)); } /// Extract the source location from the given declaration. inline SourceLoc extractNearestSourceLoc(const GenericTypeDecl *type) { return extractNearestSourceLoc(static_cast<const Decl *>(type)); } /// Extract the source location from the given declaration. inline SourceLoc extractNearestSourceLoc(const NominalTypeDecl *type) { return extractNearestSourceLoc(static_cast<const Decl *>(type)); } /// Extract the source location from the given declaration. inline SourceLoc extractNearestSourceLoc(const AbstractFunctionDecl *func) { return extractNearestSourceLoc(static_cast<const Decl *>(func)); } } // end namespace swift #endif
{ "content_hash": "0172dcd139bf79076a55dcbfab9cff30", "timestamp": "", "source": "github", "line_count": 7714, "max_line_length": 102, "avg_line_length": 35.43725693544205, "alnum_prop": 0.7057319388505394, "repo_name": "parkera/swift", "id": "5efc1d100bbba2857290e9adc195fe6846a09889", "size": "273367", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/swift/AST/Decl.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "12337" }, { "name": "C", "bytes": "228398" }, { "name": "C++", "bytes": "33022469" }, { "name": "CMake", "bytes": "524486" }, { "name": "D", "bytes": "1107" }, { "name": "DTrace", "bytes": "2438" }, { "name": "Emacs Lisp", "bytes": "57265" }, { "name": "LLVM", "bytes": "70793" }, { "name": "MATLAB", "bytes": "2576" }, { "name": "Makefile", "bytes": "1841" }, { "name": "Objective-C", "bytes": "420134" }, { "name": "Objective-C++", "bytes": "252651" }, { "name": "Perl", "bytes": "2211" }, { "name": "Python", "bytes": "1557207" }, { "name": "Roff", "bytes": "3495" }, { "name": "Ruby", "bytes": "2091" }, { "name": "Shell", "bytes": "229048" }, { "name": "Swift", "bytes": "28985279" }, { "name": "Vim script", "bytes": "16761" }, { "name": "sed", "bytes": "1050" } ], "symlink_target": "" }
use super::bitmask::BitMask; use super::EMPTY; use core::{mem, ptr}; // Use the native word size as the group size. Using a 64-bit group size on // a 32-bit architecture will just end up being more expensive because // shifts and multiplies will need to be emulated. #[cfg(any( target_pointer_width = "64", target_arch = "aarch64", target_arch = "x86_64", target_arch = "wasm32", ))] type GroupWord = u64; #[cfg(all( any(target_pointer_width = "32", target_pointer_width = "16"), not(target_arch = "aarch64"), not(target_arch = "x86_64"), not(target_arch = "wasm32"), ))] type GroupWord = u32; pub type BitMaskWord = GroupWord; pub const BITMASK_STRIDE: usize = 8; // We only care about the highest bit of each byte for the mask. #[allow(clippy::cast_possible_truncation, clippy::unnecessary_cast)] pub const BITMASK_MASK: BitMaskWord = 0x8080_8080_8080_8080_u64 as GroupWord; /// Helper function to replicate a byte across a `GroupWord`. #[inline] fn repeat(byte: u8) -> GroupWord { GroupWord::from_ne_bytes([byte; Group::WIDTH]) } /// Abstraction over a group of control bytes which can be scanned in /// parallel. /// /// This implementation uses a word-sized integer. #[derive(Copy, Clone)] pub struct Group(GroupWord); // We perform all operations in the native endianness, and convert to // little-endian just before creating a BitMask. The can potentially // enable the compiler to eliminate unnecessary byte swaps if we are // only checking whether a BitMask is empty. #[allow(clippy::use_self)] impl Group { /// Number of bytes in the group. pub const WIDTH: usize = mem::size_of::<Self>(); /// Returns a full group of empty bytes, suitable for use as the initial /// value for an empty hash table. /// /// This is guaranteed to be aligned to the group size. #[inline] pub const fn static_empty() -> &'static [u8; Group::WIDTH] { #[repr(C)] struct AlignedBytes { _align: [Group; 0], bytes: [u8; Group::WIDTH], } const ALIGNED_BYTES: AlignedBytes = AlignedBytes { _align: [], bytes: [EMPTY; Group::WIDTH], }; &ALIGNED_BYTES.bytes } /// Loads a group of bytes starting at the given address. #[inline] #[allow(clippy::cast_ptr_alignment)] // unaligned load pub unsafe fn load(ptr: *const u8) -> Self { Group(ptr::read_unaligned(ptr.cast())) } /// Loads a group of bytes starting at the given address, which must be /// aligned to `mem::align_of::<Group>()`. #[inline] #[allow(clippy::cast_ptr_alignment)] pub unsafe fn load_aligned(ptr: *const u8) -> Self { // FIXME: use align_offset once it stabilizes debug_assert_eq!(ptr as usize & (mem::align_of::<Self>() - 1), 0); Group(ptr::read(ptr.cast())) } /// Stores the group of bytes to the given address, which must be /// aligned to `mem::align_of::<Group>()`. #[inline] #[allow(clippy::cast_ptr_alignment)] pub unsafe fn store_aligned(self, ptr: *mut u8) { // FIXME: use align_offset once it stabilizes debug_assert_eq!(ptr as usize & (mem::align_of::<Self>() - 1), 0); ptr::write(ptr.cast(), self.0); } /// Returns a `BitMask` indicating all bytes in the group which *may* /// have the given value. /// /// This function may return a false positive in certain cases where /// the byte in the group differs from the searched value only in its /// lowest bit. This is fine because: /// - This never happens for `EMPTY` and `DELETED`, only full entries. /// - The check for key equality will catch these. /// - This only happens if there is at least 1 true match. /// - The chance of this happening is very low (< 1% chance per byte). #[inline] pub fn match_byte(self, byte: u8) -> BitMask { // This algorithm is derived from // https://graphics.stanford.edu/~seander/bithacks.html##ValueInWord let cmp = self.0 ^ repeat(byte); BitMask((cmp.wrapping_sub(repeat(0x01)) & !cmp & repeat(0x80)).to_le()) } /// Returns a `BitMask` indicating all bytes in the group which are /// `EMPTY`. #[inline] pub fn match_empty(self) -> BitMask { // If the high bit is set, then the byte must be either: // 1111_1111 (EMPTY) or 1000_0000 (DELETED). // So we can just check if the top two bits are 1 by ANDing them. BitMask((self.0 & (self.0 << 1) & repeat(0x80)).to_le()) } /// Returns a `BitMask` indicating all bytes in the group which are /// `EMPTY` or `DELETED`. #[inline] pub fn match_empty_or_deleted(self) -> BitMask { // A byte is EMPTY or DELETED iff the high bit is set BitMask((self.0 & repeat(0x80)).to_le()) } /// Returns a `BitMask` indicating all bytes in the group which are full. #[inline] pub fn match_full(self) -> BitMask { self.match_empty_or_deleted().invert() } /// Performs the following transformation on all bytes in the group: /// - `EMPTY => EMPTY` /// - `DELETED => EMPTY` /// - `FULL => DELETED` #[inline] pub fn convert_special_to_empty_and_full_to_deleted(self) -> Self { // Map high_bit = 1 (EMPTY or DELETED) to 1111_1111 // and high_bit = 0 (FULL) to 1000_0000 // // Here's this logic expanded to concrete values: // let full = 1000_0000 (true) or 0000_0000 (false) // !1000_0000 + 1 = 0111_1111 + 1 = 1000_0000 (no carry) // !0000_0000 + 0 = 1111_1111 + 0 = 1111_1111 (no carry) let full = !self.0 & repeat(0x80); Group(!full + (full >> 7)) } }
{ "content_hash": "1281120065cdd7ee7f711b6361bcff69", "timestamp": "", "source": "github", "line_count": 154, "max_line_length": 79, "avg_line_length": 37.201298701298704, "alnum_prop": 0.6173852330249607, "repo_name": "rust-lang/hashbrown", "id": "52955a45b65526a4dc8148afe1580aee7dde49bc", "size": "5729", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/raw/generic.rs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Rust", "bytes": "568165" }, { "name": "Shell", "bytes": "2337" } ], "symlink_target": "" }
package org.wso2.carbon.caching.impl; import org.testng.annotations.Test; import org.wso2.carbon.caching.impl.eviction.EvictionUtil; import org.wso2.carbon.caching.impl.eviction.LeastRecentlyUsedEvictionAlgorithm; import org.wso2.carbon.caching.impl.eviction.MostRecentlyUsedEvictionAlgorithm; import org.wso2.carbon.caching.impl.eviction.RandomEvictionAlgorithm; import org.wso2.carbon.context.PrivilegedCarbonContext; import javax.cache.Cache; import javax.cache.CacheConfiguration; import javax.cache.CacheManager; import javax.cache.Caching; import java.io.File; import java.util.HashSet; import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; /** * TODO: class description */ public class CachingTestCase { private Cache<String, Integer> cache; private String key = "testKey"; public CachingTestCase() { System.setProperty("carbon.home", new File(".").getAbsolutePath()); String cacheName = "sampleCache"; // CacheManager cacheManager = Caching.getCacheManager(); // same as Caching.getCacheManagerFactory().getCacheManager("__default__"); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain("foo.com"); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(1); CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager("test"); cache = cacheManager.getCache(cacheName); } @Test(groups = {"org.wso2.carbon.clustering.hazelcast.jsr107"}, description = "") public void checkNonExistentItem() throws Exception { assertNull(cache.get(key)); } @Test(groups = {"org.wso2.carbon.clustering.hazelcast.jsr107"}, dependsOnMethods = "checkNonExistentItem", description = "") public void checkPut() throws Exception { Integer sampleValue = 1245; cache.put(key, sampleValue); assertEquals(cache.get(key), sampleValue); } @Test(groups = {"org.wso2.carbon.clustering.hazelcast.jsr107"}, description = "") public void checkMultipleCacheManagers() { String cacheName = "sampleCache"; CacheManager cacheManager1 = Caching.getCacheManagerFactory().getCacheManager("test-1"); Cache<String, Integer> cache1 = cacheManager1.getCache(cacheName); int value1 = 9876; cache1.put(key, value1); CacheManager cacheManager2 = Caching.getCacheManagerFactory().getCacheManager("test-2"); Cache<String, String> cache2 = cacheManager2.getCache(cacheName); String value2 = "Afkham Azeez"; cache2.put(key, value2); assertEquals(cache1.get(key).intValue(), value1); assertEquals(cache2.get(key), value2); assertNotEquals(cache1.get(key), value2); assertNotEquals(cache2.get(key), value1); } @Test(groups = {"org.wso2.carbon.clustering.hazelcast.jsr107"}, description = "") public void checkMultipleCaches() { CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager("test-1"); Cache<String, Integer> cache1 = cacheManager.getCache("sampleCache1"); Cache<String, String> cache2 = cacheManager.getCache("sampleCache2"); int value1 = 9876; String value2 = "Afkham Azeez"; cache1.put(key, value1); cache2.put(key, value2); assertEquals(cache1.get(key).intValue(), value1); assertEquals(cache2.get(key), value2); assertNotEquals(cache1.get(key), value2); assertNotEquals(cache2.get(key), value1); } @Test(groups = {"org.wso2.carbon.clustering.hazelcast.jsr107"}, description = "") public void checkWithCustomCacheConfiguration() { CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager("test"); String cacheName = "cacheXXX"; cache = cacheManager.<String, Integer>createCacheBuilder(cacheName). setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS, 10)). setStoreByValue(false).build(); int value = 9876; cache.put(key, value); assertEquals(cache.get(key).intValue(), value); } @Test(groups = {"org.wso2.carbon.clustering.hazelcast.jsr107"}, expectedExceptions = {javax.cache.CacheException.class}, dependsOnMethods = "checkWithCustomCacheConfiguration") public void testCreateExistingCache() { CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager("test"); String cacheName = "cacheXXX"; cache = cacheManager.<String, Integer>createCacheBuilder(cacheName). setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS, 10)). setStoreByValue(false).build(); } @Test(groups = {"org.wso2.carbon.clustering.hazelcast.jsr107"}, description = "") public void testSerializableObject() { String name = "Afkham Azeez"; String address = "301/2A, Dehiwela Road"; Long id = (long) 789; SerializableTestObject obj = new SerializableTestObject(name, address, id); CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager("test"); String cacheName = "sampleCacheX"; Cache<Long, SerializableTestObject> cache = cacheManager.getCache(cacheName); cache.put(id, obj); Cache<Long, SerializableTestObject> cache2 = cacheManager.getCache(cacheName); assertEquals(cache2.get(id).getId(), id); assertEquals(cache2.get(id).getAddress(), address); assertEquals(cache2.get(id).getName(), name); } @Test(groups = {"org.wso2.carbon.clustering.hazelcast.jsr107"}, dependsOnMethods = "testSerializableObject", description = "") public void testRemoveObjectFromCache() { Long id = (long) 789; String cacheName = "sampleCacheX"; CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager("test"); Cache<Long, SerializableTestObject> cache = cacheManager.getCache(cacheName); assertNotNull(cache.get(id)); Cache<Long, SerializableTestObject> cache2 = cacheManager.getCache(cacheName); cache2.remove(id); assertNull(cache.get(id)); } @Test(groups = {"org.wso2.carbon.clustering.hazelcast.jsr107"}, description = "") public void testCacheIterator() { Long id = (long) 789; String cacheName = "sampleCacheABC"; CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager("test"); Cache<Long, Long> cache = cacheManager.getCache(cacheName); cache.put((long) 123, id); cache.put((long) 456, id); cache.put((long) 789, id); cache.put((long) 12, id); int entries = 0; for (Cache.Entry<Long, Long> entry : cache) { assertNotNull(entry); entries++; } assertEquals(entries, 4); } @Test(groups = {"org.wso2.carbon.clustering.hazelcast.jsr107"}, description = "") public void testCacheLoaderLoadAll() { CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager("test"); String cacheName = "cacheYYY"; Cache<String, String> cache = cacheManager.<String, String>createCacheBuilder(cacheName). setCacheLoader(new TestCacheLoader<String, String>()).build(); HashSet<String> hashSet = new HashSet<String>(); for (int i = 1; i < 6; i++) { hashSet.add("key" + i); } Future<Map<String, ? extends String>> future = cache.loadAll(hashSet); while (!future.isDone()) { try { Thread.sleep(1); } catch (InterruptedException ignored) { } } for (int i = 1; i < 6; i++) { assertNotNull(cache.get("key" + i)); } } @Test(groups = {"org.wso2.carbon.clustering.hazelcast.jsr107"}, description = "") public void testCacheLoaderLoad() { CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager("test"); String cacheName = "testCacheLoaderLoad-ZZZ"; Cache<String, String> cache = cacheManager.<String, String>createCacheBuilder(cacheName). setCacheLoader(new TestCacheLoader<String, String>()).build(); Future<String> future = cache.load("key1"); while (!future.isDone()) { try { Thread.sleep(1); } catch (InterruptedException ignored) { } } assertNotNull(cache.get("key1")); } @Test(groups = {"org.wso2.carbon.clustering.hazelcast.jsr107"}, description = "") public void testCacheExpiry() { CacheManager cacheManager = Caching.getCacheManagerFactory().getCacheManager("testCacheExpiry-manager"); String cacheName = "testCacheExpiry"; Cache<String, Integer> cache = cacheManager.<String, Integer>createCacheBuilder(cacheName). setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS, 1)). setStoreByValue(false).build(); int value = 9876; cache.put(key, value); assertEquals(cache.get(key).intValue(), value); try { Thread.sleep(2000); } catch (InterruptedException ignored) { } ((CacheImpl) cache).runCacheExpiry(); assertNull(cache.get(key)); } }
{ "content_hash": "a9a72ad8d1fb5e24fe09c4eb939cf911", "timestamp": "", "source": "github", "line_count": 246, "max_line_length": 141, "avg_line_length": 40.08130081300813, "alnum_prop": 0.6558823529411765, "repo_name": "maheshika/carbon4-kernel", "id": "a1b3bab3dfbd6b0c059dab7ff6853b8a86cf7eb4", "size": "10527", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/javax.cache/src/test/java/org/wso2/carbon/caching/impl/CachingTestCase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "332285" }, { "name": "Java", "bytes": "8868082" }, { "name": "JavaScript", "bytes": "1359280" }, { "name": "PHP", "bytes": "15326" }, { "name": "Shell", "bytes": "63102" } ], "symlink_target": "" }
layout: post title: "¡Nuevo PC!" subtitle: "Características de mi nuevo PC montado a piezas" description: Características de mi nuevo PC montado a piezas date: 2015-08-20 12:00:00 sitemap: lastmod: 2019-03-02 tag: [informatica,geek] author: "@R12Leal" header-img: "img/post/pc.jpg" permalink: /:title/ comments: true --- <h2 class="section-heading">Introducción</h2> <hr /> <p>Tras el "fallecimiento" de la placa base, de mi último ordenador, decidí renovar por completo mi sistema informático con un pc que está preparado para las tareas más básicas de un usuario normal y a la vez puede usarse para algunos de los juegos más populares de estos tiempos.</p> <hr /> <h2 class="section-heading">Características</h2> <hr /> <ul class="ulposts"> <li><strong>Placa base</strong>: MSI H81M-P33 (Intel Socket 1150, SDDR3, Micro ATX, USB 3.0, VGA + DVI, GBLAN, SATA3).</li> <li><strong>Procesador</strong>: Intel 1150 G1840 - Procesador 2 x 2.8 GHz/2 MB/Box.</li> <li><strong>Gráfica</strong>: integrada.</li> <li><strong>Tarjeta de red</strong>: integrada.</li> <li><strong>Tarjeta de sonido</strong>: integrada.</li> <li><strong>Memoria</strong>: Kingston KVR13N9S8/4 - Memoria RAM de 4 GB (PC3-10600, 240 pines, CL9).</li> <li><strong>Caja</strong>: B-Move BMKAIROS - Caja semitorre, 500 W, Negro.</li> <li><strong>Fuente</strong>: Viene incluida con la caja.</li> <li><strong>Disco duro</strong>: Toshiba DT01ACA050 500GB 7200 SATA 3.</li> <li><strong>Unidad CD/DVD</strong>: Asus DRW-24F1MT Grabadora DVD 24X Negra.</li> <li><strong>Precio</strong>: pueden variar dependiendo del portal donde realices las compras, entre 180 y 200 euros.</li> </ul> <hr /> <h2 class="section-heading">Explicación</h2> <hr /> <p>Es una "setUp" muy barata para ofimática, Youtube, ver películas, juegos poco exigentes, series o televisión online, emuladores y trastear con programas como por ejemplo Photoshop. No es una configuración que se haya diseñado principalmente para el gaming, pero la verdad es que es un PC con el que se pueden jugar a algunos juegos. Es capaz de mover juegos con los gráficos aceptables, y de forma muy decente, como LoL (League of Legends), Counter Strike (CSGO), Minecraft, WoW (World of Warcraft) y otros actuales que no son muy exigentes.</p> <hr /> <h2 class="section-heading">Ampliación para el futuro</h2> <hr /> <p>Es una máquina con un gran potencial de ampliación. Con solo añadirle una gráfica barata podremos jugar a prácticamente cualquier juego exigente con gráficos medios. Para gráficas muy superiores (+ 160 €) ya sería conveniente cambiar el procesador por un i3 o un i5 y también sería necesario cambiar la fuente de alimentación para que soporte gráficas de gamas más altas.</p> <p>Otra opción interesante para evitar micro parones (Stuttering) en algunos principios de carga de algunos juegos, y ganar fluidez, es añadirle otro módulo de RAM. Con esto ganamos más depósito y haríamos que la gráfica integrada funcionara mejor gracias al uso del doble canal de memoria, lo recomendado sería comprar el módulo del mismo tipo, misma marca y mismas características para evitar incompatibilidades. En el futuro podemos ponerle un i5 o un i7 dependiendo del uso al que va destinado.</p> <hr /> <h2 class="section-heading">Conclusión</h2> <hr /> <p>Si no tienes mucho presupuesto esta puede ser una opción idónea para empezar. Si deseas aprender y conocer otras configuraciones puedes visitar <a href="http://forohardware.com" title="¡Visita Foro Hardware!" target="_blank">forohardware.com</a>, Salu2!</p>
{ "content_hash": "19918249bb6a1f622c464142369960fa", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 548, "avg_line_length": 80.17777777777778, "alnum_prop": 0.7408536585365854, "repo_name": "R12Leal/R12Leal.github.io", "id": "4d3f6dccbf6e52fb6ec6791cd6c8b4f2da2278ec", "size": "3662", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2015-08-20-nuevo-pc.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "214728" }, { "name": "HTML", "bytes": "43161" }, { "name": "JavaScript", "bytes": "146587" }, { "name": "Less", "bytes": "8020" }, { "name": "PHP", "bytes": "2961" }, { "name": "SCSS", "bytes": "29741" } ], "symlink_target": "" }
#ifndef _DECAF_NET_SOCKETEXCEPTION_H_ #define _DECAF_NET_SOCKETEXCEPTION_H_ #include <decaf/io/IOException.h> namespace decaf { namespace net { /** * Exception for errors when manipulating sockets. */ class DECAF_API SocketException : public io::IOException { public: SocketException(); SocketException(const lang::Exception& ex); SocketException(const SocketException& ex); /** * Constructor - Initializes the file name and line number where * this message occurred. Sets the message to report, using an * optional list of arguments to parse into the message * * @param file The file name where exception occurs * @param lineNumber The line number where the exception occurred. * @param cause The exception that was the cause for this one to be thrown. * @param msg The message to report * @param ... list of primitives that are formatted into the message */ SocketException(const char* file, const int lineNumber, const std::exception* cause, const char* msg, ...); /** * Constructor * * @param cause Pointer to the exception that caused this one to * be thrown, the object is cloned caller retains ownership. */ SocketException(const std::exception* cause); /** * Constructor - Initializes the file name and line number where * this message occurred. Sets the message to report, using an * optional list of arguments to parse into the message * * @param file The file name where exception occurs * @param lineNumber The line number where the exception occurred. * @param msg The message to report * @param ... list of primitives that are formatted into the message */ SocketException(const char* file, const int lineNumber, const char* msg, ...); /** * Clones this exception. This is useful for cases where you need * to preserve the type of the original exception as well as the message. * All subclasses should override. * * @return a new Exception instance that is a copy of this Exception object. */ virtual SocketException* clone() const { return new SocketException(*this); } virtual ~SocketException() throw(); }; }} #endif // _DECAF_NET_SOCKETEXCEPTION_H_
{ "content_hash": "f7aedfb25295e72d2778e69c5cd175db", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 115, "avg_line_length": 34.68055555555556, "alnum_prop": 0.6283540248297957, "repo_name": "apache/activemq-cpp", "id": "a2fed9c9f60250fa7adba9cb23f3422786deefac", "size": "3298", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "activemq-cpp/src/main/decaf/net/SocketException.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "447207" }, { "name": "C++", "bytes": "12024283" }, { "name": "Java", "bytes": "251150" }, { "name": "M4", "bytes": "72135" }, { "name": "Makefile", "bytes": "114773" }, { "name": "Objective-C", "bytes": "14815" }, { "name": "Shell", "bytes": "7934" } ], "symlink_target": "" }
module CCO.Feedback ( -- * Messages Message (Log, Warning, Error) , isError -- :: Message -> Bool , fromMessage -- :: Message -> Doc -- * The Feedback monad , Feedback -- abstract, instances: Functor, Monad , trace -- :: Int -> String -> Feedback () , trace_ -- :: String -> Feedback () , warn -- :: Int -> String -> Feedback () , warn_ -- :: String -> Feedback () , errorMessage -- :: Doc -> Feedback () , message -- :: Message -> Feedback () , messages -- :: [Message] -> Feedback () , wError -- :: Feedback a -> Feedback a , succeeding -- :: Feedback a -> Bool , failing -- :: Feedback a -> Bool , runFeedback -- :: Feedback a -> Handle -> IO (Maybe a) ) where import CCO.Feedback.Message import CCO.Printing (Doc, text) import System.IO (Handle) import Control.Monad import Control.Applicative ------------------------------------------------------------------------------- -- The Feedback monad ------------------------------------------------------------------------------- -- | The @Feedback@ monad. -- Keeps track of 'Message's, failing if an 'Error' message is encountered. data Feedback a = Succeed [Message] a | Fail [Message] instance Functor Feedback where fmap f (Succeed msgs x) = Succeed msgs (f x) fmap _ (Fail msgs) = Fail msgs instance Monad Feedback where return x = Succeed [] x Succeed msgs x >>= f = case f x of Succeed msgs' y -> Succeed (msgs ++ msgs') y Fail msgs' -> Fail (msgs ++ msgs') Fail msgs >>= _ = Fail msgs fail msg = Fail [Error (text msg)] instance Applicative Feedback where pure = return (<*>) = ap -- | Issues a list of 'Message's. -- Fails if the list contains an 'Error' message. messages :: [Message] -> Feedback () messages msgs | any isError msgs = Fail msgs | otherwise = Succeed msgs () -- | Issues a 'Message'. -- Fails if an 'Error' message is issued. message :: Message -> Feedback () message msg = messages [msg] -- | Issues an 'Error' message. errorMessage :: Doc -> Feedback a errorMessage doc = Fail [Error doc] -- | Issues a 'Log' message at a specified verbosity level containing a -- specified text. trace :: Int -> String -> Feedback () trace v = message . Log v . text -- | Issues a 'Log' message at the default verbosity level 1 containing a -- specified text. trace_ :: String -> Feedback () trace_ = trace 1 -- | Issues a 'Warning' message at a specified severity level containing a -- specified text. warn :: Int -> String -> Feedback () warn w = message . Warning w . text -- | Issues a 'Warning' message at the default severity level 1 containing a -- specified text. warn_ :: String -> Feedback () warn_ = warn 1 -- | Turns all 'Warning' messages into 'Error' messages. wError :: Feedback a -> Feedback a wError (Fail msgs) = Fail (fatalizeWarnings msgs) wError (Succeed msgs x) = let msgs' = fatalizeWarnings msgs in if any isError msgs' then Fail msgs' else Succeed msgs' x -- | Retrieves whether a 'Feedback' computation will succeed. succeeding :: Feedback a -> Bool succeeding (Succeed _ _) = True succeeding _ = False -- | Retrieves whether a 'Feedback' computation will fail. failing :: Feedback a -> Bool failing (Fail _) = True failing _ = False -- | Runs a 'Feedback' computation at a specified verbosity and severity level, -- pretty printing messages onto a specified -- 'Handle'. runFeedback :: Feedback a -> Int -> Int -> Handle -> IO (Maybe a) runFeedback (Succeed msgs x) v w h = do let msgs' = filterMessages v w msgs putMessages h msgs' return (Just x) runFeedback (Fail msgs) v w h = do let msgs' = filterMessages v w msgs putMessages h msgs' return Nothing
{ "content_hash": "891ae46436d2208f430bab7df9d40df1", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 79, "avg_line_length": 37.00847457627118, "alnum_prop": 0.5285092741012136, "repo_name": "aochagavia/CompilerConstruction", "id": "e0a68449f3d5dc50f33a43a6b02a2738a6591f16", "size": "4814", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "tdiagrams/uu-cco/src/CCO/Feedback.hs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "2103" }, { "name": "Haskell", "bytes": "291422" }, { "name": "Logos", "bytes": "3119" }, { "name": "Makefile", "bytes": "2514" }, { "name": "Standard ML", "bytes": "986" }, { "name": "TeX", "bytes": "2797" }, { "name": "Yacc", "bytes": "4486" } ], "symlink_target": "" }
@interface ViewController : UIViewController { IBOutlet IQDropDownTextField *textFieldTextPicker; IBOutlet IQDropDownTextField *textFieldOptionalTextPicker; IBOutlet IQDropDownTextField *textFieldDatePicker; IBOutlet IQDropDownTextField *textFieldTimePicker; IBOutlet IQDropDownTextField *textFieldDateTimePicker; } @end
{ "content_hash": "62bbe9e1e4067846d1e484c644fd4416", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 62, "avg_line_length": 31.181818181818183, "alnum_prop": 0.8279883381924198, "repo_name": "fjsosa/IQDropDownTextField", "id": "a6ab2df0e12b92c6241c0b3251e22f50f12d3c20", "size": "540", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Drop Down TextField/ViewController.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "53481" }, { "name": "Ruby", "bytes": "689" } ], "symlink_target": "" }
namespace gpu { class GpuMemoryBufferFactory; class GpuMemoryBufferManagerInterface; namespace gles2 { class MailboxManager; class QueryManager; } class GPU_EXPORT GpuControlService : public GpuControl { public: GpuControlService(GpuMemoryBufferManagerInterface* gpu_memory_buffer_manager, GpuMemoryBufferFactory* gpu_memory_buffer_factory, gles2::MailboxManager* mailbox_manager, gles2::QueryManager* query_manager); virtual ~GpuControlService(); // Overridden from GpuControl: virtual bool SupportsGpuMemoryBuffer() OVERRIDE; virtual gfx::GpuMemoryBuffer* CreateGpuMemoryBuffer( size_t width, size_t height, unsigned internalformat, int32* id) OVERRIDE; virtual void DestroyGpuMemoryBuffer(int32 id) OVERRIDE; virtual bool GenerateMailboxNames(unsigned num, std::vector<gpu::Mailbox>* names) OVERRIDE; virtual uint32 InsertSyncPoint() OVERRIDE; virtual void SignalSyncPoint(uint32 sync_point, const base::Closure& callback) OVERRIDE; virtual void SignalQuery(uint32 query, const base::Closure& callback) OVERRIDE; virtual void SendManagedMemoryStats(const ManagedMemoryStats& stats) OVERRIDE; // Register an existing gpu memory buffer and get an ID that can be used // to identify it in the command buffer. bool RegisterGpuMemoryBuffer(int32 id, gfx::GpuMemoryBufferHandle buffer, size_t width, size_t height, unsigned internalformat); private: GpuMemoryBufferManagerInterface* gpu_memory_buffer_manager_; GpuMemoryBufferFactory* gpu_memory_buffer_factory_; gles2::MailboxManager* mailbox_manager_; gles2::QueryManager* query_manager_; typedef std::map<int32, linked_ptr<gfx::GpuMemoryBuffer> > GpuMemoryBufferMap; GpuMemoryBufferMap gpu_memory_buffers_; DISALLOW_COPY_AND_ASSIGN(GpuControlService); }; } // namespace gpu #endif // GPU_COMMAND_BUFFER_SERVICE_GPU_CONTROL_SERVICE_H_
{ "content_hash": "4cd73d4671c720abbe0d1e19a2977eb2", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 80, "avg_line_length": 37.01724137931034, "alnum_prop": 0.6823474615742897, "repo_name": "cvsuser-chromium/chromium", "id": "b9e7474117a4ce79eb4137f5e89dc539bf0ffe11", "size": "2572", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gpu/command_buffer/service/gpu_control_service.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "AppleScript", "bytes": "6973" }, { "name": "Assembly", "bytes": "36421" }, { "name": "C", "bytes": "6924841" }, { "name": "C++", "bytes": "179649999" }, { "name": "CSS", "bytes": "812951" }, { "name": "Java", "bytes": "3768838" }, { "name": "JavaScript", "bytes": "8338074" }, { "name": "Makefile", "bytes": "52980" }, { "name": "Objective-C", "bytes": "819293" }, { "name": "Objective-C++", "bytes": "6453781" }, { "name": "PHP", "bytes": "61320" }, { "name": "Perl", "bytes": "17897" }, { "name": "Python", "bytes": "5640877" }, { "name": "Rebol", "bytes": "262" }, { "name": "Shell", "bytes": "648699" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "15926" } ], "symlink_target": "" }
import assert from "assert" import { ArrayRecord, defineArrayRecord } from "../../src/index" import { thrownMessage } from "../lib/util" describe("defineArrayRecord:", () => { describe("ArrayRecord with 'uint8' and 4", () => { const TestRecord = defineArrayRecord("uint8", 4) let buffer: Buffer let record: ArrayRecord<number> beforeEach(() => { buffer = Buffer.from([0x01, 0x02, 0x03, 0x04, 0x05]) record = TestRecord.view(buffer) }) // // Basic // it("should have length property", () => { assert.strictEqual(record.length, 4) }) it("should read the 1st..4th bytes", () => { assert.strictEqual(record[0], 1) assert.strictEqual(record[1], 2) assert.strictEqual(record[2], 3) assert.strictEqual(record[3], 4) assert.strictEqual(buffer[0], 0x01) assert.strictEqual(buffer[1], 0x02) assert.strictEqual(buffer[2], 0x03) assert.strictEqual(buffer[3], 0x04) assert.strictEqual(buffer[4], 0x05) }) it("should write the 1st..4th bytes", () => { record[0] = 135 record[1] = 101 record[2] = 67 record[3] = 33 assert.strictEqual(record[0], 135) assert.strictEqual(record[1], 101) assert.strictEqual(record[2], 67) assert.strictEqual(record[3], 33) assert.strictEqual(buffer[0], 0x87) assert.strictEqual(buffer[1], 0x65) assert.strictEqual(buffer[2], 0x43) assert.strictEqual(buffer[3], 0x21) assert.strictEqual(buffer[4], 0x05) }) describe("with offset 1", () => { beforeEach(() => { record = TestRecord.view(buffer, 1) }) it("should have length property", () => { assert.strictEqual(record.length, 4) }) it("should read the 2nd..5th bytes", () => { assert.strictEqual(record[0], 2) assert.strictEqual(record[1], 3) assert.strictEqual(record[2], 4) assert.strictEqual(record[3], 5) assert.strictEqual(buffer[0], 0x01) assert.strictEqual(buffer[1], 0x02) assert.strictEqual(buffer[2], 0x03) assert.strictEqual(buffer[3], 0x04) assert.strictEqual(buffer[4], 0x05) }) it("should write the 2nd..5th bytes", () => { record[0] = 135 record[1] = 101 record[2] = 67 record[3] = 33 assert.strictEqual(record[0], 135) assert.strictEqual(record[1], 101) assert.strictEqual(record[2], 67) assert.strictEqual(record[3], 33) assert.strictEqual(buffer[0], 0x01) assert.strictEqual(buffer[1], 0x87) assert.strictEqual(buffer[2], 0x65) assert.strictEqual(buffer[3], 0x43) assert.strictEqual(buffer[4], 0x21) }) }) // // Meta Informations // it("should have bitLength 32", () => { assert.strictEqual(TestRecord.bitLength, 32) }) it("should have byteLength 4", () => { assert.strictEqual(TestRecord.byteLength, 4) }) it("should have keys [0,1,2,3]", () => { assert.deepStrictEqual(Array.from(record.keys()), [0, 1, 2, 3]) }) it("should have values [1,2,3,4]", () => { assert.deepStrictEqual(Array.from(record.values()), [1, 2, 3, 4]) }) it("should have entries [[0,1],[1,2],[2,3],[3,4]]", () => { assert.deepStrictEqual(Array.from(record.entries()), [ [0, 1], [1, 2], [2, 3], [3, 4], ]) }) // // Boundary Check // it("should be ok if it wrote 255", () => { for (const k of record.keys()) { record[k] = 255 assert.strictEqual(record[k], 255) } }) it("should be ok if it wrote 0", () => { for (const k of record.keys()) { record[k] = 0 assert.strictEqual(record[k], 0) } }) it("should throw if it wrote 256 (out of range)", () => { for (const k of record.keys()) { assert.strictEqual( thrownMessage(() => { record[k] = 256 }), `AssertionError: '${k}' should be within '0..255', but got 256.`, ) } }) it("should throw if it wrote -1 (out of range)", () => { for (const k of record.keys()) { assert.strictEqual( thrownMessage(() => { record[k] = -1 }), `AssertionError: '${k}' should be within '0..255', but got -1.`, ) } }) it("should throw if it creates a Record with an invalid offset (out of range)", () => { assert.strictEqual( thrownMessage(() => { TestRecord.view(buffer, -1) }), "AssertionError: 'byteOffset' should be '>=0', but got -1.", ) }) it("should throw if it creates a Record with an invalid offset (out of range)", () => { assert.strictEqual( thrownMessage(() => { TestRecord.view(buffer, 2) }), "AssertionError: 'buffer' should have enough size for the offset and size of this record (2 + 4 = 6), but got 5.", ) }) }) })
{ "content_hash": "71a69ee3656c0506e51d74f609098c89", "timestamp": "", "source": "github", "line_count": 177, "max_line_length": 130, "avg_line_length": 33.79661016949152, "alnum_prop": 0.4622199933132731, "repo_name": "mysticatea/bre", "id": "2539cbba79af9902efc9b53076f87845a2d16595", "size": "5982", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/array-record/uint8.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1331" }, { "name": "TypeScript", "bytes": "303231" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>Abell</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- <servlet> <description></description> <display-name>StartupServlet</display-name> <servlet-name>StartupServlet</servlet-name> <servlet-class>anthony.muller.celestia.abell.web.StartupServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <resource-ref> <res-ref-name>jdbc/DefaultDB</res-ref-name> <res-type>javax.sql.DataSource</res-type> </resource-ref> --> </web-app>
{ "content_hash": "b882d45c4724fed55b5b3d506e8c8e69", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 107, "avg_line_length": 36.51724137931034, "alnum_prop": 0.6997167138810199, "repo_name": "AnthonyMullerPlayground/Abell", "id": "0e23240c7479cbc81b2b313d7cda51be2ccd9ae1", "size": "1059", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Abell/WebContent/WEB-INF/web.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "138" }, { "name": "Java", "bytes": "9180" } ], "symlink_target": "" }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <html xmlns:wicket="http://wicket.apache.org/"> <body> <wicket:panel> <form wicket:id="objectlistform"> <fieldset> <legend>Permission Object Search Operations</legend> &nbsp;&nbsp; <label for="searchVal"></label> <input type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" wicket:id="search" value="search" name="search"/> <div wicket:id="ousearchmodal"></div> &nbsp;&nbsp; <span wicket:id="searchOptions"> <input type="text" wicket:id="searchVal" id="searchVal" class="formLarge" style="width: 250px"/> <input type="radio" wicket:id="objectRb" id="objectRb">Object Name</input> <input type="radio" wicket:id="ouRb" id="ouRb"><a href="#" wicket:id="ouAssignLinkLbl" id="ouAssignLinkLbl">Perm Organization</a></input> </span> </fieldset> <div wicket:id="objecttreegrid"> </div> </form> </wicket:panel> </body> </html>
{ "content_hash": "e0ac023e706f29760167c2f5f5bf65b3", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 157, "avg_line_length": 43.23255813953488, "alnum_prop": 0.657880580957504, "repo_name": "apache/directory-fortress-commander", "id": "6ded9020e601df166d6253da4b5cb29648062c16", "size": "1859", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/resources/org/apache/directory/fortress/web/panel/ObjectListPanel.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "12627" }, { "name": "HTML", "bytes": "166871" }, { "name": "Java", "bytes": "879019" } ], "symlink_target": "" }
<?php header("Location:demos"); ?>
{ "content_hash": "b43a05df0df94332cfaaca06a939c880", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 34, "avg_line_length": 34, "alnum_prop": 0.6470588235294118, "repo_name": "sasknot/mfc-api-class", "id": "e3d6f33359068c9a2c6ae804b11d351a86f61c7c", "size": "34", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "857" }, { "name": "PHP", "bytes": "8089" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using Newtonsoft.Json; using osu.Framework.Logging; using osu.Framework.Platform; using osu.Game.Database; using osu.Game.Extensions; using osu.Game.IO; using osu.Game.IO.Archives; using osu.Game.Stores; using Realms; #nullable enable namespace osu.Game.Skinning { public class SkinModelManager : RealmArchiveModelManager<SkinInfo> { private const string skin_info_file = "skininfo.json"; private readonly IStorageResourceProvider skinResources; public SkinModelManager(Storage storage, RealmAccess realm, IStorageResourceProvider skinResources) : base(storage, realm) { this.skinResources = skinResources; // can be removed 20220420. populateMissingHashes(); } public override IEnumerable<string> HandledExtensions => new[] { ".osk" }; protected override string[] HashableFileTypes => new[] { ".ini", ".json" }; protected override bool ShouldDeleteArchive(string path) => Path.GetExtension(path)?.ToLowerInvariant() == @".osk"; protected override SkinInfo CreateModel(ArchiveReader archive) => new SkinInfo { Name = archive.Name ?? @"No name" }; private const string unknown_creator_string = @"Unknown"; protected override bool HasCustomHashFunction => true; protected override void Populate(SkinInfo model, ArchiveReader? archive, Realm realm, CancellationToken cancellationToken = default) { var skinInfoFile = model.Files.SingleOrDefault(f => f.Filename == skin_info_file); if (skinInfoFile != null) { try { using (var existingStream = Files.Storage.GetStream(skinInfoFile.File.GetStoragePath())) using (var reader = new StreamReader(existingStream)) { var deserialisedSkinInfo = JsonConvert.DeserializeObject<SkinInfo>(reader.ReadToEnd()); if (deserialisedSkinInfo != null) { // for now we only care about the instantiation info. // eventually we probably want to transfer everything across. model.InstantiationInfo = deserialisedSkinInfo.InstantiationInfo; } } } catch (Exception e) { LogForModel(model, $"Error during {skin_info_file} parsing, falling back to default", e); // Not sure if we should still run the import in the case of failure here, but let's do so for now. model.InstantiationInfo = string.Empty; } } // Always rewrite instantiation info (even after parsing in from the skin json) for sanity. model.InstantiationInfo = createInstance(model).GetType().GetInvariantInstantiationInfo(); checkSkinIniMetadata(model, realm); } private void checkSkinIniMetadata(SkinInfo item, Realm realm) { var instance = createInstance(item); // This function can be run on fresh import or save. The logic here ensures a skin.ini file is in a good state for both operations. // `Skin` will parse the skin.ini and populate `Skin.Configuration` during construction above. string skinIniSourcedName = instance.Configuration.SkinInfo.Name; string skinIniSourcedCreator = instance.Configuration.SkinInfo.Creator; string archiveName = item.Name.Replace(@".osk", string.Empty, StringComparison.OrdinalIgnoreCase); bool isImport = !item.IsManaged; if (isImport) { item.Name = !string.IsNullOrEmpty(skinIniSourcedName) ? skinIniSourcedName : archiveName; item.Creator = !string.IsNullOrEmpty(skinIniSourcedCreator) ? skinIniSourcedCreator : unknown_creator_string; // For imports, we want to use the archive or folder name as part of the metadata, in addition to any existing skin.ini metadata. // In an ideal world, skin.ini would be the only source of metadata, but a lot of skin creators and users don't update it when making modifications. // In both of these cases, the expectation from the user is that the filename or folder name is displayed somewhere to identify the skin. if (archiveName != item.Name // lazer exports use this format && archiveName != item.GetDisplayString()) item.Name = @$"{item.Name} [{archiveName}]"; } // By this point, the metadata in SkinInfo will be correct. // Regardless of whether this is an import or not, let's write the skin.ini if non-existing or non-matching. // This is (weirdly) done inside ComputeHash to avoid adding a new method to handle this case. After switching to realm it can be moved into another place. if (skinIniSourcedName != item.Name) updateSkinIniMetadata(item, realm); } private void updateSkinIniMetadata(SkinInfo item, Realm realm) { string nameLine = @$"Name: {item.Name}"; string authorLine = @$"Author: {item.Creator}"; string[] newLines = { @"// The following content was automatically added by osu! during import, based on filename / folder metadata.", @"[General]", nameLine, authorLine, }; var existingFile = item.Files.SingleOrDefault(f => f.Filename.Equals(@"skin.ini", StringComparison.OrdinalIgnoreCase)); if (existingFile == null) { // In the case a skin doesn't have a skin.ini yet, let's create one. writeNewSkinIni(); } else { using (Stream stream = new MemoryStream()) { using (var sw = new StreamWriter(stream, Encoding.UTF8, 1024, true)) { using (var existingStream = Files.Storage.GetStream(existingFile.File.GetStoragePath())) using (var sr = new StreamReader(existingStream)) { string? line; while ((line = sr.ReadLine()) != null) sw.WriteLine(line); } sw.WriteLine(); foreach (string line in newLines) sw.WriteLine(line); } ReplaceFile(existingFile, stream, realm); // can be removed 20220502. if (!ensureIniWasUpdated(item)) { Logger.Log($"Skin {item}'s skin.ini had issues and has been removed. Please report this and provide the problematic skin.", LoggingTarget.Database, LogLevel.Important); var existingIni = item.Files.SingleOrDefault(f => f.Filename.Equals(@"skin.ini", StringComparison.OrdinalIgnoreCase)); if (existingIni != null) item.Files.Remove(existingIni); writeNewSkinIni(); } } } // The hash is already populated at this point in import. // As we have changed files, it needs to be recomputed. item.Hash = ComputeHash(item); void writeNewSkinIni() { using (Stream stream = new MemoryStream()) { using (var sw = new StreamWriter(stream, Encoding.UTF8, 1024, true)) { foreach (string line in newLines) sw.WriteLine(line); } AddFile(item, stream, @"skin.ini", realm); } item.Hash = ComputeHash(item); } } private bool ensureIniWasUpdated(SkinInfo item) { // This is a final consistency check to ensure that hash computation doesn't enter an infinite loop. // With other changes to the surrounding code this should never be hit, but until we are 101% sure that there // are no other cases let's avoid a hard startup crash by bailing and alerting. var instance = createInstance(item); return instance.Configuration.SkinInfo.Name == item.Name; } private void populateMissingHashes() { Realm.Run(realm => { var skinsWithoutHashes = realm.All<SkinInfo>().Where(i => !i.Protected && string.IsNullOrEmpty(i.Hash)).ToArray(); foreach (SkinInfo skin in skinsWithoutHashes) { try { realm.Write(r => skin.Hash = ComputeHash(skin)); } catch (Exception e) { Delete(skin); Logger.Error(e, $"Existing skin {skin} has been deleted during hash recomputation due to being invalid"); } } }); } private Skin createInstance(SkinInfo item) => item.CreateInstance(skinResources); public void Save(Skin skin) { skin.SkinInfo.PerformWrite(s => { // Serialise out the SkinInfo itself. string skinInfoJson = JsonConvert.SerializeObject(s, new JsonSerializerSettings { Formatting = Formatting.Indented }); using (var streamContent = new MemoryStream(Encoding.UTF8.GetBytes(skinInfoJson))) { AddFile(s, streamContent, skin_info_file, s.Realm); } // Then serialise each of the drawable component groups into respective files. foreach (var drawableInfo in skin.DrawableComponentInfo) { string json = JsonConvert.SerializeObject(drawableInfo.Value, new JsonSerializerSettings { Formatting = Formatting.Indented }); using (var streamContent = new MemoryStream(Encoding.UTF8.GetBytes(json))) { string filename = @$"{drawableInfo.Key}.json"; var oldFile = s.Files.FirstOrDefault(f => f.Filename == filename); if (oldFile != null) ReplaceFile(oldFile, streamContent, s.Realm); else AddFile(s, streamContent, filename, s.Realm); } } s.Hash = ComputeHash(s); }); } public override bool IsAvailableLocally(SkinInfo model) => true; // skins do not have online download support yet. } }
{ "content_hash": "97d809b1ccf5d6bed20b7819359a6fb2", "timestamp": "", "source": "github", "line_count": 264, "max_line_length": 192, "avg_line_length": 42.68560606060606, "alnum_prop": 0.557547253527376, "repo_name": "NeoAdonis/osu", "id": "23813e8eb208420a683b18a76dea371054ed511c", "size": "11419", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "osu.Game/Skinning/SkinModelManager.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "12741336" }, { "name": "GLSL", "bytes": "230" }, { "name": "PowerShell", "bytes": "468" }, { "name": "Ruby", "bytes": "4185" }, { "name": "Shell", "bytes": "258" } ], "symlink_target": "" }
ACCEPTED #### According to NUB Generator [autonym] #### Published in null #### Original name null ### Remarks null
{ "content_hash": "fa602521232664ae971b1be9b166eeed", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 23, "avg_line_length": 9.076923076923077, "alnum_prop": 0.6779661016949152, "repo_name": "mdoering/backbone", "id": "a7819dd80ea627e182f104262cc353ba3ffd5300", "size": "173", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Rhynchosia/Rhynchosia luteola/Rhynchosia luteola luteola/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<md-toolbar class="md-whiteframe-4dp"> <div class="md-toolbar-tools"> <span flex></span> <img src="img/logo-branca.png" width="170px"/> <span flex></span> </div> </md-toolbar>
{ "content_hash": "4f109e3f5ffb5bbdca607f3397691e6c", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 54, "avg_line_length": 30.714285714285715, "alnum_prop": 0.5534883720930233, "repo_name": "LADOSSIFPB/nutrif", "id": "07fe2b08b8aab9faa49947443ae3b224e9fa2aca", "size": "215", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "nutrif-web-refactor/view/templates/toolbar-login.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "231534" }, { "name": "HTML", "bytes": "6534305" }, { "name": "Java", "bytes": "507491" }, { "name": "JavaScript", "bytes": "1402876" }, { "name": "Python", "bytes": "8425" }, { "name": "TSQL", "bytes": "2780" } ], "symlink_target": "" }
id: 587d78ad367417b2b2512af9 title: Use the align-items Property in the Tweet Embed challengeType: 0 videoUrl: 'https://scrimba.com/p/pVaDAv/cd3PNfq' forumTopicId: 301106 dashedName: use-the-align-items-property-in-the-tweet-embed --- # --description-- The last challenge introduced the `align-items` property and gave an example. This property can be applied to a few tweet embed elements to align the flex items inside them. # --instructions-- Add the CSS property `align-items` to the header's `.follow-btn` element. Set the value to `center`. # --hints-- Your `.follow-btn` should be rendered on the page. Be sure to turn off any extensions such as ad blockers. ```js assert($('.follow-btn').length > 0 && $('.follow-btn').css('display') !== 'none'); ``` The `.follow-btn` element should have the `align-items` property set to a value of `center`. ```js assert($('.follow-btn').css('align-items') == 'center'); ``` # --seed-- ## --seed-contents-- ```html <style> body { font-family: Arial, sans-serif; } header, footer { display: flex; flex-direction: row; } header .profile-thumbnail { width: 50px; height: 50px; border-radius: 4px; } header .profile-name { display: flex; flex-direction: column; justify-content: center; margin-left: 10px; } header .follow-btn { display: flex; margin: 0 0 0 auto; } header .follow-btn button { border: 0; border-radius: 3px; padding: 5px; } header h3, header h4 { display: flex; margin: 0; } #inner p { margin-bottom: 10px; font-size: 20px; } #inner hr { margin: 20px 0; border-style: solid; opacity: 0.1; } footer .stats { display: flex; font-size: 15px; } footer .stats strong { font-size: 18px; } footer .stats .likes { margin-left: 10px; } footer .cta { margin-left: auto; } footer .cta button { border: 0; background: transparent; } </style> <header> <img src="https://freecodecamp.s3.amazonaws.com/quincy-twitter-photo.jpg" alt="Quincy Larson's profile picture" class="profile-thumbnail"> <div class="profile-name"> <h3>Quincy Larson</h3> <h4>@ossia</h4> </div> <div class="follow-btn"> <button>Follow</button> </div> </header> <div id="inner"> <p>I meet so many people who are in search of that one trick that will help them work smart. Even if you work smart, you still have to work hard.</p> <span class="date">1:32 PM - 12 Jan 2018</span> <hr> </div> <footer> <div class="stats"> <div class="Retweets"> <strong>107</strong> Retweets </div> <div class="likes"> <strong>431</strong> Likes </div> </div> <div class="cta"> <button class="share-btn">Share</button> <button class="retweet-btn">Retweet</button> <button class="like-btn">Like</button> </div> </footer> ``` # --solutions-- ```html <style> body { font-family: Arial, sans-serif; } header, footer { display: flex; flex-direction: row; } header .profile-thumbnail { width: 50px; height: 50px; border-radius: 4px; } header .profile-name { display: flex; flex-direction: column; justify-content: center; margin-left: 10px; } header .follow-btn { display: flex; align-items: center; margin: 0 0 0 auto; } header .follow-btn button { border: 0; border-radius: 3px; padding: 5px; } header h3, header h4 { display: flex; margin: 0; } #inner p { margin-bottom: 10px; font-size: 20px; } #inner hr { margin: 20px 0; border-style: solid; opacity: 0.1; } footer .stats { display: flex; font-size: 15px; } footer .stats strong { font-size: 18px; } footer .stats .likes { margin-left: 10px; } footer .cta { margin-left: auto; } footer .cta button { border: 0; background: transparent; } </style> <header> <img src="https://freecodecamp.s3.amazonaws.com/quincy-twitter-photo.jpg" alt="Quincy Larson's profile picture" class="profile-thumbnail"> <div class="profile-name"> <h3>Quincy Larson</h3> <h4>@ossia</h4> </div> <div class="follow-btn"> <button>Follow</button> </div> </header> <div id="inner"> <p>I meet so many people who are in search of that one trick that will help them work smart. Even if you work smart, you still have to work hard.</p> <span class="date">1:32 PM - 12 Jan 2018</span> <hr> </div> <footer> <div class="stats"> <div class="Retweets"> <strong>107</strong> Retweets </div> <div class="likes"> <strong>431</strong> Likes </div> </div> <div class="cta"> <button class="share-btn">Share</button> <button class="retweet-btn">Retweet</button> <button class="like-btn">Like</button> </div> </footer> ```
{ "content_hash": "15ea0590aee146bd653458ffdf042090", "timestamp": "", "source": "github", "line_count": 221, "max_line_length": 173, "avg_line_length": 21.85972850678733, "alnum_prop": 0.6245083833574829, "repo_name": "FreeCodeCamp/FreeCodeCamp", "id": "98b3d28d95701ffa00303fb18c5a7ec33d601cdc", "size": "4835", "binary": false, "copies": "2", "ref": "refs/heads/i18n-sync-client", "path": "curriculum/challenges/english/01-responsive-web-design/css-flexbox/use-the-align-items-property-in-the-tweet-embed.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "190263" }, { "name": "HTML", "bytes": "160430" }, { "name": "JavaScript", "bytes": "546299" } ], "symlink_target": "" }
<?xml version="1.0"?> <!DOCTYPE OpenGLAPI SYSTEM "gl_API.dtd"> <!-- Note: no GLX protocol info yet. --> <OpenGLAPI> <category name="GL_ARB_robustness" number="105"> <enum name="GUILTY_CONTEXT_RESET_ARB" value="0x8253"/> <enum name="INNOCENT_CONTEXT_RESET_ARB" value="0x8254"/> <enum name="UNKNOWN_CONTEXT_RESET_ARB" value="0x8255"/> <enum name="RESET_NOTIFICATION_STRATEGY_ARB" count="1" value="0x8256"> <size name="Get" mode="get"/> </enum> <enum name="LOSE_CONTEXT_ON_RESET_ARB" value="0x8252"/> <enum name="NO_RESET_NOTIFICATION_ARB" value="0x8261"/> <enum name="CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB" value="0x00000004"/> <function name="GetGraphicsResetStatusARB" offset="assign"> <return type="GLenum"/> </function> <!-- OpenGL 1.0 sized buffer queries --> <function name="GetnMapdvARB" offset="assign" deprecated="3.1"> <param name="target" type="GLenum"/> <param name="query" type="GLenum"/> <param name="bufSize" type="GLsizei"/> <param name="v" type="GLdouble *" output="true"/> </function> <function name="GetnMapfvARB" offset="assign" deprecated="3.1"> <param name="target" type="GLenum"/> <param name="query" type="GLenum"/> <param name="bufSize" type="GLsizei"/> <param name="v" type="GLfloat *" output="true"/> </function> <function name="GetnMapivARB" offset="assign" deprecated="3.1"> <param name="target" type="GLenum"/> <param name="query" type="GLenum"/> <param name="bufSize" type="GLsizei"/> <param name="v" type="GLint *" output="true"/> </function> <function name="GetnPixelMapfvARB" offset="assign" deprecated="3.1"> <param name="map" type="GLenum"/> <param name="bufSize" type="GLsizei"/> <param name="values" type="GLfloat *" output="true"/> </function> <function name="GetnPixelMapuivARB" offset="assign" deprecated="3.1"> <param name="map" type="GLenum"/> <param name="bufSize" type="GLsizei"/> <param name="values" type="GLuint *" output="true"/> </function> <function name="GetnPixelMapusvARB" offset="assign" deprecated="3.1"> <param name="map" type="GLenum"/> <param name="bufSize" type="GLsizei"/> <param name="values" type="GLushort *" output="true"/> </function> <function name="GetnPolygonStippleARB" offset="assign"> <param name="bufSize" type="GLsizei"/> <param name="pattern" type="GLubyte *" output="true"/> </function> <function name="GetnTexImageARB" offset="assign"> <param name="target" type="GLenum"/> <param name="level" type="GLint"/> <param name="format" type="GLenum"/> <param name="type" type="GLenum"/> <param name="bufSize" type="GLsizei"/> <param name="img" type="GLvoid *" output="true"/> </function> <function name="ReadnPixelsARB" offset="assign"> <param name="x" type="GLint"/> <param name="y" type="GLint"/> <param name="width" type="GLsizei"/> <param name="height" type="GLsizei"/> <param name="format" type="GLenum"/> <param name="type" type="GLenum"/> <param name="bufSize" type="GLsizei"/> <param name="data" type="GLvoid *" output="true"/> </function> <!-- ARB_imaging sized buffer queries --> <function name="GetnColorTableARB" offset="assign" deprecated="3.1"> <param name="target" type="GLenum"/> <param name="format" type="GLenum"/> <param name="type" type="GLenum"/> <param name="bufSize" type="GLsizei"/> <param name="table" type="GLvoid *" output="true"/> </function> <function name="GetnConvolutionFilterARB" offset="assign" deprecated="3.1"> <param name="target" type="GLenum"/> <param name="format" type="GLenum"/> <param name="type" type="GLenum"/> <param name="bufSize" type="GLsizei"/> <param name="image" type="GLvoid *" output="true"/> </function> <function name="GetnSeparableFilterARB" offset="assign" deprecated="3.1"> <param name="target" type="GLenum"/> <param name="format" type="GLenum"/> <param name="type" type="GLenum"/> <param name="rowBufSize" type="GLsizei"/> <param name="row" type="GLvoid *" output="true"/> <param name="columnBufSize" type="GLsizei"/> <param name="column" type="GLvoid *" output="true"/> <param name="span" type="GLvoid *" output="true"/> </function> <function name="GetnHistogramARB" offset="assign" deprecated="3.1"> <param name="target" type="GLenum"/> <param name="reset" type="GLboolean"/> <param name="format" type="GLenum"/> <param name="type" type="GLenum"/> <param name="bufSize" type="GLsizei"/> <param name="values" type="GLvoid *" output="true"/> </function> <function name="GetnMinmaxARB" offset="assign" deprecated="3.1"> <param name="target" type="GLenum"/> <param name="reset" type="GLboolean"/> <param name="format" type="GLenum"/> <param name="type" type="GLenum"/> <param name="bufSize" type="GLsizei"/> <param name="values" type="GLvoid *" output="true"/> </function> <!-- OpenGL 1.3 sized buffer queries --> <function name="GetnCompressedTexImageARB" offset="assign"> <param name="target" type="GLenum"/> <param name="lod" type="GLint"/> <param name="bufSize" type="GLsizei"/> <param name="img" type="GLvoid *" output="true"/> </function> <!-- OpenGL 2.0 sized buffer queries --> <function name="GetnUniformfvARB" offset="assign"> <param name="program" type="GLhandleARB"/> <param name="location" type="GLint"/> <param name="bufSize" type="GLsizei"/> <param name="params" type="GLfloat *" output="true"/> </function> <function name="GetnUniformivARB" offset="assign"> <param name="program" type="GLhandleARB"/> <param name="location" type="GLint"/> <param name="bufSize" type="GLsizei"/> <param name="params" type="GLint *" output="true"/> </function> <function name="GetnUniformuivARB" offset="assign"> <param name="program" type="GLhandleARB"/> <param name="location" type="GLint"/> <param name="bufSize" type="GLsizei"/> <param name="params" type="GLuint *" output="true"/> </function> <function name="GetnUniformdvARB" offset="assign"> <param name="program" type="GLhandleARB"/> <param name="location" type="GLint"/> <param name="bufSize" type="GLsizei"/> <param name="params" type="GLdouble *" output="true"/> </function> </category> </OpenGLAPI>
{ "content_hash": "7a04c3f9ab2ff9853cdedc7927d18f78", "timestamp": "", "source": "github", "line_count": 185, "max_line_length": 79, "avg_line_length": 37.31891891891892, "alnum_prop": 0.5940034762456546, "repo_name": "devlato/kolibrios-llvm", "id": "14048bf49cccc5c868d069cbf6c834ae1a88a117", "size": "6904", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "contrib/sdk/sources/Mesa/src/mapi/glapi/gen/ARB_robustness.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "15418643" }, { "name": "C", "bytes": "126021466" }, { "name": "C++", "bytes": "11476220" }, { "name": "CSS", "bytes": "1230161" }, { "name": "JavaScript", "bytes": "687" }, { "name": "Logos", "bytes": "905" }, { "name": "Lua", "bytes": "2055" }, { "name": "Objective-C", "bytes": "482461" }, { "name": "Pascal", "bytes": "6692" }, { "name": "Perl", "bytes": "317449" }, { "name": "Puppet", "bytes": "161697" }, { "name": "Python", "bytes": "1036533" }, { "name": "Shell", "bytes": "448869" }, { "name": "Verilog", "bytes": "2829" }, { "name": "Visual Basic", "bytes": "4346" }, { "name": "XSLT", "bytes": "4325" } ], "symlink_target": "" }
if(DEFINED POLLY_OSX_10_14_DEP_10_10_CXX17_CMAKE_) return() else() set(POLLY_OSX_10_14_DEP_10_10_CXX17_CMAKE_ 1) endif() include("${CMAKE_CURRENT_LIST_DIR}/utilities/polly_init.cmake") set(OSX_SDK_VERSION "10.14") set(POLLY_XCODE_COMPILER "clang") polly_init( "Xcode (OS X ${OSX_SDK_VERSION} | Deployment 10.10) / \ ${POLLY_XCODE_COMPILER} / \ LLVM Standard C++ Library (libc++) / c++17 support" "Xcode" ) include("${CMAKE_CURRENT_LIST_DIR}/utilities/polly_common.cmake") include("${CMAKE_CURRENT_LIST_DIR}/compiler/xcode.cmake") set(CMAKE_OSX_DEPLOYMENT_TARGET "10.10" CACHE STRING "OS X Deployment target" FORCE) include("${CMAKE_CURRENT_LIST_DIR}/library/std/libcxx.cmake") include("${CMAKE_CURRENT_LIST_DIR}/flags/cxx17.cmake") include("${CMAKE_CURRENT_LIST_DIR}/os/osx.cmake")
{ "content_hash": "c927d780cdbe4342f9dbe8fbf96a5c21", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 84, "avg_line_length": 30.76923076923077, "alnum_prop": 0.70875, "repo_name": "idscan/polly", "id": "4ae7e0eb5517411eef6710861e1734e4b75bafaf", "size": "861", "binary": false, "copies": "3", "ref": "refs/heads/develop", "path": "osx-10-14-dep-10-10-cxx17.cmake", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Batchfile", "bytes": "26" }, { "name": "CMake", "bytes": "636016" }, { "name": "Python", "bytes": "89186" }, { "name": "Shell", "bytes": "2426" } ], "symlink_target": "" }
using System.Web; using System.Web.Optimization; namespace SocresSamples.Azure.Search { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/site.css")); } } }
{ "content_hash": "4e35a71cc649c275005c47e7a6b1c68a", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 112, "avg_line_length": 40.483870967741936, "alnum_prop": 0.5768924302788845, "repo_name": "Socres/Socres", "id": "b0f71abee0c04b83ffef326b136b9680ca57d699", "size": "1257", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samples/SocresSamples.Azure.Search/App_Start/BundleConfig.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "70136" } ], "symlink_target": "" }