code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
''' YARN Cluster Metrics -------------------- yarn.metrics.appsSubmitted The number of submitted apps yarn.metrics.appsCompleted The number of completed apps yarn.metrics.appsPending The number of pending apps yarn.metrics.appsRunning The number of running apps yarn.metrics.appsFailed The number of failed apps yarn.metrics.appsKilled The number of killed apps yarn.metrics.reservedMB The size of reserved memory yarn.metrics.availableMB The amount of available memory yarn.metrics.allocatedMB The amount of allocated memory yarn.metrics.totalMB The amount of total memory yarn.metrics.reservedVirtualCores The number of reserved virtual cores yarn.metrics.availableVirtualCores The number of available virtual cores yarn.metrics.allocatedVirtualCores The number of allocated virtual cores yarn.metrics.totalVirtualCores The total number of virtual cores yarn.metrics.containersAllocated The number of containers allocated yarn.metrics.containersReserved The number of containers reserved yarn.metrics.containersPending The number of containers pending yarn.metrics.totalNodes The total number of nodes yarn.metrics.activeNodes The number of active nodes yarn.metrics.lostNodes The number of lost nodes yarn.metrics.unhealthyNodes The number of unhealthy nodes yarn.metrics.decommissionedNodes The number of decommissioned nodes yarn.metrics.rebootedNodes The number of rebooted nodes YARN App Metrics ---------------- yarn.app.progress The progress of the application as a percent yarn.app.startedTime The time in which application started (in ms since epoch) yarn.app.finishedTime The time in which the application finished (in ms since epoch) yarn.app.elapsedTime The elapsed time since the application started (in ms) yarn.app.allocatedMB The sum of memory in MB allocated to the applications running containers yarn.app.allocatedVCores The sum of virtual cores allocated to the applications running containers yarn.app.runningContainers The number of containers currently running for the application yarn.app.memorySeconds The amount of memory the application has allocated (megabyte-seconds) yarn.app.vcoreSeconds The amount of CPU resources the application has allocated (virtual core-seconds) YARN Node Metrics ----------------- yarn.node.lastHealthUpdate The last time the node reported its health (in ms since epoch) yarn.node.usedMemoryMB The total amount of memory currently used on the node (in MB) yarn.node.availMemoryMB The total amount of memory currently available on the node (in MB) yarn.node.usedVirtualCores The total number of vCores currently used on the node yarn.node.availableVirtualCores The total number of vCores available on the node yarn.node.numContainers The total number of containers currently running on the node YARN Capacity Scheduler Metrics ----------------- yarn.queue.root.maxCapacity The configured maximum queue capacity in percentage for root queue yarn.queue.root.usedCapacity The used queue capacity in percentage for root queue yarn.queue.root.capacity The configured queue capacity in percentage for root queue yarn.queue.numPendingApplications The number of pending applications in this queue yarn.queue.userAMResourceLimit.memory The maximum memory resources a user can use for Application Masters (in MB) yarn.queue.userAMResourceLimit.vCores The maximum vCpus a user can use for Application Masters yarn.queue.absoluteCapacity The absolute capacity percentage this queue can use of entire cluster yarn.queue.userLimitFactor The minimum user limit percent set in the configuration yarn.queue.userLimit The user limit factor set in the configuration yarn.queue.numApplications The number of applications currently in the queue yarn.queue.usedAMResource.memory The memory resources used for Application Masters (in MB) yarn.queue.usedAMResource.vCores The vCpus used for Application Masters yarn.queue.absoluteUsedCapacity The absolute used capacity percentage this queue is using of the entire cluster yarn.queue.resourcesUsed.memory The total memory resources this queue is using (in MB) yarn.queue.resourcesUsed.vCores The total vCpus this queue is using yarn.queue.AMResourceLimit.vCores The maximum vCpus this queue can use for Application Masters yarn.queue.AMResourceLimit.memory The maximum memory resources this queue can use for Application Masters (in MB) yarn.queue.capacity The configured queue capacity in percentage relative to its parent queue yarn.queue.numActiveApplications The number of active applications in this queue yarn.queue.absoluteMaxCapacity The absolute maximum capacity percentage this queue can use of the entire cluster yarn.queue.usedCapacity The used queue capacity in percentage yarn.queue.numContainers The number of containers being used yarn.queue.maxCapacity The configured maximum queue capacity in percentage relative to its parent queue yarn.queue.maxApplications The maximum number of applications this queue can have yarn.queue.maxApplicationsPerUser The maximum number of active applications per user this queue can have ''' # stdlib from urlparse import urljoin, urlsplit, urlunsplit # 3rd party from requests.exceptions import Timeout, HTTPError, InvalidURL, ConnectionError import requests # Project from checks import AgentCheck from config import _is_affirmative # Default settings DEFAULT_RM_URI = 'http://localhost:8088' DEFAULT_TIMEOUT = 5 DEFAULT_CUSTER_NAME = 'default_cluster' DEFAULT_COLLECT_APP_METRICS = True MAX_DETAILED_QUEUES = 100 # Path to retrieve cluster metrics YARN_CLUSTER_METRICS_PATH = '/ws/v1/cluster/metrics' # Path to retrieve YARN APPS YARN_APPS_PATH = '/ws/v1/cluster/apps' # Path to retrieve node statistics YARN_NODES_PATH = '/ws/v1/cluster/nodes' # Path to retrieve queue statistics YARN_SCHEDULER_PATH = '/ws/v1/cluster/scheduler' # Metric types GAUGE = 'gauge' INCREMENT = 'increment' # Name of the service check SERVICE_CHECK_NAME = 'yarn.can_connect' # Application states to collect YARN_APPLICATION_STATES = 'RUNNING' # Cluster metrics identifier YARN_CLUSTER_METRICS_ELEMENT = 'clusterMetrics' # Cluster metrics for YARN YARN_CLUSTER_METRICS = { 'appsSubmitted': ('yarn.metrics.apps_submitted', GAUGE), 'appsCompleted': ('yarn.metrics.apps_completed', GAUGE), 'appsPending': ('yarn.metrics.apps_pending', GAUGE), 'appsRunning': ('yarn.metrics.apps_running', GAUGE), 'appsFailed': ('yarn.metrics.apps_failed', GAUGE), 'appsKilled': ('yarn.metrics.apps_killed', GAUGE), 'reservedMB': ('yarn.metrics.reserved_mb', GAUGE), 'availableMB': ('yarn.metrics.available_mb', GAUGE), 'allocatedMB': ('yarn.metrics.allocated_mb', GAUGE), 'totalMB': ('yarn.metrics.total_mb', GAUGE), 'reservedVirtualCores': ('yarn.metrics.reserved_virtual_cores', GAUGE), 'availableVirtualCores': ('yarn.metrics.available_virtual_cores', GAUGE), 'allocatedVirtualCores': ('yarn.metrics.allocated_virtual_cores', GAUGE), 'totalVirtualCores': ('yarn.metrics.total_virtual_cores', GAUGE), 'containersAllocated': ('yarn.metrics.containers_allocated', GAUGE), 'containersReserved': ('yarn.metrics.containers_reserved', GAUGE), 'containersPending': ('yarn.metrics.containers_pending', GAUGE), 'totalNodes': ('yarn.metrics.total_nodes', GAUGE), 'activeNodes': ('yarn.metrics.active_nodes', GAUGE), 'lostNodes': ('yarn.metrics.lost_nodes', GAUGE), 'unhealthyNodes': ('yarn.metrics.unhealthy_nodes', GAUGE), 'decommissionedNodes': ('yarn.metrics.decommissioned_nodes', GAUGE), 'rebootedNodes': ('yarn.metrics.rebooted_nodes', GAUGE), } # Application metrics for YARN YARN_APP_METRICS = { 'progress': ('yarn.apps.progress', INCREMENT), 'startedTime': ('yarn.apps.started_time', INCREMENT), 'finishedTime': ('yarn.apps.finished_time', INCREMENT), 'elapsedTime': ('yarn.apps.elapsed_time', INCREMENT), 'allocatedMB': ('yarn.apps.allocated_mb', INCREMENT), 'allocatedVCores': ('yarn.apps.allocated_vcores', INCREMENT), 'runningContainers': ('yarn.apps.running_containers', INCREMENT), 'memorySeconds': ('yarn.apps.memory_seconds', INCREMENT), 'vcoreSeconds': ('yarn.apps.vcore_seconds', INCREMENT), } # Node metrics for YARN YARN_NODE_METRICS = { 'lastHealthUpdate': ('yarn.node.last_health_update', GAUGE), 'usedMemoryMB': ('yarn.node.used_memory_mb', GAUGE), 'availMemoryMB': ('yarn.node.avail_memory_mb', GAUGE), 'usedVirtualCores': ('yarn.node.used_virtual_cores', GAUGE), 'availableVirtualCores': ('yarn.node.available_virtual_cores', GAUGE), 'numContainers': ('yarn.node.num_containers', GAUGE), } # Root queue metrics for YARN YARN_ROOT_QUEUE_METRICS = { 'maxCapacity': ('yarn.queue.root.max_capacity', GAUGE), 'usedCapacity': ('yarn.queue.root.used_capacity', GAUGE), 'capacity': ('yarn.queue.root.capacity', GAUGE) } # Queue metrics for YARN YARN_QUEUE_METRICS = { 'numPendingApplications': ('yarn.queue.num_pending_applications', GAUGE), 'userAMResourceLimit.memory': ('yarn.queue.user_am_resource_limit.memory', GAUGE), 'userAMResourceLimit.vCores': ('yarn.queue.user_am_resource_limit.vcores', GAUGE), 'absoluteCapacity': ('yarn.queue.absolute_capacity', GAUGE), 'userLimitFactor': ('yarn.queue.user_limit_factor', GAUGE), 'userLimit': ('yarn.queue.user_limit', GAUGE), 'numApplications': ('yarn.queue.num_applications', GAUGE), 'usedAMResource.memory': ('yarn.queue.used_am_resource.memory', GAUGE), 'usedAMResource.vCores': ('yarn.queue.used_am_resource.vcores', GAUGE), 'absoluteUsedCapacity': ('yarn.queue.absolute_used_capacity', GAUGE), 'resourcesUsed.memory': ('yarn.queue.resources_used.memory', GAUGE), 'resourcesUsed.vCores': ('yarn.queue.resources_used.vcores', GAUGE), 'AMResourceLimit.vCores': ('yarn.queue.am_resource_limit.vcores', GAUGE), 'AMResourceLimit.memory': ('yarn.queue.am_resource_limit.memory', GAUGE), 'capacity': ('yarn.queue.capacity', GAUGE), 'numActiveApplications': ('yarn.queue.num_active_applications', GAUGE), 'absoluteMaxCapacity': ('yarn.queue.absolute_max_capacity', GAUGE), 'usedCapacity' : ('yarn.queue.used_capacity', GAUGE), 'numContainers': ('yarn.queue.num_containers', GAUGE), 'maxCapacity': ('yarn.queue.max_capacity', GAUGE), 'maxApplications': ('yarn.queue.max_applications', GAUGE), 'maxApplicationsPerUser': ('yarn.queue.max_applications_per_user', GAUGE) } class YarnCheck(AgentCheck): ''' Extract statistics from YARN's ResourceManger REST API ''' _ALLOWED_APPLICATION_TAGS = [ 'applicationTags', 'applicationType', 'name', 'queue', 'user' ] def check(self, instance): # Get properties from conf file rm_address = instance.get('resourcemanager_uri', DEFAULT_RM_URI) app_tags = instance.get('application_tags', {}) queue_blacklist = instance.get('queue_blacklist', []) if type(app_tags) is not dict: self.log.error('application_tags is incorrect: %s is not a dictionary', app_tags) app_tags = {} filtered_app_tags = {} for dd_prefix, yarn_key in app_tags.iteritems(): if yarn_key in self._ALLOWED_APPLICATION_TAGS: filtered_app_tags[dd_prefix] = yarn_key app_tags = filtered_app_tags # Collected by default app_tags['app_name'] = 'name' # Get additional tags from the conf file tags = instance.get('tags', []) if tags is None: tags = [] else: tags = list(set(tags)) # Get the cluster name from the conf file cluster_name = instance.get('cluster_name') if cluster_name is None: self.warning("The cluster_name must be specified in the instance configuration, defaulting to '%s'" % (DEFAULT_CUSTER_NAME)) cluster_name = DEFAULT_CUSTER_NAME tags.append('cluster_name:%s' % cluster_name) # Get metrics from the Resource Manager self._yarn_cluster_metrics(rm_address, tags) if _is_affirmative(instance.get('collect_app_metrics', DEFAULT_COLLECT_APP_METRICS)): self._yarn_app_metrics(rm_address, app_tags, tags) self._yarn_node_metrics(rm_address, tags) self._yarn_scheduler_metrics(rm_address, tags, queue_blacklist) def _yarn_cluster_metrics(self, rm_address, addl_tags): ''' Get metrics related to YARN cluster ''' metrics_json = self._rest_request_to_json(rm_address, YARN_CLUSTER_METRICS_PATH) if metrics_json: yarn_metrics = metrics_json[YARN_CLUSTER_METRICS_ELEMENT] if yarn_metrics is not None: self._set_yarn_metrics_from_json(addl_tags, yarn_metrics, YARN_CLUSTER_METRICS) def _yarn_app_metrics(self, rm_address, app_tags, addl_tags): ''' Get metrics for running applications ''' metrics_json = self._rest_request_to_json( rm_address, YARN_APPS_PATH, states=YARN_APPLICATION_STATES ) if (metrics_json and metrics_json['apps'] is not None and metrics_json['apps']['app'] is not None): for app_json in metrics_json['apps']['app']: tags = [] for dd_tag, yarn_key in app_tags.iteritems(): try: val = app_json[yarn_key] if val: tags.append("{tag}:{value}".format( tag=dd_tag, value=val )) except KeyError: self.log.error("Invalid value %s for application_tag", yarn_key) tags.extend(addl_tags) self._set_yarn_metrics_from_json(tags, app_json, YARN_APP_METRICS) def _yarn_node_metrics(self, rm_address, addl_tags): ''' Get metrics related to YARN nodes ''' metrics_json = self._rest_request_to_json(rm_address, YARN_NODES_PATH) if (metrics_json and metrics_json['nodes'] is not None and metrics_json['nodes']['node'] is not None): for node_json in metrics_json['nodes']['node']: node_id = node_json['id'] tags = ['node_id:%s' % str(node_id)] tags.extend(addl_tags) self._set_yarn_metrics_from_json(tags, node_json, YARN_NODE_METRICS) def _yarn_scheduler_metrics(self, rm_address, addl_tags, queue_blacklist): ''' Get metrics from YARN scheduler ''' metrics_json = self._rest_request_to_json(rm_address, YARN_SCHEDULER_PATH) try: metrics_json = metrics_json['scheduler']['schedulerInfo'] if metrics_json['type'] == 'capacityScheduler': self._yarn_capacity_scheduler_metrics(metrics_json, addl_tags, queue_blacklist) except KeyError: pass def _yarn_capacity_scheduler_metrics(self, metrics_json, addl_tags, queue_blacklist): ''' Get metrics from YARN scheduler if it's type is capacityScheduler ''' tags = ['queue_name:%s' % metrics_json['queueName']] tags.extend(addl_tags) self._set_yarn_metrics_from_json(tags, metrics_json, YARN_ROOT_QUEUE_METRICS) if metrics_json['queues'] is not None and metrics_json['queues']['queue'] is not None: queues_count = 0 for queue_json in metrics_json['queues']['queue']: queue_name = queue_json['queueName'] if queue_name in queue_blacklist: self.log.debug('Queue "%s" is blacklisted. Ignoring it' % queue_name) continue queues_count += 1 if queues_count > MAX_DETAILED_QUEUES: self.warning("Found more than 100 queues, will only send metrics on first 100 queues. " + " Please filter the queues with the check's `queue_blacklist` parameter") break tags = ['queue_name:%s' % str(queue_name)] tags.extend(addl_tags) self._set_yarn_metrics_from_json(tags, queue_json, YARN_QUEUE_METRICS) def _set_yarn_metrics_from_json(self, tags, metrics_json, yarn_metrics): ''' Parse the JSON response and set the metrics ''' for dict_path, metric in yarn_metrics.iteritems(): metric_name, metric_type = metric metric_value = self._get_value_from_json(dict_path, metrics_json) if metric_value is not None: self._set_metric(metric_name, metric_type, metric_value, tags) def _get_value_from_json(self, dict_path, metrics_json): ''' Get a value from a dictionary under N keys, represented as str("key1.key2...key{n}") ''' for key in dict_path.split('.'): if key in metrics_json: metrics_json = metrics_json.get(key) else: return None return metrics_json def _set_metric(self, metric_name, metric_type, value, tags=None, device_name=None): ''' Set a metric ''' if metric_type == GAUGE: self.gauge(metric_name, value, tags=tags, device_name=device_name) elif metric_type == INCREMENT: self.increment(metric_name, value, tags=tags, device_name=device_name) else: self.log.error('Metric type "%s" unknown', metric_type) def _rest_request_to_json(self, address, object_path, *args, **kwargs): ''' Query the given URL and return the JSON response ''' response_json = None service_check_tags = ['url:%s' % self._get_url_base(address)] url = address if object_path: url = self._join_url_dir(url, object_path) # Add args to the url if args: for directory in args: url = self._join_url_dir(url, directory) self.log.debug('Attempting to connect to "%s"' % url) # Add kwargs as arguments if kwargs: query = '&'.join(['{0}={1}'.format(key, value) for key, value in kwargs.iteritems()]) url = urljoin(url, '?' + query) try: response = requests.get(url, timeout=self.default_integration_http_timeout) response.raise_for_status() response_json = response.json() except Timeout as e: self.service_check(SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=service_check_tags, message="Request timeout: {0}, {1}".format(url, e)) raise except (HTTPError, InvalidURL, ConnectionError) as e: self.service_check(SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=service_check_tags, message="Request failed: {0}, {1}".format(url, e)) raise except ValueError as e: self.service_check(SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=service_check_tags, message=str(e)) raise else: self.service_check(SERVICE_CHECK_NAME, AgentCheck.OK, tags=service_check_tags, message='Connection to %s was successful' % url) return response_json def _join_url_dir(self, url, *args): ''' Join a URL with multiple directories ''' for path in args: url = url.rstrip('/') + '/' url = urljoin(url, path.lstrip('/')) return url def _get_url_base(self, url): ''' Return the base of a URL ''' s = urlsplit(url) return urlunsplit([s.scheme, s.netloc, '', '', ''])
StackVista/sts-agent-integrations-core
yarn/check.py
Python
bsd-3-clause
20,533
def extractRoontalesCom(item): ''' Parser for 'roontales.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractRoontalesCom.py
Python
bsd-3-clause
539
typedef unsigned char color; typedef struct { color Blue; color Green; color Red; } BGR; typedef struct { BGR content[16][16]; } color_block; typedef struct { short content[8][8]; } color_converted_block; color_block color_block_to_be_converted; /* RGB to YCbCr Conversion: */ // Y = 0.299*R + 0.587*G + 0.114*B color RGB2Y(const color r, const color g, const color b) { return (153 * r + 301 * g + 58 * b) >> 9; } // Cb = -0.1687*R - 0.3313*G + 0.5*B + 128 color RGB2Cb(const color r, const color g, const color b) { return (65536 - 86 * r - 170 * g + 256 * b) >> 9; } // Cr = 0.5*R - 0.4187*G - 0.0813*B + 128 color RGB2Cr(const color r, const color g, const color b) { return (65536 + 256 * r - 214 * g - 42 * b) >> 9; } // chroma subsampling, i.e. converting a 16x16 RGB block into 8x8 Cb and Cr void subsample(BGR rgb[16][16], short cb[8][8], short cr[8][8]) { unsigned r, c; for (r = 0; r < 8; r++) for (c = 0; c < 8; c++) { unsigned rr = (r << 1); unsigned cc = (c << 1); // calculating average values color R = (rgb[rr][cc].Red + rgb[rr][cc + 1].Red + rgb[rr + 1][cc].Red + rgb[rr + 1][cc + 1].Red) >> 2; color G = (rgb[rr][cc].Green + rgb[rr][cc + 1].Green + rgb[rr + 1][cc].Green + rgb[rr + 1][cc + 1].Green) >> 2; color B = (rgb[rr][cc].Blue + rgb[rr][cc + 1].Blue + rgb[rr + 1][cc].Blue + rgb[rr + 1][cc + 1].Blue) >> 2; cb[r][c] = (short) RGB2Cb(R, G, B) - 128; cr[r][c] = (short) RGB2Cr(R, G, B) - 128; } } void color_conversion(color_block current_color_block) { color_converted_block outgoing_blocks[2][2]; color_converted_block cb_block; color_converted_block cr_block; unsigned int i, j, r, c; // getting four 8x8 Y-blocks for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { for (r = 0; r < 8; r++) { for (c = 0; c < 8; c++) { const unsigned rr = (i << 3) + r; const unsigned cc = (j << 3) + c; const color R = current_color_block.content[rr][cc].Red; const color G = current_color_block.content[rr][cc].Green; const color B = current_color_block.content[rr][cc].Blue; // converting RGB into Y (luminance) outgoing_blocks[i][j].content[r][c] = RGB2Y(R, G, B) - 128; } } } } // one block of 8x8 Cr short Cb8x8[8][8]; // one block of 8x8 Cb short Cr8x8[8][8]; // create subsampled Cb and Cr blocks subsample(current_color_block.content, Cb8x8, Cr8x8); for (r = 0; r < 8; r++) { for (c = 0; c < 8; c++) { cb_block.content[r][c] = Cb8x8[r][c]; } } for (r = 0; r < 8; r++) { for (c = 0; c < 8; c++) { cr_block.content[r][c] = Cr8x8[r][c]; } } } int main() { color_conversion(color_block_to_be_converted); return 1; }
mikulcak/forsyde_psopc
examples/jpeg_encoder_four_processors/sweet/color_conversion/color_conversion.c
C
bsd-3-clause
2,697
/* * Copyright (c) 2016, SRCH2 * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the SRCH2 nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL SRCH2 BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef __WRAPPER_UNIONLOWESTLEVELSUGGESTIONOPERATOR_H__ #define __WRAPPER_UNIONLOWESTLEVELSUGGESTIONOPERATOR_H__ #include "instantsearch/Constants.h" #include "index/ForwardIndex.h" #include "index/Trie.h" #include "index/InvertedIndex.h" #include "operation/HistogramManager.h" #include "PhysicalPlan.h" using namespace std; namespace srch2 { namespace instantsearch { /* * This operator is a suggestion opertor. As of Dec,23rd,2013 this operator is only used when there is * a single keyword in the query which is too popular and we decide to return the results of most likely * completions instead of returning the results of the query itself. It's also known as H1 heuristic. */ class UnionLowestLevelSuggestionOperator : public PhysicalPlanNode { friend class PhysicalOperatorFactory; public: /* * This struct is used with a heap to output records sorted by their score */ struct SuggestionCursorHeapItem{ SuggestionCursorHeapItem(){ this->suggestionIndex = 0; this->invertedListCursor = 0; this->recordId = 0; this->score = 0; this->termRecordStaticScore = 0; } SuggestionCursorHeapItem(unsigned suggestionIndex, unsigned invertedListCursor, unsigned recordId, float score, const vector<unsigned>& attributeIdsList, float termRecordStaticScore){ this->suggestionIndex = suggestionIndex; this->invertedListCursor = invertedListCursor; this->recordId = recordId; this->score = score; this->attributeIdsList = attributeIdsList; this->termRecordStaticScore = termRecordStaticScore; } SuggestionCursorHeapItem(const SuggestionCursorHeapItem & src){ this->suggestionIndex = src.suggestionIndex; this->invertedListCursor = src.invertedListCursor; this->recordId = src.recordId; this->score = src.score; this->attributeIdsList = src.attributeIdsList; this->termRecordStaticScore = src.termRecordStaticScore; } bool operator()(const SuggestionCursorHeapItem & left, const SuggestionCursorHeapItem & right){ return left.score < right.score; } unsigned suggestionIndex; unsigned invertedListCursor; unsigned recordId; float score; vector<unsigned> attributeIdsList ; float termRecordStaticScore ; }; bool open(QueryEvaluatorInternal * queryEvaluator, PhysicalPlanExecutionParameters & params); PhysicalPlanRecordItem * getNext(const PhysicalPlanExecutionParameters & params) ; bool close(PhysicalPlanExecutionParameters & params); string toString(); bool verifyByRandomAccess(PhysicalPlanRandomAccessVerificationParameters & parameters) ; ~UnionLowestLevelSuggestionOperator(); private: UnionLowestLevelSuggestionOperator() ; // vector of all suggestions of the keyword std::vector<SuggestionInfo > suggestionPairs; // inverted lists corresponding to suggestions. We keep them in this vector for improving efficiency. std::vector<shared_ptr<vectorview<unsigned> > > suggestionPairsInvertedListReadViews; // this heap keeps the most top unread records of inverted lists and always keeps the best one // according to runtime score on top std::vector<SuggestionCursorHeapItem> recordItemsHeap; QueryEvaluatorInternal * queryEvaluatorIntrnal; shared_ptr<vectorview<InvertedListContainerPtr> > invertedListDirectoryReadView; shared_ptr<vectorview<unsigned> > invertedIndexKeywordIdsReadView; shared_ptr<vectorview<ForwardListPtr> > forwardIndexDirectoryReadView; /* * this function iterates on possible suggestions and puts the first record * of each inverted list in a max heap */ void initializeHeap(Term * term, Ranker * ranker, float prefixMatchPenalty); /* * This function returns the top element of recordItemsHeap and uses the same inverted * list to push another record to the heap */ bool getNextHeapItem(Term * term, Ranker * ranker, float prefixMatchPenalty, UnionLowestLevelSuggestionOperator::SuggestionCursorHeapItem & item); }; class UnionLowestLevelSuggestionOptimizationOperator : public PhysicalPlanOptimizationNode { friend class PhysicalOperatorFactory; public: // The cost of open of a child is considered only once in the cost computation // of parent open function. PhysicalPlanCost getCostOfOpen(const PhysicalPlanExecutionParameters & params) ; // The cost of getNext of a child is multiplied by the estimated number of calls to this function // when the cost of parent is being calculated. PhysicalPlanCost getCostOfGetNext(const PhysicalPlanExecutionParameters & params) ; // the cost of close of a child is only considered once since each node's close function is only called once. PhysicalPlanCost getCostOfClose(const PhysicalPlanExecutionParameters & params) ; PhysicalPlanCost getCostOfVerifyByRandomAccess(const PhysicalPlanExecutionParameters & params); void getOutputProperties(IteratorProperties & prop); void getRequiredInputProperties(IteratorProperties & prop); PhysicalPlanNodeType getType() ; bool validateChildren(); }; } } #endif // __WRAPPER_UNIONLOWESTLEVELSUGGESTIONOPERATOR_H__
SRCH2/srch2-ngn
src/core/operation/physical_plan/UnionLowestLevelSuggestionOperator.h
C
bsd-3-clause
6,526
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>alt property - ImageElement class - polymer_app_layout.behaviors library - Dart API</title> <!-- required because all the links are pseudo-absolute --> <base href="../.."> <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="static-assets/prettify.css"> <link rel="stylesheet" href="static-assets/css/bootstrap.min.css"> <link rel="stylesheet" href="static-assets/styles.css"> <meta name="description" content="API docs for the alt property from the ImageElement class, for the Dart programming language."> <link rel="icon" href="static-assets/favicon.png"> <!-- Do not remove placeholder --> <!-- Header Placeholder --> </head> <body> <div id="overlay-under-drawer"></div> <header class="container-fluid" id="title"> <nav class="navbar navbar-fixed-top"> <div class="container"> <button id="sidenav-left-toggle" type="button">&nbsp;</button> <ol class="breadcrumbs gt-separated hidden-xs"> <li><a href="index.html">polymer_app_layout_template</a></li> <li><a href="polymer_app_layout.behaviors/polymer_app_layout.behaviors-library.html">polymer_app_layout.behaviors</a></li> <li><a href="polymer_app_layout.behaviors/ImageElement-class.html">ImageElement</a></li> <li class="self-crumb">alt</li> </ol> <div class="self-name">alt</div> </div> </nav> <div class="container masthead"> <ol class="breadcrumbs gt-separated visible-xs"> <li><a href="index.html">polymer_app_layout_template</a></li> <li><a href="polymer_app_layout.behaviors/polymer_app_layout.behaviors-library.html">polymer_app_layout.behaviors</a></li> <li><a href="polymer_app_layout.behaviors/ImageElement-class.html">ImageElement</a></li> <li class="self-crumb">alt</li> </ol> <div class="title-description"> <h1 class="title"> <div class="kind">property</div> alt </h1> <!-- p class="subtitle"> </p --> </div> <ul class="subnav"> </ul> </div> </header> <div class="container body"> <div class="col-xs-6 col-sm-3 sidebar sidebar-offcanvas-left"> <h5><a href="index.html">polymer_app_layout_template</a></h5> <h5><a href="polymer_app_layout.behaviors/polymer_app_layout.behaviors-library.html">polymer_app_layout.behaviors</a></h5> <h5><a href="polymer_app_layout.behaviors/ImageElement-class.html">ImageElement</a></h5> <ol> <li class="section-title"><a href="polymer_app_layout.behaviors/ImageElement-class.html#instance-properties">Properties</a></li> <li><a href="polymer_app_layout.behaviors/ImageElement/alt.html">alt</a> </li> <li>attributes </li> <li>baseUri </li> <li>borderEdge </li> <li>childNodes </li> <li>children </li> <li>classes </li> <li>className </li> <li>client </li> <li>clientHeight </li> <li>clientLeft </li> <li>clientTop </li> <li>clientWidth </li> <li><a href="polymer_app_layout.behaviors/ImageElement/complete.html">complete</a> </li> <li>contentEdge </li> <li>contentEditable </li> <li>contextMenu </li> <li><a href="polymer_app_layout.behaviors/ImageElement/crossOrigin.html">crossOrigin</a> </li> <li><a href="polymer_app_layout.behaviors/ImageElement/currentSrc.html">currentSrc</a> </li> <li>dataset </li> <li>dir </li> <li>documentOffset </li> <li>draggable </li> <li>dropzone </li> <li>firstChild </li> <li><a href="polymer_app_layout.behaviors/ImageElement/height.html">height</a> </li> <li>hidden </li> <li>id </li> <li>innerHtml </li> <li>inputMethodContext </li> <li><a href="polymer_app_layout.behaviors/ImageElement/integrity.html">integrity</a> </li> <li>isContentEditable </li> <li><a href="polymer_app_layout.behaviors/ImageElement/isMap.html">isMap</a> </li> <li>lang </li> <li>lastChild </li> <li>localName </li> <li>marginEdge </li> <li>namespaceUri </li> <li><a href="polymer_app_layout.behaviors/ImageElement/naturalHeight.html">naturalHeight</a> </li> <li><a href="polymer_app_layout.behaviors/ImageElement/naturalWidth.html">naturalWidth</a> </li> <li>nextElementSibling </li> <li>nextNode </li> <li>nodeName </li> <li>nodes </li> <li>nodeType </li> <li>nodeValue </li> <li>offset </li> <li>offsetHeight </li> <li>offsetLeft </li> <li>offsetParent </li> <li>offsetTop </li> <li>offsetWidth </li> <li>on </li> <li>onAbort </li> <li>onBeforeCopy </li> <li>onBeforeCut </li> <li>onBeforePaste </li> <li>onBlur </li> <li>onCanPlay </li> <li>onCanPlayThrough </li> <li>onChange </li> <li>onClick </li> <li>onContextMenu </li> <li>onCopy </li> <li>onCut </li> <li>onDoubleClick </li> <li>onDrag </li> <li>onDragEnd </li> <li>onDragEnter </li> <li>onDragLeave </li> <li>onDragOver </li> <li>onDragStart </li> <li>onDrop </li> <li>onDurationChange </li> <li>onEmptied </li> <li>onEnded </li> <li>onError </li> <li>onFocus </li> <li>onFullscreenChange </li> <li>onFullscreenError </li> <li>onInput </li> <li>onInvalid </li> <li>onKeyDown </li> <li>onKeyPress </li> <li>onKeyUp </li> <li>onLoad </li> <li>onLoadedData </li> <li>onLoadedMetadata </li> <li>onMouseDown </li> <li>onMouseEnter </li> <li>onMouseLeave </li> <li>onMouseMove </li> <li>onMouseOut </li> <li>onMouseOver </li> <li>onMouseUp </li> <li>onMouseWheel </li> <li>onPaste </li> <li>onPause </li> <li>onPlay </li> <li>onPlaying </li> <li>onRateChange </li> <li>onReset </li> <li>onResize </li> <li>onScroll </li> <li>onSearch </li> <li>onSeeked </li> <li>onSeeking </li> <li>onSelect </li> <li>onSelectStart </li> <li>onStalled </li> <li>onSubmit </li> <li>onSuspend </li> <li>onTimeUpdate </li> <li>onTouchCancel </li> <li>onTouchEnd </li> <li>onTouchEnter </li> <li>onTouchLeave </li> <li>onTouchMove </li> <li>onTouchStart </li> <li>onTransitionEnd </li> <li>onVolumeChange </li> <li>onWaiting </li> <li>outerHtml </li> <li>ownerDocument </li> <li>paddingEdge </li> <li>parent </li> <li>parentNode </li> <li>previousElementSibling </li> <li>previousNode </li> <li>scrollHeight </li> <li>scrollLeft </li> <li>scrollTop </li> <li>scrollWidth </li> <li>shadowRoot </li> <li><a href="polymer_app_layout.behaviors/ImageElement/sizes.html">sizes</a> </li> <li>spellcheck </li> <li><a href="polymer_app_layout.behaviors/ImageElement/src.html">src</a> </li> <li><a href="polymer_app_layout.behaviors/ImageElement/srcset.html">srcset</a> </li> <li>style </li> <li>tabIndex </li> <li>tagName </li> <li>text </li> <li>title </li> <li>translate </li> <li><a href="polymer_app_layout.behaviors/ImageElement/useMap.html">useMap</a> </li> <li><a href="polymer_app_layout.behaviors/ImageElement/width.html">width</a> </li> <li>xtag </li> <li class="section-title"><a href="polymer_app_layout.behaviors/ImageElement-class.html#constructors">Constructors</a></li> <li><a href="polymer_app_layout.behaviors/ImageElement/ImageElement.html">ImageElement</a></li> <li><a href="polymer_app_layout.behaviors/ImageElement/ImageElement.created.html">created</a></li> <li class="section-title"><a href="polymer_app_layout.behaviors/ImageElement-class.html#methods">Methods</a></li> <li>addEventListener </li> <li>animate </li> <li>append </li> <li>appendHtml </li> <li>appendText </li> <li>attached </li> <li>attributeChanged </li> <li>blur </li> <li>click </li> <li>clone </li> <li>contains </li> <li>createFragment </li> <li>createShadowRoot </li> <li>detached </li> <li>dispatchEvent </li> <li>enteredView </li> <li>focus </li> <li>getAnimationPlayers </li> <li>getAttribute </li> <li>getAttributeNS </li> <li>getBoundingClientRect </li> <li>getClientRects </li> <li>getComputedStyle </li> <li>getDestinationInsertionPoints </li> <li>getElementsByClassName </li> <li>getNamespacedAttributes </li> <li>hasChildNodes </li> <li>insertAdjacentElement </li> <li>insertAdjacentHtml </li> <li>insertAdjacentText </li> <li>insertAllBefore </li> <li>insertBefore </li> <li>leftView </li> <li>matches </li> <li>matchesWithAncestors </li> <li>offsetTo </li> <li>query </li> <li>queryAll </li> <li>querySelector </li> <li>querySelectorAll </li> <li>remove </li> <li>removeEventListener </li> <li>replaceWith </li> <li>requestFullscreen </li> <li>requestPointerLock </li> <li>scrollIntoView </li> <li>setAttribute </li> <li>setAttributeNS </li> <li>setInnerHtml </li> <li>toString </li> </ol> </div><!--/.sidebar-offcanvas--> <div class="col-xs-12 col-sm-9 col-md-6 main-content"> <section class="multi-line-signature"> <span class="returntype">String</span> <span class="name ">alt</span> <div class="readable-writable"> read / write </div> </section> <section class="desc markdown"> <p class="no-docs">Not documented.</p> </section> </div> <!-- /.main-content --> </div> <!-- container --> <footer> <div class="container-fluid"> <div class="container"> <p class="text-center"> <span class="no-break"> polymer_app_layout_template 0.1.0 api docs </span> &bull; <span class="copyright no-break"> <a href="https://www.dartlang.org"> <img src="static-assets/favicon.png" alt="Dart" title="Dart"width="16" height="16"> </a> </span> &bull; <span class="copyright no-break"> <a href="http://creativecommons.org/licenses/by-sa/4.0/">cc license</a> </span> </p> </div> </div> </footer> <script src="static-assets/prettify.js"></script> <script src="static-assets/script.js"></script> <!-- Do not remove placeholder --> <!-- Footer Placeholder --> </body> </html>
lejard-h/polymer_app_layout_templates
doc/api/polymer_app_layout.behaviors/ImageElement/alt.html
HTML
bsd-3-clause
11,319
<h1>your create page</h1>
jonschwadron/secret-message
views/create.html
HTML
bsd-3-clause
26
<?php /** * Created by PhpStorm. * User: Admin * Date: 07.11.13 * Time: 16:48 */ namespace Project\Form; use Zend\Form\Form; use Zend\InputFilter\Factory as InputFactory; use Zend\InputFilter\InputFilter; class ProjectForm extends Form { public function __construct($name = null) { parent::__construct('project'); $this->setAttribute('method', 'post'); //$this->setInputFilter(new ProjectInputFilter()); $this->add(array( 'name' => 'id', 'type' => 'Hidden', )); $this->add(array( 'name' => 'created', 'type' => 'Hidden', )); $this->add(array( 'name' => 'userId', 'type' => 'Hidden', )); $this->add(array( 'name' => 'title', 'type' => 'Text', 'options' => array( 'min' => 3, 'max' => 25, 'label' => 'Title', ), )); $this->add(array( 'name' => 'body', 'type' => 'Textarea', 'options' => array( 'label' => 'Text', ), )); $this->add(array( 'name' => 'state', 'type' => 'Checkbox', 'options' => array( 'label' => 'published', ), )); $this->add(array( 'name' => 'submit', 'type' => 'Submit', 'attributes' => array( 'value' => 'Save', 'id' => 'submitbutton', ), )); } }
mufanu/zf2
module/Project/src/Project/Form/ProjectForm.php
PHP
bsd-3-clause
1,659
class InventoryUnit < ActiveRecord::Base belongs_to :variant belongs_to :order belongs_to :shipment belongs_to :return_authorization named_scope :retrieve_on_hand, lambda {|variant, quantity| {:conditions => ["state = 'on_hand' AND variant_id = ?", variant], :limit => quantity}} # state machine (see http://github.com/pluginaweek/state_machine/tree/master for details) state_machine :initial => 'on_hand' do event :fill_backorder do transition :to => 'sold', :from => 'backordered' end event :ship do transition :to => 'shipped', :if => :allow_ship? #, :from => 'sold' end # TODO: add backorder state and relevant transitions end # destroy the specified number of on hand inventory units def self.destroy_on_hand(variant, quantity) inventory = self.retrieve_on_hand(variant, quantity) inventory.each do |unit| unit.destroy end end # create the specified number of on hand inventory units def self.create_on_hand(variant, quantity) quantity.times do self.create(:variant => variant, :state => 'on_hand') end end # grab the appropriate units from inventory, mark as sold and associate with the order # def self.sell_units(order) # out_of_stock_items = [] # order.line_items.each do |line_item| # variant = line_item.variant # quantity = line_item.quantity # product=variant.product # current_deal=DealHistory.find_by_is_active(true) # # mark all of these units as sold and associate them with this order # # if product.deal_expiry_date<Time.now # out_of_stock_items << {:line_item => line_item, :expired => 'true'} # # elsif variant.count_on_hand==0 # out_of_stock_items << {:line_item => line_item, :sold_out => 'true'} # # # else # # remaining_quantity = variant.count_on_hand - quantity # if (remaining_quantity >= 0) # quantity.times do # order.inventory_units.create(:variant => variant, :state => "sold") # end # variant.update_attribute(:count_on_hand, remaining_quantity) # product.update_attribute(:currently_bought_count,product.currently_bought_count+quantity) # if remaining_quantity==0 # current_deal.sell_out # end # if product.currently_bought_count==product.minimum_number # # end # # else # # line_item.update_attribute(:quantity, quantity + remaining_quantity) # out_of_stock_items << {:line_item => line_item, :count => -remaining_quantity} # # end # end # end # # out_of_stock_items # end class << self def deal_status_update(order) product = order.line_items[0].variant.product user = User.find_by_email(order.email) begin if product.id == 1060500648 if order.state!='credit_owed' bought_count=product.currently_bought_count min_number = product.minimum_number if bought_count>min_number and (bought_count-1)>min_number logger.info "deal already on and trying to send confirmation mail" message = "Hi ,We have emailed you the coupon for MasthiDeals - #{product.name} - order no : #{order.number}." send_sms(user.phone_no,message) OrderMailer.deliver_voucher(order,product,order.user.email) if order.gift? message = "Hi, #{ order.checkout.bill_address.name } has gifted you #{ product.gift_sms } Please check your email for further details." send_sms(order.giftee_phone_no,message) OrderMailer.deliver_gift_notification(order, product, product.master) OrderMailer.deliver_gift_voucher(order,product) end elsif bought_count<min_number logger.info "deal not on and trying to send placement mail" OrderMailer.deliver_placed(order,user) message = "Hi,Your order no : #{order.number} for MasthiDeals - #{product.name} is successfuly placed. We will email you the voucher when the deals goes live.Order number : ( #{order.number})." send_sms(user.phone_no,message) elsif bought_count==min_number or (bought_count-1)<min_number logger.info "deal on with this placement and trying to send confirmation mail" OrderMailer.deliver_voucher(order,product,order.user.email) if order.gift? message = "Hi, #{ order.checkout.bill_address.name } has gifted you #{ product.gift_sms } Please check your email for further details." send_sms(order.giftee_phone_no,message) OrderMailer.deliver_gift_notification(order, product, product.master) OrderMailer.deliver_gift_voucher(order,product) end message = "Hi ,We have emailed you the coupon for MasthiDeals - #{product.name} - order no : #{order.number}." send_sms(user.phone_no,message) end else OrderMailer.deliver_credit_owed(order) logger.info "credit owed mailed to........." +order.email admin = User.first(:include => :roles, :conditions => ["roles.name = 'admin'"]) UserMailer.deliver_notify_credit_owed_to_admin(admin, order) logger.info "and mailed to admin also........." end else if order.state!='credit_owed' order.line_items.each do |line_item| variant =line_item.variant product=line_item.variant.product old_count=product.currently_bought_count - line_item.quantity if product.currently_bought_count>product.minimum_number and old_count>product.minimum_number logger.info "deal already on and trying to send confirmation mail" # we are sending vouchers after the deal is on message = "Hi ,We have emailed you the coupon for MasthiDeals - #{product.name} - order no : #{order.number}." send_sms(user.phone_no,message) OrderMailer.deliver_voucher(order,product,order.user.email) if order.gift? message = "Hi, #{ order.checkout.bill_address.name } has gifted you #{ product.gift_sms } Please check your email for further details." send_sms(order.giftee_phone_no,message) OrderMailer.deliver_gift_notification(order, product, variant) OrderMailer.deliver_gift_voucher(order,product) end #OrderMailer.deliver_confirm(order) elsif product.currently_bought_count<product.minimum_number logger.info "deal not on and trying to send placement mail" user = User.find_by_email(order.email) OrderMailer.deliver_placed(order,user) message = "Hi,Your order no : #{order.number} for MasthiDeals - #{product.name} is successfuly placed. We will email you the voucher when the deals goes live.Order number : ( #{order.number})." send_sms(user.phone_no,message) elsif product.currently_bought_count==product.minimum_number or old_count<product.minimum_number logger.info "deal on with this placement and trying to send confirmation mail" #sending vouchers for all users before bought line_items_variant = variant.line_items # OrderMailer.deliver_notify_admin(product) line_items_variant.each do |item| if item.order.state == "paid" OrderMailer.deliver_voucher(item.order,product,item.order.user.email) if order.gift? message = "Hi, #{ order.checkout.bill_address.name } has gifted you #{ product.gift_sms } Please check your email for further details." send_sms(order.giftee_phone_no,message) OrderMailer.deliver_gift_notification(item.order, product, variant) OrderMailer.deliver_gift_voucher(item.order,product) end message = "Hi ,We have emailed you the coupon for MasthiDeals - #{product.name} - order no : #{order.number}." send_sms(user.phone_no,message) end end # OrderMailer.deliver_confirm(order) end end else OrderMailer.deliver_credit_owed(order) logger.info "credit owed mailed to........." +order.email admin = User.first(:include => :roles, :conditions => ["roles.name = 'admin'"]) UserMailer.deliver_notify_credit_owed_to_admin(admin, order) logger.info "and mailed to admin also........." end end rescue Exception => e logger.error "problem sending order mails"+e.message end end def send_sms(phone_no,message) query = "INSERT INTO jenooutbox (mobilenumber,message) VALUES('#{ phone_no }','#{message}');" result = ActiveRecord::Base.connection.execute(query) end end def self.sufficient_inventory(line_item) status="available" variant = line_item.variant quantity = line_item.quantity product=variant.product current_deal=DealHistory.find(:first, :conditions=>['product_id=? AND (is_active = ? OR is_side_deal = ?)',line_item.variant.product.id,true,true ]) if product.deal_expiry_date<Time.now status="expired" current_deal.sell_out elsif variant.count_on_hand==0 status= "sold_out" else remaining_quantity = variant.count_on_hand - quantity if (remaining_quantity < 0) status="out_of_stock" end end logger.info "checking for sufficient quantity and result is "+status status end def self.sell_units(order) out_of_stock_items = [] bought_count_flag = 0 order.line_items.each do |line_item| variant = line_item.variant quantity = line_item.quantity product=line_item.product # current_deal=DealHistory.find_by_is_active(true) # mark all of these units as sold and associate them with this order current_deal=DealHistory.find(:first, :conditions=>['product_id=? AND (is_active = ? OR is_side_deal = ?)',product.id,true,true ]) remaining_quantity = variant.count_on_hand - quantity status=self.sufficient_inventory(line_item) if status=="available" logger.info "status is available and updating inventories" quantity.times do order.inventory_units.create(:variant => variant, :state => "sold") end variant.update_attribute(:count_on_hand, remaining_quantity) bought=variant.product.currently_bought_count+quantity if remaining_quantity==0 logger.info "deal is going to be over and hence set sold out" current_deal.sell_out end if variant.product_id == 1060500648 if bought_count_flag == 0 puts "coming if" bought_count_flag = 1 variant.product.update_attribute(:currently_bought_count, variant.product.currently_bought_count + 1) end else variant.product.update_attribute(:currently_bought_count, bought) end elsif status=="out_of_stock" # (quantity + remaining_quantity).times do # order.inventory_units.create(:variant => variant, :state => "sold") # end #line_item.update_attribute(:quantity, quantity + remaining_quantity) out_of_stock_items << {:line_item => line_item, :count => -remaining_quantity} end end out_of_stock_items end def can_restock? %w(sold shipped).include?(state) end def restock! variant.update_attribute(:count_on_hand, variant.count_on_hand + 1) variant.product.update_attribute(:currently_bought_count, variant.product.currently_bought_count-1) delete end # find the specified quantity of units with the specified status def self.find_by_status(variant, quantity, status) variant.inventory_units.find(:all, :conditions => ['status = ? ', status], :limit => quantity) end private def allow_ship? Spree::Config[:allow_backorder_shipping] || (state == 'ready_to_ship') end end
vivekamn/spree
vendor/extensions/masti/app/models/inventory_unit.rb
Ruby
bsd-3-clause
12,372
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveFunctor #-} module Data.Queue ( Queue , empty, singleton, fromList , toList, enqueue, dequeue, enqueueAll ) where import Control.DeepSeq (NFData) import GHC.Generics (Generic) data Queue a = Q [a] [a] deriving (Show, Eq, Functor, NFData, Generic) empty ∷ Queue a empty = Q [] [] singleton ∷ a → Queue a singleton a = Q [a] [] fromList ∷ [a] → Queue a fromList as = Q as [] toList ∷ Queue a → [a] toList (Q h t) = h ++ reverse t enqueue ∷ Queue a → a → Queue a enqueue (Q h t) a = Q (a:h) t enqueueAll ∷ Queue a → [a] → Queue a enqueueAll (Q h t) as = Q (as ++ h) t dequeue ∷ Queue a → Maybe (Queue a, a) dequeue (Q [] []) = Nothing dequeue (Q h []) = let (h':t) = reverse h in Just (Q [] t, h') dequeue (Q h (h':t)) = Just (Q h t, h')
stefan-hoeck/labeled-graph
Data/Queue.hs
Haskell
bsd-3-clause
898
// ***************************************************************************** // // © Component Factory Pty Ltd 2012. All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, 17/267 Nepean Hwy, // Seaford, Vic 3198, Australia and are supplied subject to licence terms. // // Version 4.4.1.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Windows.Forms; using System.ComponentModel; using System.ComponentModel.Design; namespace ComponentFactory.Krypton.Toolkit { /// <summary> /// CollectionEditor used for a KryptonContextMenuItemCollection instance. /// </summary> public class KryptonContextMenuItemCollectionEditor : CollectionEditor { /// <summary> /// Initialize a new instance of the KryptonContextMenuItemCollectionEditor class. /// </summary> public KryptonContextMenuItemCollectionEditor() : base(typeof(KryptonContextMenuItemCollection)) { } /// <summary> /// Gets the data types that this collection editor can contain. /// </summary> /// <returns>An array of data types that this collection can contain.</returns> protected override Type[] CreateNewItemTypes() { return new Type[] { typeof(KryptonContextMenuItem), typeof(KryptonContextMenuSeparator), typeof(KryptonContextMenuHeading) }; } } }
Cocotteseb/Krypton
Source/Krypton Components/ComponentFactory.Krypton.Design/Toolkit/KryptonContextMenuItemCollectionEditor.cs
C#
bsd-3-clause
1,548
// NOTE(jim): // GETTING NESTED SCROLL RIGHT IS DELICATE BUSINESS. THEREFORE THIS COMPONENT // IS THE ONLY PLACE WHERE SCROLL CODE SHOULD BE HANDLED. THANKS. import { Global, css } from '@emotion/core'; import { theme } from '@expo/styleguide'; import * as React from 'react'; import * as Constants from '~/constants/theme'; const STYLES_GLOBAL = css` html { background: ${theme.background.default}; } @media screen and (max-width: ${Constants.breakpoints.mobile}) { html { /* width */ ::-webkit-scrollbar { width: 6px; } /* Track */ ::-webkit-scrollbar-track { background: ${theme.background.default}; } /* Handle */ ::-webkit-scrollbar-thumb { background: ${theme.background.tertiary}; border-radius: 10px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: ${theme.background.quaternary}; } } } `; const STYLES_CONTAINER = css` width: 100%; height: 100vh; overflow: hidden; margin: 0 auto 0 auto; border-right: 1px solid ${theme.border.default}; background: ${theme.background.default}; display: flex; align-items: center; justify-content: space-between; flex-direction: column; @media screen and (max-width: 1440px) { border-left: 0px; border-right: 0px; } @media screen and (max-width: ${Constants.breakpoints.mobile}) { display: block; height: auto; } `; const STYLES_HEADER = css` flex-shrink: 0; width: 100%; @media screen and (min-width: ${Constants.breakpoints.mobile}) { border-bottom: 1px solid ${theme.border.default}; } @media screen and (max-width: ${Constants.breakpoints.mobile}) { position: sticky; top: -57px; z-index: 3; } `; const SHOW_SEARCH_AND_MENU = css` @media screen and (max-width: ${Constants.breakpoints.mobile}) { top: 0px; } `; const STYLES_CONTENT = css` display: flex; align-items: flex-start; margin: 0 auto; justify-content: space-between; width: 100%; height: 100%; min-height: 25%; @media screen and (max-width: ${Constants.breakpoints.mobile}) { height: auto; } `; const STYLES_SIDEBAR = css` flex-shrink: 0; max-width: 280px; height: 100%; overflow: hidden; transition: 200ms ease max-width; background: ${theme.background.canvas}; @media screen and (max-width: 1200px) { max-width: 280px; } @media screen and (max-width: ${Constants.breakpoints.mobile}) { display: none; } `; const STYLES_LEFT = css` border-right: 1px solid ${theme.border.default}; `; const STYLES_RIGHT = css` border-left: 1px solid ${theme.border.default}; background-color: ${theme.background.default}; `; const STYLES_CENTER = css` background: ${theme.background.default}; min-width: 5%; width: 100%; height: 100%; overflow: hidden; display: flex; @media screen and (max-width: ${Constants.breakpoints.mobile}) { height: auto; overflow: auto; } `; // NOTE(jim): // All the other components tame the UI. this one allows a container to scroll. const STYLES_SCROLL_CONTAINER = css` height: 100%; width: 100%; padding-bottom: 36px; overflow-y: scroll; overflow-x: hidden; -webkit-overflow-scrolling: touch; /* width */ ::-webkit-scrollbar { width: 6px; } /* Track */ ::-webkit-scrollbar-track { background: transparent; cursor: pointer; } /* Handle */ ::-webkit-scrollbar-thumb { background: ${theme.background.tertiary}; border-radius: 10px; } /* Handle on hover */ ::-webkit-scrollbar-thumb:hover { background: ${theme.background.quaternary}; } @media screen and (max-width: ${Constants.breakpoints.mobile}) { overflow-y: auto; } `; const STYLES_CENTER_WRAPPER = css` max-width: 1200px; margin: auto; `; type ScrollContainerProps = { scrollPosition?: number; scrollHandler?: () => void; }; class ScrollContainer extends React.Component<ScrollContainerProps> { scrollRef = React.createRef<HTMLDivElement>(); componentDidMount() { if (this.props.scrollPosition && this.scrollRef.current) { this.scrollRef.current.scrollTop = this.props.scrollPosition; } } public getScrollTop = () => { return this.scrollRef.current?.scrollTop ?? 0; }; public getScrollRef = () => { return this.scrollRef; }; render() { return ( <div css={STYLES_SCROLL_CONTAINER} ref={this.scrollRef} onScroll={this.props.scrollHandler}> {this.props.children} </div> ); } } type Props = { onContentScroll?: (scrollTop: number) => void; isMenuActive: boolean; tocVisible: boolean; isMobileSearchActive: boolean; header: React.ReactNode; sidebarScrollPosition: number; sidebar: React.ReactNode; sidebarRight: React.ReactElement; }; export default class DocumentationNestedScrollLayout extends React.Component<Props> { static defaultProps = { sidebarScrollPosition: 0, }; sidebarRef = React.createRef<ScrollContainer>(); contentRef = React.createRef<ScrollContainer>(); sidebarRightRef = React.createRef<ScrollContainer>(); public getSidebarScrollTop = () => { return this.sidebarRef.current?.getScrollTop() ?? 0; }; public getContentScrollTop = () => { return this.contentRef.current?.getScrollTop() ?? 0; }; render() { const { isMobileSearchActive, isMenuActive, sidebarScrollPosition } = this.props; if (isMenuActive) { window.scrollTo(0, 0); } return ( <div css={STYLES_CONTAINER}> <Global styles={STYLES_GLOBAL} /> <div css={[STYLES_HEADER, (isMobileSearchActive || isMenuActive) && SHOW_SEARCH_AND_MENU]}> {this.props.header} </div> <div css={STYLES_CONTENT}> <div css={[STYLES_SIDEBAR, STYLES_LEFT]}> <ScrollContainer ref={this.sidebarRef} scrollPosition={sidebarScrollPosition}> {this.props.sidebar} </ScrollContainer> </div> <div css={STYLES_CENTER}> <ScrollContainer ref={this.contentRef} scrollHandler={this.scrollHandler}> <div css={STYLES_CENTER_WRAPPER}>{this.props.children}</div> </ScrollContainer> </div> {this.props.tocVisible && ( <div css={[STYLES_SIDEBAR, STYLES_RIGHT]}> <ScrollContainer ref={this.sidebarRightRef}> {React.cloneElement(this.props.sidebarRight, { selfRef: this.sidebarRightRef, contentRef: this.contentRef, })} </ScrollContainer> </div> )} </div> </div> ); } private scrollHandler = () => { this.props.onContentScroll && this.props.onContentScroll(this.getContentScrollTop()); }; }
exponent/exponent
docs/components/DocumentationNestedScrollLayout.tsx
TypeScript
bsd-3-clause
6,797
# See e.g. http://stackoverflow.com/a/14076841/931303 try: import pymysql pymysql.install_as_MySQLdb() except ImportError: pass
jorgecarleitao/public-contracts
main/__init__.py
Python
bsd-3-clause
140
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>HiddenInputElement class - polymer_app_layout.behaviors library - Dart API</title> <!-- required because all the links are pseudo-absolute --> <base href=".."> <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="static-assets/prettify.css"> <link rel="stylesheet" href="static-assets/css/bootstrap.min.css"> <link rel="stylesheet" href="static-assets/styles.css"> <meta name="description" content="API docs for the HiddenInputElement class from the polymer_app_layout.behaviors library, for the Dart programming language."> <link rel="icon" href="static-assets/favicon.png"> <!-- Do not remove placeholder --> <!-- Header Placeholder --> </head> <body> <div id="overlay-under-drawer"></div> <header class="container-fluid" id="title"> <nav class="navbar navbar-fixed-top"> <div class="container"> <button id="sidenav-left-toggle" type="button">&nbsp;</button> <ol class="breadcrumbs gt-separated hidden-xs"> <li><a href="index.html">polymer_app_layout_template</a></li> <li><a href="polymer_app_layout.behaviors/polymer_app_layout.behaviors-library.html">polymer_app_layout.behaviors</a></li> <li class="self-crumb">HiddenInputElement</li> </ol> <div class="self-name">HiddenInputElement</div> </div> </nav> <div class="container masthead"> <ol class="breadcrumbs gt-separated visible-xs"> <li><a href="index.html">polymer_app_layout_template</a></li> <li><a href="polymer_app_layout.behaviors/polymer_app_layout.behaviors-library.html">polymer_app_layout.behaviors</a></li> <li class="self-crumb">HiddenInputElement</li> </ol> <div class="title-description"> <h1 class="title"> <div class="kind">class</div> HiddenInputElement </h1> <!-- p class="subtitle"> Hidden input which is not intended to be seen or edited by the user. </p --> </div> <ul class="subnav"> <li><a href="polymer_app_layout.behaviors/HiddenInputElement-class.html#constructors">Constructors</a></li> </ul> </div> </header> <div class="container body"> <div class="col-xs-6 col-sm-3 col-md-3 sidebar sidebar-offcanvas-left"> <h5><a href="index.html">polymer_app_layout_template</a></h5> <h5><a href="polymer_app_layout.behaviors/polymer_app_layout.behaviors-library.html">polymer_app_layout.behaviors</a></h5> <ol> <li class="section-title"><a href="polymer_app_layout.behaviors/polymer_app_layout.behaviors-library.html#typedefs">Typedefs</a></li> <li><a href="polymer_app_layout.behaviors/DatabaseCallback.html">DatabaseCallback</a></li> <li><a href="polymer_app_layout.behaviors/EventListener.html">EventListener</a></li> <li><a href="polymer_app_layout.behaviors/FontFaceSetForEachCallback.html">FontFaceSetForEachCallback</a></li> <li><a href="polymer_app_layout.behaviors/HeadersForEachCallback.html">HeadersForEachCallback</a></li> <li><a href="polymer_app_layout.behaviors/MediaDeviceInfoCallback.html">MediaDeviceInfoCallback</a></li> <li><a href="polymer_app_layout.behaviors/MediaStreamTrackSourcesCallback.html">MediaStreamTrackSourcesCallback</a></li> <li><a href="polymer_app_layout.behaviors/MetadataCallback.html">MetadataCallback</a></li> <li><a href="polymer_app_layout.behaviors/MidiErrorCallback.html">MidiErrorCallback</a></li> <li><a href="polymer_app_layout.behaviors/MidiSuccessCallback.html">MidiSuccessCallback</a></li> <li><a href="polymer_app_layout.behaviors/MutationCallback.html">MutationCallback</a></li> <li><a href="polymer_app_layout.behaviors/RequestAnimationFrameCallback.html">RequestAnimationFrameCallback</a></li> <li><a href="polymer_app_layout.behaviors/RtcStatsCallback.html">RtcStatsCallback</a></li> <li><a href="polymer_app_layout.behaviors/StorageErrorCallback.html">StorageErrorCallback</a></li> <li><a href="polymer_app_layout.behaviors/StorageQuotaCallback.html">StorageQuotaCallback</a></li> <li><a href="polymer_app_layout.behaviors/StorageUsageCallback.html">StorageUsageCallback</a></li> <li><a href="polymer_app_layout.behaviors/TimeoutHandler.html">TimeoutHandler</a></li> <li><a href="polymer_app_layout.behaviors/VoidCallback.html">VoidCallback</a></li> <li class="section-title"><a href="polymer_app_layout.behaviors/polymer_app_layout.behaviors-library.html#properties">Properties</a></li> <li><a href="polymer_app_layout.behaviors/document.html">document</a></li> <li><a href="polymer_app_layout.behaviors/htmlBlinkMap.html">htmlBlinkMap</a></li> <li><a href="polymer_app_layout.behaviors/window.html">window</a></li> <li class="section-title"><a href="polymer_app_layout.behaviors/polymer_app_layout.behaviors-library.html#functions">Functions</a></li> <li><a href="polymer_app_layout.behaviors/make_dart_rectangle.html">make_dart_rectangle</a></li> <li><a href="polymer_app_layout.behaviors/query.html">query</a></li> <li><a href="polymer_app_layout.behaviors/queryAll.html">queryAll</a></li> <li><a href="polymer_app_layout.behaviors/querySelector.html">querySelector</a></li> <li><a href="polymer_app_layout.behaviors/querySelectorAll.html">querySelectorAll</a></li> <li><a href="polymer_app_layout.behaviors/spawnDomUri.html">spawnDomUri</a></li> <li><a href="polymer_app_layout.behaviors/unwrap_jso.html">unwrap_jso</a></li> <li><a href="polymer_app_layout.behaviors/wrap_jso.html">wrap_jso</a></li> <li><a href="polymer_app_layout.behaviors/wrap_jso_list.html">wrap_jso_list</a></li> <li class="section-title"><a href="polymer_app_layout.behaviors/polymer_app_layout.behaviors-library.html#classes">Classes</a></li> <li><a href="polymer_app_layout.behaviors/AbstractWorker-class.html">AbstractWorker</a></li> <li><a href="polymer_app_layout.behaviors/AnchorElement-class.html">AnchorElement</a></li> <li><a href="polymer_app_layout.behaviors/Animation-class.html">Animation</a></li> <li><a href="polymer_app_layout.behaviors/AnimationEffect-class.html">AnimationEffect</a></li> <li><a href="polymer_app_layout.behaviors/AnimationEvent-class.html">AnimationEvent</a></li> <li><a href="polymer_app_layout.behaviors/AnimationNode-class.html">AnimationNode</a></li> <li><a href="polymer_app_layout.behaviors/AnimationPlayer-class.html">AnimationPlayer</a></li> <li><a href="polymer_app_layout.behaviors/AnimationPlayerEvent-class.html">AnimationPlayerEvent</a></li> <li><a href="polymer_app_layout.behaviors/AnimationTimeline-class.html">AnimationTimeline</a></li> <li><a href="polymer_app_layout.behaviors/ApplicationCache-class.html">ApplicationCache</a></li> <li><a href="polymer_app_layout.behaviors/ApplicationCacheErrorEvent-class.html">ApplicationCacheErrorEvent</a></li> <li><a href="polymer_app_layout.behaviors/AreaElement-class.html">AreaElement</a></li> <li><a href="polymer_app_layout.behaviors/AudioElement-class.html">AudioElement</a></li> <li><a href="polymer_app_layout.behaviors/AudioTrack-class.html">AudioTrack</a></li> <li><a href="polymer_app_layout.behaviors/AudioTrackList-class.html">AudioTrackList</a></li> <li><a href="polymer_app_layout.behaviors/AutocompleteErrorEvent-class.html">AutocompleteErrorEvent</a></li> <li><a href="polymer_app_layout.behaviors/BarProp-class.html">BarProp</a></li> <li><a href="polymer_app_layout.behaviors/BaseElement-class.html">BaseElement</a></li> <li><a href="polymer_app_layout.behaviors/BatteryManager-class.html">BatteryManager</a></li> <li><a href="polymer_app_layout.behaviors/BeforeUnloadEvent-class.html">BeforeUnloadEvent</a></li> <li><a href="polymer_app_layout.behaviors/Blob-class.html">Blob</a></li> <li><a href="polymer_app_layout.behaviors/Body-class.html">Body</a></li> <li><a href="polymer_app_layout.behaviors/BodyElement-class.html">BodyElement</a></li> <li><a href="polymer_app_layout.behaviors/BRElement-class.html">BRElement</a></li> <li><a href="polymer_app_layout.behaviors/ButtonElement-class.html">ButtonElement</a></li> <li><a href="polymer_app_layout.behaviors/ButtonInputElement-class.html">ButtonInputElement</a></li> <li><a href="polymer_app_layout.behaviors/CacheStorage-class.html">CacheStorage</a></li> <li><a href="polymer_app_layout.behaviors/Canvas2DContextAttributes-class.html">Canvas2DContextAttributes</a></li> <li><a href="polymer_app_layout.behaviors/CanvasElement-class.html">CanvasElement</a></li> <li><a href="polymer_app_layout.behaviors/CanvasGradient-class.html">CanvasGradient</a></li> <li><a href="polymer_app_layout.behaviors/CanvasImageSource-class.html">CanvasImageSource</a></li> <li><a href="polymer_app_layout.behaviors/CanvasPattern-class.html">CanvasPattern</a></li> <li><a href="polymer_app_layout.behaviors/CanvasRenderingContext-class.html">CanvasRenderingContext</a></li> <li><a href="polymer_app_layout.behaviors/CanvasRenderingContext2D-class.html">CanvasRenderingContext2D</a></li> <li><a href="polymer_app_layout.behaviors/CDataSection-class.html">CDataSection</a></li> <li><a href="polymer_app_layout.behaviors/CharacterData-class.html">CharacterData</a></li> <li><a href="polymer_app_layout.behaviors/CheckboxInputElement-class.html">CheckboxInputElement</a></li> <li><a href="polymer_app_layout.behaviors/ChildNode-class.html">ChildNode</a></li> <li><a href="polymer_app_layout.behaviors/CircularGeofencingRegion-class.html">CircularGeofencingRegion</a></li> <li><a href="polymer_app_layout.behaviors/CloseEvent-class.html">CloseEvent</a></li> <li><a href="polymer_app_layout.behaviors/Comment-class.html">Comment</a></li> <li><a href="polymer_app_layout.behaviors/CompositionEvent-class.html">CompositionEvent</a></li> <li><a href="polymer_app_layout.behaviors/Console-class.html">Console</a></li> <li><a href="polymer_app_layout.behaviors/ConsoleBase-class.html">ConsoleBase</a></li> <li><a href="polymer_app_layout.behaviors/ContentElement-class.html">ContentElement</a></li> <li><a href="polymer_app_layout.behaviors/Coordinates-class.html">Coordinates</a></li> <li><a href="polymer_app_layout.behaviors/Credential-class.html">Credential</a></li> <li><a href="polymer_app_layout.behaviors/CredentialsContainer-class.html">CredentialsContainer</a></li> <li><a href="polymer_app_layout.behaviors/Crypto-class.html">Crypto</a></li> <li><a href="polymer_app_layout.behaviors/CryptoKey-class.html">CryptoKey</a></li> <li><a href="polymer_app_layout.behaviors/Css-class.html">Css</a></li> <li><a href="polymer_app_layout.behaviors/CssCharsetRule-class.html">CssCharsetRule</a></li> <li><a href="polymer_app_layout.behaviors/CssClassSet-class.html">CssClassSet</a></li> <li><a href="polymer_app_layout.behaviors/CssFilterRule-class.html">CssFilterRule</a></li> <li><a href="polymer_app_layout.behaviors/CssFontFaceRule-class.html">CssFontFaceRule</a></li> <li><a href="polymer_app_layout.behaviors/CssImportRule-class.html">CssImportRule</a></li> <li><a href="polymer_app_layout.behaviors/CssKeyframeRule-class.html">CssKeyframeRule</a></li> <li><a href="polymer_app_layout.behaviors/CssKeyframesRule-class.html">CssKeyframesRule</a></li> <li><a href="polymer_app_layout.behaviors/CssMediaRule-class.html">CssMediaRule</a></li> <li><a href="polymer_app_layout.behaviors/CssPageRule-class.html">CssPageRule</a></li> <li><a href="polymer_app_layout.behaviors/CssRect-class.html">CssRect</a></li> <li><a href="polymer_app_layout.behaviors/CssRule-class.html">CssRule</a></li> <li><a href="polymer_app_layout.behaviors/CssStyleDeclaration-class.html">CssStyleDeclaration</a></li> <li><a href="polymer_app_layout.behaviors/CssStyleDeclarationBase-class.html">CssStyleDeclarationBase</a></li> <li><a href="polymer_app_layout.behaviors/CssStyleRule-class.html">CssStyleRule</a></li> <li><a href="polymer_app_layout.behaviors/CssStyleSheet-class.html">CssStyleSheet</a></li> <li><a href="polymer_app_layout.behaviors/CssSupportsRule-class.html">CssSupportsRule</a></li> <li><a href="polymer_app_layout.behaviors/CssViewportRule-class.html">CssViewportRule</a></li> <li><a href="polymer_app_layout.behaviors/CustomEvent-class.html">CustomEvent</a></li> <li><a href="polymer_app_layout.behaviors/CustomStream-class.html">CustomStream</a></li> <li><a href="polymer_app_layout.behaviors/DataListElement-class.html">DataListElement</a></li> <li><a href="polymer_app_layout.behaviors/DataTransfer-class.html">DataTransfer</a></li> <li><a href="polymer_app_layout.behaviors/DataTransferItem-class.html">DataTransferItem</a></li> <li><a href="polymer_app_layout.behaviors/DataTransferItemList-class.html">DataTransferItemList</a></li> <li><a href="polymer_app_layout.behaviors/DateInputElement-class.html">DateInputElement</a></li> <li><a href="polymer_app_layout.behaviors/DedicatedWorkerGlobalScope-class.html">DedicatedWorkerGlobalScope</a></li> <li><a href="polymer_app_layout.behaviors/DeprecatedStorageInfo-class.html">DeprecatedStorageInfo</a></li> <li><a href="polymer_app_layout.behaviors/DeprecatedStorageQuota-class.html">DeprecatedStorageQuota</a></li> <li><a href="polymer_app_layout.behaviors/DetailsElement-class.html">DetailsElement</a></li> <li><a href="polymer_app_layout.behaviors/DeviceAcceleration-class.html">DeviceAcceleration</a></li> <li><a href="polymer_app_layout.behaviors/DeviceLightEvent-class.html">DeviceLightEvent</a></li> <li><a href="polymer_app_layout.behaviors/DeviceMotionEvent-class.html">DeviceMotionEvent</a></li> <li><a href="polymer_app_layout.behaviors/DeviceOrientationEvent-class.html">DeviceOrientationEvent</a></li> <li><a href="polymer_app_layout.behaviors/DeviceRotationRate-class.html">DeviceRotationRate</a></li> <li><a href="polymer_app_layout.behaviors/DialogElement-class.html">DialogElement</a></li> <li><a href="polymer_app_layout.behaviors/Dimension-class.html">Dimension</a></li> <li><a href="polymer_app_layout.behaviors/DirectoryEntry-class.html">DirectoryEntry</a></li> <li><a href="polymer_app_layout.behaviors/DirectoryReader-class.html">DirectoryReader</a></li> <li><a href="polymer_app_layout.behaviors/DivElement-class.html">DivElement</a></li> <li><a href="polymer_app_layout.behaviors/DListElement-class.html">DListElement</a></li> <li><a href="polymer_app_layout.behaviors/Document-class.html">Document</a></li> <li><a href="polymer_app_layout.behaviors/DocumentFragment-class.html">DocumentFragment</a></li> <li><a href="polymer_app_layout.behaviors/DomError-class.html">DomError</a></li> <li><a href="polymer_app_layout.behaviors/DomException-class.html">DomException</a></li> <li><a href="polymer_app_layout.behaviors/DomImplementation-class.html">DomImplementation</a></li> <li><a href="polymer_app_layout.behaviors/DomIterator-class.html">DomIterator</a></li> <li><a href="polymer_app_layout.behaviors/DomMatrix-class.html">DomMatrix</a></li> <li><a href="polymer_app_layout.behaviors/DomMatrixReadOnly-class.html">DomMatrixReadOnly</a></li> <li><a href="polymer_app_layout.behaviors/DomParser-class.html">DomParser</a></li> <li><a href="polymer_app_layout.behaviors/DomPoint-class.html">DomPoint</a></li> <li><a href="polymer_app_layout.behaviors/DomPointReadOnly-class.html">DomPointReadOnly</a></li> <li><a href="polymer_app_layout.behaviors/DomRectReadOnly-class.html">DomRectReadOnly</a></li> <li><a href="polymer_app_layout.behaviors/DomSettableTokenList-class.html">DomSettableTokenList</a></li> <li><a href="polymer_app_layout.behaviors/DomStringList-class.html">DomStringList</a></li> <li><a href="polymer_app_layout.behaviors/DomStringMap-class.html">DomStringMap</a></li> <li><a href="polymer_app_layout.behaviors/DomTokenList-class.html">DomTokenList</a></li> <li><a href="polymer_app_layout.behaviors/Element-class.html">Element</a></li> <li><a href="polymer_app_layout.behaviors/ElementEvents-class.html">ElementEvents</a></li> <li><a href="polymer_app_layout.behaviors/ElementList-class.html">ElementList</a></li> <li><a href="polymer_app_layout.behaviors/ElementStream-class.html">ElementStream</a></li> <li><a href="polymer_app_layout.behaviors/ElementUpgrader-class.html">ElementUpgrader</a></li> <li><a href="polymer_app_layout.behaviors/EmailInputElement-class.html">EmailInputElement</a></li> <li><a href="polymer_app_layout.behaviors/EmbedElement-class.html">EmbedElement</a></li> <li><a href="polymer_app_layout.behaviors/Entry-class.html">Entry</a></li> <li><a href="polymer_app_layout.behaviors/ErrorEvent-class.html">ErrorEvent</a></li> <li><a href="polymer_app_layout.behaviors/Event-class.html">Event</a></li> <li><a href="polymer_app_layout.behaviors/Events-class.html">Events</a></li> <li><a href="polymer_app_layout.behaviors/EventSource-class.html">EventSource</a></li> <li><a href="polymer_app_layout.behaviors/EventStreamProvider-class.html">EventStreamProvider</a></li> <li><a href="polymer_app_layout.behaviors/EventTarget-class.html">EventTarget</a></li> <li><a href="polymer_app_layout.behaviors/ExtendableEvent-class.html">ExtendableEvent</a></li> <li><a href="polymer_app_layout.behaviors/FederatedCredential-class.html">FederatedCredential</a></li> <li><a href="polymer_app_layout.behaviors/FetchEvent-class.html">FetchEvent</a></li> <li><a href="polymer_app_layout.behaviors/FieldSetElement-class.html">FieldSetElement</a></li> <li><a href="polymer_app_layout.behaviors/File-class.html">File</a></li> <li><a href="polymer_app_layout.behaviors/FileEntry-class.html">FileEntry</a></li> <li><a href="polymer_app_layout.behaviors/FileError-class.html">FileError</a></li> <li><a href="polymer_app_layout.behaviors/FileList-class.html">FileList</a></li> <li><a href="polymer_app_layout.behaviors/FileReader-class.html">FileReader</a></li> <li><a href="polymer_app_layout.behaviors/FileStream-class.html">FileStream</a></li> <li><a href="polymer_app_layout.behaviors/FileSystem-class.html">FileSystem</a></li> <li><a href="polymer_app_layout.behaviors/FileUploadInputElement-class.html">FileUploadInputElement</a></li> <li><a href="polymer_app_layout.behaviors/FileWriter-class.html">FileWriter</a></li> <li><a href="polymer_app_layout.behaviors/FixedSizeListIterator-class.html">FixedSizeListIterator</a></li> <li><a href="polymer_app_layout.behaviors/FocusEvent-class.html">FocusEvent</a></li> <li><a href="polymer_app_layout.behaviors/FontFace-class.html">FontFace</a></li> <li><a href="polymer_app_layout.behaviors/FontFaceSet-class.html">FontFaceSet</a></li> <li><a href="polymer_app_layout.behaviors/FontFaceSetLoadEvent-class.html">FontFaceSetLoadEvent</a></li> <li><a href="polymer_app_layout.behaviors/FormData-class.html">FormData</a></li> <li><a href="polymer_app_layout.behaviors/FormElement-class.html">FormElement</a></li> <li><a href="polymer_app_layout.behaviors/Gamepad-class.html">Gamepad</a></li> <li><a href="polymer_app_layout.behaviors/GamepadButton-class.html">GamepadButton</a></li> <li><a href="polymer_app_layout.behaviors/GamepadEvent-class.html">GamepadEvent</a></li> <li><a href="polymer_app_layout.behaviors/Geofencing-class.html">Geofencing</a></li> <li><a href="polymer_app_layout.behaviors/GeofencingRegion-class.html">GeofencingRegion</a></li> <li><a href="polymer_app_layout.behaviors/Geolocation-class.html">Geolocation</a></li> <li><a href="polymer_app_layout.behaviors/Geoposition-class.html">Geoposition</a></li> <li><a href="polymer_app_layout.behaviors/GlobalEventHandlers-class.html">GlobalEventHandlers</a></li> <li><a href="polymer_app_layout.behaviors/HashChangeEvent-class.html">HashChangeEvent</a></li> <li><a href="polymer_app_layout.behaviors/HeadElement-class.html">HeadElement</a></li> <li><a href="polymer_app_layout.behaviors/Headers-class.html">Headers</a></li> <li><a href="polymer_app_layout.behaviors/HeadingElement-class.html">HeadingElement</a></li> <li><a href="polymer_app_layout.behaviors/HiddenInputElement-class.html">HiddenInputElement</a></li> <li><a href="polymer_app_layout.behaviors/History-class.html">History</a></li> <li><a href="polymer_app_layout.behaviors/HistoryBase-class.html">HistoryBase</a></li> <li><a href="polymer_app_layout.behaviors/HRElement-class.html">HRElement</a></li> <li><a href="polymer_app_layout.behaviors/HtmlCollection-class.html">HtmlCollection</a></li> <li><a href="polymer_app_layout.behaviors/HtmlDocument-class.html">HtmlDocument</a></li> <li><a href="polymer_app_layout.behaviors/HtmlElement-class.html">HtmlElement</a></li> <li><a href="polymer_app_layout.behaviors/HtmlFormControlsCollection-class.html">HtmlFormControlsCollection</a></li> <li><a href="polymer_app_layout.behaviors/HtmlHtmlElement-class.html">HtmlHtmlElement</a></li> <li><a href="polymer_app_layout.behaviors/HtmlOptionsCollection-class.html">HtmlOptionsCollection</a></li> <li><a href="polymer_app_layout.behaviors/HttpRequest-class.html">HttpRequest</a></li> <li><a href="polymer_app_layout.behaviors/HttpRequestEventTarget-class.html">HttpRequestEventTarget</a></li> <li><a href="polymer_app_layout.behaviors/HttpRequestUpload-class.html">HttpRequestUpload</a></li> <li><a href="polymer_app_layout.behaviors/IconBehavior-class.html">IconBehavior</a></li> <li><a href="polymer_app_layout.behaviors/IFrameElement-class.html">IFrameElement</a></li> <li><a href="polymer_app_layout.behaviors/ImageBitmap-class.html">ImageBitmap</a></li> <li><a href="polymer_app_layout.behaviors/ImageButtonInputElement-class.html">ImageButtonInputElement</a></li> <li><a href="polymer_app_layout.behaviors/ImageData-class.html">ImageData</a></li> <li><a href="polymer_app_layout.behaviors/ImageElement-class.html">ImageElement</a></li> <li><a href="polymer_app_layout.behaviors/ImmutableListMixin-class.html">ImmutableListMixin</a></li> <li><a href="polymer_app_layout.behaviors/InjectedScriptHost-class.html">InjectedScriptHost</a></li> <li><a href="polymer_app_layout.behaviors/InputElement-class.html">InputElement</a></li> <li><a href="polymer_app_layout.behaviors/InputElementBase-class.html">InputElementBase</a></li> <li><a href="polymer_app_layout.behaviors/InputMethodContext-class.html">InputMethodContext</a></li> <li><a href="polymer_app_layout.behaviors/InstallEvent-class.html">InstallEvent</a></li> <li><a href="polymer_app_layout.behaviors/KeyboardEvent-class.html">KeyboardEvent</a></li> <li><a href="polymer_app_layout.behaviors/KeyboardEventStream-class.html">KeyboardEventStream</a></li> <li><a href="polymer_app_layout.behaviors/KeyCode-class.html">KeyCode</a></li> <li><a href="polymer_app_layout.behaviors/KeyEvent-class.html">KeyEvent</a></li> <li><a href="polymer_app_layout.behaviors/KeygenElement-class.html">KeygenElement</a></li> <li><a href="polymer_app_layout.behaviors/KeyLocation-class.html">KeyLocation</a></li> <li><a href="polymer_app_layout.behaviors/LabelElement-class.html">LabelElement</a></li> <li><a href="polymer_app_layout.behaviors/LeftNavBehavior-class.html">LeftNavBehavior</a></li> <li><a href="polymer_app_layout.behaviors/LegendElement-class.html">LegendElement</a></li> <li><a href="polymer_app_layout.behaviors/LIElement-class.html">LIElement</a></li> <li><a href="polymer_app_layout.behaviors/LinkElement-class.html">LinkElement</a></li> <li><a href="polymer_app_layout.behaviors/LocalCredential-class.html">LocalCredential</a></li> <li><a href="polymer_app_layout.behaviors/LocalDateTimeInputElement-class.html">LocalDateTimeInputElement</a></li> <li><a href="polymer_app_layout.behaviors/Location-class.html">Location</a></li> <li><a href="polymer_app_layout.behaviors/LocationBase-class.html">LocationBase</a></li> <li><a href="polymer_app_layout.behaviors/MapElement-class.html">MapElement</a></li> <li><a href="polymer_app_layout.behaviors/MediaController-class.html">MediaController</a></li> <li><a href="polymer_app_layout.behaviors/MediaDeviceInfo-class.html">MediaDeviceInfo</a></li> <li><a href="polymer_app_layout.behaviors/MediaElement-class.html">MediaElement</a></li> <li><a href="polymer_app_layout.behaviors/MediaError-class.html">MediaError</a></li> <li><a href="polymer_app_layout.behaviors/MediaKeyError-class.html">MediaKeyError</a></li> <li><a href="polymer_app_layout.behaviors/MediaKeyEvent-class.html">MediaKeyEvent</a></li> <li><a href="polymer_app_layout.behaviors/MediaKeyMessageEvent-class.html">MediaKeyMessageEvent</a></li> <li><a href="polymer_app_layout.behaviors/MediaKeyNeededEvent-class.html">MediaKeyNeededEvent</a></li> <li><a href="polymer_app_layout.behaviors/MediaKeys-class.html">MediaKeys</a></li> <li><a href="polymer_app_layout.behaviors/MediaKeySession-class.html">MediaKeySession</a></li> <li><a href="polymer_app_layout.behaviors/MediaList-class.html">MediaList</a></li> <li><a href="polymer_app_layout.behaviors/MediaQueryList-class.html">MediaQueryList</a></li> <li><a href="polymer_app_layout.behaviors/MediaQueryListEvent-class.html">MediaQueryListEvent</a></li> <li><a href="polymer_app_layout.behaviors/MediaSource-class.html">MediaSource</a></li> <li><a href="polymer_app_layout.behaviors/MediaStream-class.html">MediaStream</a></li> <li><a href="polymer_app_layout.behaviors/MediaStreamEvent-class.html">MediaStreamEvent</a></li> <li><a href="polymer_app_layout.behaviors/MediaStreamTrack-class.html">MediaStreamTrack</a></li> <li><a href="polymer_app_layout.behaviors/MediaStreamTrackEvent-class.html">MediaStreamTrackEvent</a></li> <li><a href="polymer_app_layout.behaviors/MemoryInfo-class.html">MemoryInfo</a></li> <li><a href="polymer_app_layout.behaviors/MenuElement-class.html">MenuElement</a></li> <li><a href="polymer_app_layout.behaviors/MenuItemElement-class.html">MenuItemElement</a></li> <li><a href="polymer_app_layout.behaviors/MessageChannel-class.html">MessageChannel</a></li> <li><a href="polymer_app_layout.behaviors/MessageEvent-class.html">MessageEvent</a></li> <li><a href="polymer_app_layout.behaviors/MessagePort-class.html">MessagePort</a></li> <li><a href="polymer_app_layout.behaviors/Metadata-class.html">Metadata</a></li> <li><a href="polymer_app_layout.behaviors/MetaElement-class.html">MetaElement</a></li> <li><a href="polymer_app_layout.behaviors/MeterElement-class.html">MeterElement</a></li> <li><a href="polymer_app_layout.behaviors/MidiAccess-class.html">MidiAccess</a></li> <li><a href="polymer_app_layout.behaviors/MidiConnectionEvent-class.html">MidiConnectionEvent</a></li> <li><a href="polymer_app_layout.behaviors/MidiInput-class.html">MidiInput</a></li> <li><a href="polymer_app_layout.behaviors/MidiInputMap-class.html">MidiInputMap</a></li> <li><a href="polymer_app_layout.behaviors/MidiMessageEvent-class.html">MidiMessageEvent</a></li> <li><a href="polymer_app_layout.behaviors/MidiOutput-class.html">MidiOutput</a></li> <li><a href="polymer_app_layout.behaviors/MidiOutputMap-class.html">MidiOutputMap</a></li> <li><a href="polymer_app_layout.behaviors/MidiPort-class.html">MidiPort</a></li> <li><a href="polymer_app_layout.behaviors/MimeType-class.html">MimeType</a></li> <li><a href="polymer_app_layout.behaviors/MimeTypeArray-class.html">MimeTypeArray</a></li> <li><a href="polymer_app_layout.behaviors/ModElement-class.html">ModElement</a></li> <li><a href="polymer_app_layout.behaviors/MonthInputElement-class.html">MonthInputElement</a></li> <li><a href="polymer_app_layout.behaviors/MouseEvent-class.html">MouseEvent</a></li> <li><a href="polymer_app_layout.behaviors/MutationObserver-class.html">MutationObserver</a></li> <li><a href="polymer_app_layout.behaviors/MutationRecord-class.html">MutationRecord</a></li> <li><a href="polymer_app_layout.behaviors/Navigator-class.html">Navigator</a></li> <li><a href="polymer_app_layout.behaviors/NavigatorCpu-class.html">NavigatorCpu</a></li> <li><a href="polymer_app_layout.behaviors/NavigatorID-class.html">NavigatorID</a></li> <li><a href="polymer_app_layout.behaviors/NavigatorLanguage-class.html">NavigatorLanguage</a></li> <li><a href="polymer_app_layout.behaviors/NavigatorOnLine-class.html">NavigatorOnLine</a></li> <li><a href="polymer_app_layout.behaviors/NavigatorUserMediaError-class.html">NavigatorUserMediaError</a></li> <li><a href="polymer_app_layout.behaviors/NetworkInformation-class.html">NetworkInformation</a></li> <li><a href="polymer_app_layout.behaviors/Node-class.html">Node</a></li> <li><a href="polymer_app_layout.behaviors/NodeFilter-class.html">NodeFilter</a></li> <li><a href="polymer_app_layout.behaviors/NodeIterator-class.html">NodeIterator</a></li> <li><a href="polymer_app_layout.behaviors/NodeList-class.html">NodeList</a></li> <li><a href="polymer_app_layout.behaviors/NodeTreeSanitizer-class.html">NodeTreeSanitizer</a></li> <li><a href="polymer_app_layout.behaviors/NodeValidator-class.html">NodeValidator</a></li> <li><a href="polymer_app_layout.behaviors/NodeValidatorBuilder-class.html">NodeValidatorBuilder</a></li> <li><a href="polymer_app_layout.behaviors/Notification-class.html">Notification</a></li> <li><a href="polymer_app_layout.behaviors/NumberInputElement-class.html">NumberInputElement</a></li> <li><a href="polymer_app_layout.behaviors/ObjectElement-class.html">ObjectElement</a></li> <li><a href="polymer_app_layout.behaviors/OListElement-class.html">OListElement</a></li> <li><a href="polymer_app_layout.behaviors/OptGroupElement-class.html">OptGroupElement</a></li> <li><a href="polymer_app_layout.behaviors/OptionElement-class.html">OptionElement</a></li> <li><a href="polymer_app_layout.behaviors/OutputElement-class.html">OutputElement</a></li> <li><a href="polymer_app_layout.behaviors/OverflowEvent-class.html">OverflowEvent</a></li> <li><a href="polymer_app_layout.behaviors/PageTransitionEvent-class.html">PageTransitionEvent</a></li> <li><a href="polymer_app_layout.behaviors/ParagraphElement-class.html">ParagraphElement</a></li> <li><a href="polymer_app_layout.behaviors/ParamElement-class.html">ParamElement</a></li> <li><a href="polymer_app_layout.behaviors/ParentNode-class.html">ParentNode</a></li> <li><a href="polymer_app_layout.behaviors/PasswordInputElement-class.html">PasswordInputElement</a></li> <li><a href="polymer_app_layout.behaviors/Path2D-class.html">Path2D</a></li> <li><a href="polymer_app_layout.behaviors/Performance-class.html">Performance</a></li> <li><a href="polymer_app_layout.behaviors/PerformanceEntry-class.html">PerformanceEntry</a></li> <li><a href="polymer_app_layout.behaviors/PerformanceMark-class.html">PerformanceMark</a></li> <li><a href="polymer_app_layout.behaviors/PerformanceMeasure-class.html">PerformanceMeasure</a></li> <li><a href="polymer_app_layout.behaviors/PerformanceNavigation-class.html">PerformanceNavigation</a></li> <li><a href="polymer_app_layout.behaviors/PerformanceResourceTiming-class.html">PerformanceResourceTiming</a></li> <li><a href="polymer_app_layout.behaviors/PerformanceTiming-class.html">PerformanceTiming</a></li> <li><a href="polymer_app_layout.behaviors/PictureElement-class.html">PictureElement</a></li> <li><a href="polymer_app_layout.behaviors/Platform-class.html">Platform</a></li> <li><a href="polymer_app_layout.behaviors/Plugin-class.html">Plugin</a></li> <li><a href="polymer_app_layout.behaviors/PluginArray-class.html">PluginArray</a></li> <li><a href="polymer_app_layout.behaviors/PluginPlaceholderElement-class.html">PluginPlaceholderElement</a></li> <li><a href="polymer_app_layout.behaviors/Point-class.html">Point</a></li> <li><a href="polymer_app_layout.behaviors/PolymerIncludeElementBehavior-class.html">PolymerIncludeElementBehavior</a></li> <li><a href="polymer_app_layout.behaviors/PolymerRouteBehavior-class.html">PolymerRouteBehavior</a></li> <li><a href="polymer_app_layout.behaviors/PopStateEvent-class.html">PopStateEvent</a></li> <li><a href="polymer_app_layout.behaviors/PositionError-class.html">PositionError</a></li> <li><a href="polymer_app_layout.behaviors/PreElement-class.html">PreElement</a></li> <li><a href="polymer_app_layout.behaviors/Presentation-class.html">Presentation</a></li> <li><a href="polymer_app_layout.behaviors/ProcessingInstruction-class.html">ProcessingInstruction</a></li> <li><a href="polymer_app_layout.behaviors/ProgressElement-class.html">ProgressElement</a></li> <li><a href="polymer_app_layout.behaviors/ProgressEvent-class.html">ProgressEvent</a></li> <li><a href="polymer_app_layout.behaviors/PushEvent-class.html">PushEvent</a></li> <li><a href="polymer_app_layout.behaviors/PushManager-class.html">PushManager</a></li> <li><a href="polymer_app_layout.behaviors/PushRegistration-class.html">PushRegistration</a></li> <li><a href="polymer_app_layout.behaviors/QuoteElement-class.html">QuoteElement</a></li> <li><a href="polymer_app_layout.behaviors/RadioButtonInputElement-class.html">RadioButtonInputElement</a></li> <li><a href="polymer_app_layout.behaviors/Range-class.html">Range</a></li> <li><a href="polymer_app_layout.behaviors/RangeInputElement-class.html">RangeInputElement</a></li> <li><a href="polymer_app_layout.behaviors/RangeInputElementBase-class.html">RangeInputElementBase</a></li> <li><a href="polymer_app_layout.behaviors/ReadableStream-class.html">ReadableStream</a></li> <li><a href="polymer_app_layout.behaviors/ReadyState-class.html">ReadyState</a></li> <li><a href="polymer_app_layout.behaviors/Rectangle-class.html">Rectangle</a></li> <li><a href="polymer_app_layout.behaviors/RelatedEvent-class.html">RelatedEvent</a></li> <li><a href="polymer_app_layout.behaviors/ResetButtonInputElement-class.html">ResetButtonInputElement</a></li> <li><a href="polymer_app_layout.behaviors/ResourceProgressEvent-class.html">ResourceProgressEvent</a></li> <li><a href="polymer_app_layout.behaviors/RtcDataChannel-class.html">RtcDataChannel</a></li> <li><a href="polymer_app_layout.behaviors/RtcDataChannelEvent-class.html">RtcDataChannelEvent</a></li> <li><a href="polymer_app_layout.behaviors/RtcDtmfSender-class.html">RtcDtmfSender</a></li> <li><a href="polymer_app_layout.behaviors/RtcDtmfToneChangeEvent-class.html">RtcDtmfToneChangeEvent</a></li> <li><a href="polymer_app_layout.behaviors/RtcIceCandidate-class.html">RtcIceCandidate</a></li> <li><a href="polymer_app_layout.behaviors/RtcIceCandidateEvent-class.html">RtcIceCandidateEvent</a></li> <li><a href="polymer_app_layout.behaviors/RtcPeerConnection-class.html">RtcPeerConnection</a></li> <li><a href="polymer_app_layout.behaviors/RtcSessionDescription-class.html">RtcSessionDescription</a></li> <li><a href="polymer_app_layout.behaviors/RtcStatsReport-class.html">RtcStatsReport</a></li> <li><a href="polymer_app_layout.behaviors/RtcStatsResponse-class.html">RtcStatsResponse</a></li> <li><a href="polymer_app_layout.behaviors/Screen-class.html">Screen</a></li> <li><a href="polymer_app_layout.behaviors/ScreenOrientation-class.html">ScreenOrientation</a></li> <li><a href="polymer_app_layout.behaviors/ScriptElement-class.html">ScriptElement</a></li> <li><a href="polymer_app_layout.behaviors/ScrollAlignment-class.html">ScrollAlignment</a></li> <li><a href="polymer_app_layout.behaviors/SearchInputElement-class.html">SearchInputElement</a></li> <li><a href="polymer_app_layout.behaviors/SecurityPolicyViolationEvent-class.html">SecurityPolicyViolationEvent</a></li> <li><a href="polymer_app_layout.behaviors/SelectElement-class.html">SelectElement</a></li> <li><a href="polymer_app_layout.behaviors/Selection-class.html">Selection</a></li> <li><a href="polymer_app_layout.behaviors/ServiceWorkerClient-class.html">ServiceWorkerClient</a></li> <li><a href="polymer_app_layout.behaviors/ServiceWorkerClients-class.html">ServiceWorkerClients</a></li> <li><a href="polymer_app_layout.behaviors/ServiceWorkerContainer-class.html">ServiceWorkerContainer</a></li> <li><a href="polymer_app_layout.behaviors/ServiceWorkerGlobalScope-class.html">ServiceWorkerGlobalScope</a></li> <li><a href="polymer_app_layout.behaviors/ServiceWorkerRegistration-class.html">ServiceWorkerRegistration</a></li> <li><a href="polymer_app_layout.behaviors/ShadowElement-class.html">ShadowElement</a></li> <li><a href="polymer_app_layout.behaviors/ShadowRoot-class.html">ShadowRoot</a></li> <li><a href="polymer_app_layout.behaviors/SharedWorker-class.html">SharedWorker</a></li> <li><a href="polymer_app_layout.behaviors/SharedWorkerGlobalScope-class.html">SharedWorkerGlobalScope</a></li> <li><a href="polymer_app_layout.behaviors/SourceBuffer-class.html">SourceBuffer</a></li> <li><a href="polymer_app_layout.behaviors/SourceBufferList-class.html">SourceBufferList</a></li> <li><a href="polymer_app_layout.behaviors/SourceElement-class.html">SourceElement</a></li> <li><a href="polymer_app_layout.behaviors/SourceInfo-class.html">SourceInfo</a></li> <li><a href="polymer_app_layout.behaviors/SpanElement-class.html">SpanElement</a></li> <li><a href="polymer_app_layout.behaviors/SpeechGrammar-class.html">SpeechGrammar</a></li> <li><a href="polymer_app_layout.behaviors/SpeechGrammarList-class.html">SpeechGrammarList</a></li> <li><a href="polymer_app_layout.behaviors/SpeechRecognition-class.html">SpeechRecognition</a></li> <li><a href="polymer_app_layout.behaviors/SpeechRecognitionAlternative-class.html">SpeechRecognitionAlternative</a></li> <li><a href="polymer_app_layout.behaviors/SpeechRecognitionError-class.html">SpeechRecognitionError</a></li> <li><a href="polymer_app_layout.behaviors/SpeechRecognitionEvent-class.html">SpeechRecognitionEvent</a></li> <li><a href="polymer_app_layout.behaviors/SpeechRecognitionResult-class.html">SpeechRecognitionResult</a></li> <li><a href="polymer_app_layout.behaviors/SpeechSynthesis-class.html">SpeechSynthesis</a></li> <li><a href="polymer_app_layout.behaviors/SpeechSynthesisEvent-class.html">SpeechSynthesisEvent</a></li> <li><a href="polymer_app_layout.behaviors/SpeechSynthesisUtterance-class.html">SpeechSynthesisUtterance</a></li> <li><a href="polymer_app_layout.behaviors/SpeechSynthesisVoice-class.html">SpeechSynthesisVoice</a></li> <li><a href="polymer_app_layout.behaviors/Storage-class.html">Storage</a></li> <li><a href="polymer_app_layout.behaviors/StorageEvent-class.html">StorageEvent</a></li> <li><a href="polymer_app_layout.behaviors/StorageInfo-class.html">StorageInfo</a></li> <li><a href="polymer_app_layout.behaviors/StorageQuota-class.html">StorageQuota</a></li> <li><a href="polymer_app_layout.behaviors/StyleElement-class.html">StyleElement</a></li> <li><a href="polymer_app_layout.behaviors/StyleMedia-class.html">StyleMedia</a></li> <li><a href="polymer_app_layout.behaviors/StyleSheet-class.html">StyleSheet</a></li> <li><a href="polymer_app_layout.behaviors/SubmitButtonInputElement-class.html">SubmitButtonInputElement</a></li> <li><a href="polymer_app_layout.behaviors/TableCaptionElement-class.html">TableCaptionElement</a></li> <li><a href="polymer_app_layout.behaviors/TableCellElement-class.html">TableCellElement</a></li> <li><a href="polymer_app_layout.behaviors/TableColElement-class.html">TableColElement</a></li> <li><a href="polymer_app_layout.behaviors/TableElement-class.html">TableElement</a></li> <li><a href="polymer_app_layout.behaviors/TableRowElement-class.html">TableRowElement</a></li> <li><a href="polymer_app_layout.behaviors/TableSectionElement-class.html">TableSectionElement</a></li> <li><a href="polymer_app_layout.behaviors/TelephoneInputElement-class.html">TelephoneInputElement</a></li> <li><a href="polymer_app_layout.behaviors/TemplateElement-class.html">TemplateElement</a></li> <li><a href="polymer_app_layout.behaviors/Text-class.html">Text</a></li> <li><a href="polymer_app_layout.behaviors/TextAreaElement-class.html">TextAreaElement</a></li> <li><a href="polymer_app_layout.behaviors/TextEvent-class.html">TextEvent</a></li> <li><a href="polymer_app_layout.behaviors/TextInputElement-class.html">TextInputElement</a></li> <li><a href="polymer_app_layout.behaviors/TextInputElementBase-class.html">TextInputElementBase</a></li> <li><a href="polymer_app_layout.behaviors/TextMetrics-class.html">TextMetrics</a></li> <li><a href="polymer_app_layout.behaviors/TextTrack-class.html">TextTrack</a></li> <li><a href="polymer_app_layout.behaviors/TextTrackCue-class.html">TextTrackCue</a></li> <li><a href="polymer_app_layout.behaviors/TextTrackCueList-class.html">TextTrackCueList</a></li> <li><a href="polymer_app_layout.behaviors/TextTrackList-class.html">TextTrackList</a></li> <li><a href="polymer_app_layout.behaviors/TimeInputElement-class.html">TimeInputElement</a></li> <li><a href="polymer_app_layout.behaviors/TimeRanges-class.html">TimeRanges</a></li> <li><a href="polymer_app_layout.behaviors/Timing-class.html">Timing</a></li> <li><a href="polymer_app_layout.behaviors/TitleElement-class.html">TitleElement</a></li> <li><a href="polymer_app_layout.behaviors/ToolbarBehavior-class.html">ToolbarBehavior</a></li> <li><a href="polymer_app_layout.behaviors/Touch-class.html">Touch</a></li> <li><a href="polymer_app_layout.behaviors/TouchEvent-class.html">TouchEvent</a></li> <li><a href="polymer_app_layout.behaviors/TouchList-class.html">TouchList</a></li> <li><a href="polymer_app_layout.behaviors/TrackElement-class.html">TrackElement</a></li> <li><a href="polymer_app_layout.behaviors/TrackEvent-class.html">TrackEvent</a></li> <li><a href="polymer_app_layout.behaviors/TransitionEvent-class.html">TransitionEvent</a></li> <li><a href="polymer_app_layout.behaviors/TreeWalker-class.html">TreeWalker</a></li> <li><a href="polymer_app_layout.behaviors/UIEvent-class.html">UIEvent</a></li> <li><a href="polymer_app_layout.behaviors/UListElement-class.html">UListElement</a></li> <li><a href="polymer_app_layout.behaviors/UnknownElement-class.html">UnknownElement</a></li> <li><a href="polymer_app_layout.behaviors/UriPolicy-class.html">UriPolicy</a></li> <li><a href="polymer_app_layout.behaviors/Url-class.html">Url</a></li> <li><a href="polymer_app_layout.behaviors/UrlInputElement-class.html">UrlInputElement</a></li> <li><a href="polymer_app_layout.behaviors/UrlUtils-class.html">UrlUtils</a></li> <li><a href="polymer_app_layout.behaviors/UrlUtilsReadOnly-class.html">UrlUtilsReadOnly</a></li> <li><a href="polymer_app_layout.behaviors/ValidityState-class.html">ValidityState</a></li> <li><a href="polymer_app_layout.behaviors/VideoElement-class.html">VideoElement</a></li> <li><a href="polymer_app_layout.behaviors/VideoPlaybackQuality-class.html">VideoPlaybackQuality</a></li> <li><a href="polymer_app_layout.behaviors/VideoTrack-class.html">VideoTrack</a></li> <li><a href="polymer_app_layout.behaviors/VideoTrackList-class.html">VideoTrackList</a></li> <li><a href="polymer_app_layout.behaviors/VttCue-class.html">VttCue</a></li> <li><a href="polymer_app_layout.behaviors/VttRegion-class.html">VttRegion</a></li> <li><a href="polymer_app_layout.behaviors/VttRegionList-class.html">VttRegionList</a></li> <li><a href="polymer_app_layout.behaviors/WebSocket-class.html">WebSocket</a></li> <li><a href="polymer_app_layout.behaviors/WeekInputElement-class.html">WeekInputElement</a></li> <li><a href="polymer_app_layout.behaviors/WheelEvent-class.html">WheelEvent</a></li> <li><a href="polymer_app_layout.behaviors/Window-class.html">Window</a></li> <li><a href="polymer_app_layout.behaviors/WindowBase-class.html">WindowBase</a></li> <li><a href="polymer_app_layout.behaviors/WindowBase64-class.html">WindowBase64</a></li> <li><a href="polymer_app_layout.behaviors/WindowEventHandlers-class.html">WindowEventHandlers</a></li> <li><a href="polymer_app_layout.behaviors/Worker-class.html">Worker</a></li> <li><a href="polymer_app_layout.behaviors/WorkerConsole-class.html">WorkerConsole</a></li> <li><a href="polymer_app_layout.behaviors/WorkerGlobalScope-class.html">WorkerGlobalScope</a></li> <li><a href="polymer_app_layout.behaviors/WorkerPerformance-class.html">WorkerPerformance</a></li> <li><a href="polymer_app_layout.behaviors/XmlDocument-class.html">XmlDocument</a></li> <li><a href="polymer_app_layout.behaviors/XmlSerializer-class.html">XmlSerializer</a></li> <li><a href="polymer_app_layout.behaviors/XPathEvaluator-class.html">XPathEvaluator</a></li> <li><a href="polymer_app_layout.behaviors/XPathExpression-class.html">XPathExpression</a></li> <li><a href="polymer_app_layout.behaviors/XPathNSResolver-class.html">XPathNSResolver</a></li> <li><a href="polymer_app_layout.behaviors/XPathResult-class.html">XPathResult</a></li> <li><a href="polymer_app_layout.behaviors/XsltProcessor-class.html">XsltProcessor</a></li> </ol> </div> <div class="col-xs-12 col-sm-9 col-md-6 main-content"> <section class="desc markdown"> <p>Hidden input which is not intended to be seen or edited by the user.</p> </section> <section> <dl class="dl-horizontal"> <dt>Implements</dt> <dd> <ul class="comma-separated class-relationships"> <li><a href="dart-html/InputElementBase-class.html">InputElementBase</a></li> </ul> </dd> </dl> </section> <section class="summary" id="instance-properties"> <h2>Properties</h2> <dl class="properties"> <dt id="attributes" class="property"> <span class="top-level-variable-type">Map&lt;String,String&gt;</span> <span class="name ">attributes</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> All attributes on this element. </dd> <dt id="autofocus" class="property"> <span class="top-level-variable-type">bool</span> <span class="name ">autofocus</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="baseUri" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">baseUri</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="borderEdge" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/CssRect-class.html">CssRect</a></span> <span class="name ">borderEdge</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Access the dimensions and position of this element's content + padding + border box. </dd> <dt id="childNodes" class="property"> <span class="top-level-variable-type">List&lt;<a href="dart-html/Node-class.html">Node</a>&gt;</span> <span class="name ">childNodes</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> A list of this node's children. </dd> <dt id="children" class="property"> <span class="top-level-variable-type">List&lt;<a href="dart-html/Element-class.html">Element</a>&gt;</span> <span class="name ">children</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> List of the direct children of this element. </dd> <dt id="classes" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/CssClassSet-class.html">CssClassSet</a></span> <span class="name ">classes</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> The set of CSS classes applied to this element. </dd> <dt id="className" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">className</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="client" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/Rectangle-class.html">Rectangle</a></span> <span class="name ">client</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Gets the position of this element relative to the client area of the page. </dd> <dt id="clientHeight" class="property"> <span class="top-level-variable-type">int</span> <span class="name ">clientHeight</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="clientLeft" class="property"> <span class="top-level-variable-type">int</span> <span class="name ">clientLeft</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="clientTop" class="property"> <span class="top-level-variable-type">int</span> <span class="name ">clientTop</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="clientWidth" class="property"> <span class="top-level-variable-type">int</span> <span class="name ">clientWidth</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="contentEdge" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/CssRect-class.html">CssRect</a></span> <span class="name ">contentEdge</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Access this element's content position. </dd> <dt id="contentEditable" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">contentEditable</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="contextMenu" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/MenuElement-class.html">MenuElement</a></span> <span class="name ">contextMenu</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="dataset" class="property"> <span class="top-level-variable-type">Map&lt;String,String&gt;</span> <span class="name ">dataset</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> Allows access to all custom data attributes (data-*) set on this element. </dd> <dt id="dir" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">dir</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="disabled" class="property"> <span class="top-level-variable-type">bool</span> <span class="name ">disabled</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="documentOffset" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/Point-class.html">Point</a></span> <span class="name ">documentOffset</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Provides the coordinates of the element relative to the top of the document. </dd> <dt id="draggable" class="property"> <span class="top-level-variable-type">bool</span> <span class="name ">draggable</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="dropzone" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">dropzone</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="firstChild" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/Node-class.html">Node</a></span> <span class="name ">firstChild</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> The first child of this node. </dd> <dt id="hidden" class="property"> <span class="top-level-variable-type">bool</span> <span class="name ">hidden</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="id" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">id</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="incremental" class="property"> <span class="top-level-variable-type">bool</span> <span class="name ">incremental</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="indeterminate" class="property"> <span class="top-level-variable-type">bool</span> <span class="name ">indeterminate</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="innerHtml" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">innerHtml</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> Parses the HTML fragment and sets it as the contents of this element. </dd> <dt id="isContentEditable" class="property"> <span class="top-level-variable-type">bool</span> <span class="name ">isContentEditable</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="labels" class="property"> <span class="top-level-variable-type">List&lt;<a href="dart-html/Node-class.html">Node</a>&gt;</span> <span class="name ">labels</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="lang" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">lang</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="lastChild" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/Node-class.html">Node</a></span> <span class="name ">lastChild</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> The last child of this node. </dd> <dt id="localName" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">localName</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="marginEdge" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/CssRect-class.html">CssRect</a></span> <span class="name ">marginEdge</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Access the dimensions and position of this element's content + padding + border + margin box. </dd> <dt id="name" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">name</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="namespaceUri" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">namespaceUri</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> A URI that identifies the XML namespace of this element. </dd> <dt id="nextElementSibling" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/Element-class.html">Element</a></span> <span class="name ">nextElementSibling</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="nextNode" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/Node-class.html">Node</a></span> <span class="name ">nextNode</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> The next sibling node. </dd> <dt id="nodeName" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">nodeName</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> The name of this node. </dd> <dt id="nodes" class="property"> <span class="top-level-variable-type">List&lt;<a href="dart-html/Node-class.html">Node</a>&gt;</span> <span class="name ">nodes</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> A modifiable list of this node's children. </dd> <dt id="nodeType" class="property"> <span class="top-level-variable-type">int</span> <span class="name ">nodeType</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> The type of node. </dd> <dt id="nodeValue" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">nodeValue</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> The value of this node. </dd> <dt id="offset" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/Rectangle-class.html">Rectangle</a></span> <span class="name ">offset</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Gets the offset of this element relative to its offsetParent. </dd> <dt id="offsetHeight" class="property"> <span class="top-level-variable-type">int</span> <span class="name ">offsetHeight</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="offsetLeft" class="property"> <span class="top-level-variable-type">int</span> <span class="name ">offsetLeft</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="offsetParent" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/Element-class.html">Element</a></span> <span class="name ">offsetParent</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="offsetTop" class="property"> <span class="top-level-variable-type">int</span> <span class="name ">offsetTop</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="offsetWidth" class="property"> <span class="top-level-variable-type">int</span> <span class="name ">offsetWidth</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="on" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementEvents-class.html">ElementEvents</a></span> <span class="name ">on</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> This is an ease-of-use accessor for event streams which should only be used when an explicit accessor is not available. </dd> <dt id="onAbort" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onAbort</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">abort</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onBeforeCopy" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onBeforeCopy</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">beforecopy</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onBeforeCut" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onBeforeCut</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">beforecut</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onBeforePaste" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onBeforePaste</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">beforepaste</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onBlur" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onBlur</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">blur</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onCanPlay" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onCanPlay</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onCanPlayThrough" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onCanPlayThrough</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onChange" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onChange</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">change</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onClick" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/MouseEvent-class.html">MouseEvent</a>&gt;</span> <span class="name ">onClick</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">click</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onContextMenu" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/MouseEvent-class.html">MouseEvent</a>&gt;</span> <span class="name ">onContextMenu</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">contextmenu</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onCopy" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onCopy</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">copy</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onCut" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onCut</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">cut</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onDoubleClick" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onDoubleClick</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">doubleclick</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onDrag" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/MouseEvent-class.html">MouseEvent</a>&gt;</span> <span class="name ">onDrag</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> A stream of <code class="prettyprint lang-dart">drag</code> events fired when this element currently being dragged. </dd> <dt id="onDragEnd" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/MouseEvent-class.html">MouseEvent</a>&gt;</span> <span class="name ">onDragEnd</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> A stream of <code class="prettyprint lang-dart">dragend</code> events fired when this element completes a drag operation. </dd> <dt id="onDragEnter" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/MouseEvent-class.html">MouseEvent</a>&gt;</span> <span class="name ">onDragEnter</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> A stream of <code class="prettyprint lang-dart">dragenter</code> events fired when a dragged object is first dragged over this element. </dd> <dt id="onDragLeave" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/MouseEvent-class.html">MouseEvent</a>&gt;</span> <span class="name ">onDragLeave</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> A stream of <code class="prettyprint lang-dart">dragleave</code> events fired when an object being dragged over this element leaves this element's target area. </dd> <dt id="onDragOver" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/MouseEvent-class.html">MouseEvent</a>&gt;</span> <span class="name ">onDragOver</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> A stream of <code class="prettyprint lang-dart">dragover</code> events fired when a dragged object is currently being dragged over this element. </dd> <dt id="onDragStart" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/MouseEvent-class.html">MouseEvent</a>&gt;</span> <span class="name ">onDragStart</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> A stream of <code class="prettyprint lang-dart">dragstart</code> events fired when this element starts being dragged. </dd> <dt id="onDrop" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/MouseEvent-class.html">MouseEvent</a>&gt;</span> <span class="name ">onDrop</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> A stream of <code class="prettyprint lang-dart">drop</code> events fired when a dragged object is dropped on this element. </dd> <dt id="onDurationChange" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onDurationChange</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onEmptied" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onEmptied</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onEnded" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onEnded</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onError" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onError</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">error</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onFocus" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onFocus</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">focus</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onFullscreenChange" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onFullscreenChange</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">fullscreenchange</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onFullscreenError" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onFullscreenError</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">fullscreenerror</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onInput" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onInput</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">input</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onInvalid" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onInvalid</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">invalid</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onKeyDown" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/KeyboardEvent-class.html">KeyboardEvent</a>&gt;</span> <span class="name ">onKeyDown</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">keydown</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onKeyPress" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/KeyboardEvent-class.html">KeyboardEvent</a>&gt;</span> <span class="name ">onKeyPress</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">keypress</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onKeyUp" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/KeyboardEvent-class.html">KeyboardEvent</a>&gt;</span> <span class="name ">onKeyUp</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">keyup</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onLoad" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onLoad</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">load</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onLoadedData" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onLoadedData</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onLoadedMetadata" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onLoadedMetadata</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onMouseDown" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/MouseEvent-class.html">MouseEvent</a>&gt;</span> <span class="name ">onMouseDown</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">mousedown</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onMouseEnter" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/MouseEvent-class.html">MouseEvent</a>&gt;</span> <span class="name ">onMouseEnter</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">mouseenter</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onMouseLeave" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/MouseEvent-class.html">MouseEvent</a>&gt;</span> <span class="name ">onMouseLeave</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">mouseleave</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onMouseMove" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/MouseEvent-class.html">MouseEvent</a>&gt;</span> <span class="name ">onMouseMove</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">mousemove</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onMouseOut" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/MouseEvent-class.html">MouseEvent</a>&gt;</span> <span class="name ">onMouseOut</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">mouseout</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onMouseOver" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/MouseEvent-class.html">MouseEvent</a>&gt;</span> <span class="name ">onMouseOver</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">mouseover</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onMouseUp" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/MouseEvent-class.html">MouseEvent</a>&gt;</span> <span class="name ">onMouseUp</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">mouseup</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onMouseWheel" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/WheelEvent-class.html">WheelEvent</a>&gt;</span> <span class="name ">onMouseWheel</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">mousewheel</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onPaste" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onPaste</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">paste</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onPause" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onPause</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onPlay" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onPlay</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onPlaying" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onPlaying</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onRateChange" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onRateChange</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onReset" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onReset</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">reset</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onResize" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onResize</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onScroll" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onScroll</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">scroll</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onSearch" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onSearch</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">search</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onSeeked" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onSeeked</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onSeeking" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onSeeking</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onSelect" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onSelect</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">select</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onSelectStart" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onSelectStart</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">selectstart</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onStalled" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onStalled</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onSubmit" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onSubmit</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">submit</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onSuspend" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onSuspend</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onTimeUpdate" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onTimeUpdate</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onTouchCancel" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/TouchEvent-class.html">TouchEvent</a>&gt;</span> <span class="name ">onTouchCancel</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">touchcancel</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onTouchEnd" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/TouchEvent-class.html">TouchEvent</a>&gt;</span> <span class="name ">onTouchEnd</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">touchend</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onTouchEnter" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/TouchEvent-class.html">TouchEvent</a>&gt;</span> <span class="name ">onTouchEnter</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">touchenter</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onTouchLeave" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/TouchEvent-class.html">TouchEvent</a>&gt;</span> <span class="name ">onTouchLeave</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">touchleave</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onTouchMove" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/TouchEvent-class.html">TouchEvent</a>&gt;</span> <span class="name ">onTouchMove</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">touchmove</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onTouchStart" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/TouchEvent-class.html">TouchEvent</a>&gt;</span> <span class="name ">onTouchStart</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">touchstart</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onTransitionEnd" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/TransitionEvent-class.html">TransitionEvent</a>&gt;</span> <span class="name ">onTransitionEnd</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Stream of <code class="prettyprint lang-dart">transitionend</code> events handled by this <code class="prettyprint lang-dart">Element</code>. </dd> <dt id="onVolumeChange" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onVolumeChange</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="onWaiting" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ElementStream-class.html">ElementStream</a>&lt;<a href="dart-html/Event-class.html">Event</a>&gt;</span> <span class="name ">onWaiting</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="outerHtml" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">outerHtml</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="ownerDocument" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/Document-class.html">Document</a></span> <span class="name ">ownerDocument</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> The document this node belongs to. </dd> <dt id="paddingEdge" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/CssRect-class.html">CssRect</a></span> <span class="name ">paddingEdge</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> Access the dimensions and position of this element's content + padding box. </dd> <dt id="parent" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/Element-class.html">Element</a></span> <span class="name ">parent</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> The parent element of this node. </dd> <dt id="parentNode" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/Node-class.html">Node</a></span> <span class="name ">parentNode</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> The parent node of this node. </dd> <dt id="previousElementSibling" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/Element-class.html">Element</a></span> <span class="name ">previousElementSibling</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="previousNode" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/Node-class.html">Node</a></span> <span class="name ">previousNode</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> The previous sibling node. </dd> <dt id="scrollHeight" class="property"> <span class="top-level-variable-type">int</span> <span class="name ">scrollHeight</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="scrollLeft" class="property"> <span class="top-level-variable-type">int</span> <span class="name ">scrollLeft</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="scrollTop" class="property"> <span class="top-level-variable-type">int</span> <span class="name ">scrollTop</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="scrollWidth" class="property"> <span class="top-level-variable-type">int</span> <span class="name ">scrollWidth</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="shadowRoot" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ShadowRoot-class.html">ShadowRoot</a></span> <span class="name ">shadowRoot</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="spellcheck" class="property"> <span class="top-level-variable-type">bool</span> <span class="name ">spellcheck</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="style" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/CssStyleDeclaration-class.html">CssStyleDeclaration</a></span> <span class="name ">style</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="tabIndex" class="property"> <span class="top-level-variable-type">int</span> <span class="name ">tabIndex</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="tagName" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">tagName</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="text" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">text</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> All text within this node and its decendents. </dd> <dt id="title" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">title</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="translate" class="property"> <span class="top-level-variable-type">bool</span> <span class="name ">translate</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="validationMessage" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">validationMessage</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="validity" class="property"> <span class="top-level-variable-type"><a href="polymer_app_layout/ValidityState-class.html">ValidityState</a></span> <span class="name ">validity</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="value" class="property"> <span class="top-level-variable-type">String</span> <span class="name ">value</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> </dd> <dt id="willValidate" class="property"> <span class="top-level-variable-type">bool</span> <span class="name ">willValidate</span> </dt> <dd> <div class="readable-writable"> read-only, <span class="is-inherited">inherited</span> </div> </dd> <dt id="xtag" class="property"> <span class="top-level-variable-type">dynamic</span> <span class="name ">xtag</span> </dt> <dd> <div class="readable-writable"> read / write, <span class="is-inherited">inherited</span> </div> Experimental support for <a href="http://dvcs.w3.org/hg/webcomponents/raw-file/tip/explainer/index.html">web components</a>. This field stores a reference to the component implementation. It was inspired by Mozilla's <a href="http://x-tags.org/">x-tags</a> project. Please note: in the future it may be possible to <code class="prettyprint lang-dart">extend Element</code> from your class, in which case this field will be deprecated. </dd> </dl> </section> <section class="summary" id="constructors"> <h2>Constructors</h2> <dl class="constructor-summary-list"> <dt id="HiddenInputElement" class="callable"> <span class="name"><a href="polymer_app_layout.behaviors/HiddenInputElement/HiddenInputElement.html">HiddenInputElement</a></span><span class="signature">()</span> </dt> <dd> </dd> </dl> </section> <section class="summary" id="instance-methods"> <h2>Methods</h2> <dl class="callables"> <dt id="addEventListener" class="callable"> <span class="name ">addEventListener</span><span class="signature">(<wbr><span class="parameter" id="addEventListener-param-type"><span class="type-annotation">String</span> <span class="parameter-name">type</span></span>, <span class="parameter" id="addEventListener-param-listener"><span class="type-annotation">dynamic</span> <span class="parameter-name">listener</span>(<span class="parameter" id="EventListener-param-event"><span class="type-annotation"><a href="polymer_app_layout/Event-class.html">Event</a></span> <span class="parameter-name">event</span></span>)</span>, [<span class="parameter" id="addEventListener-param-useCapture"><span class="type-annotation">bool</span> <span class="parameter-name">useCapture</span></span>]) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="animate" class="callable"> <span class="name ">animate</span><span class="signature">(<wbr><span class="parameter" id="animate-param-effect"><span class="type-annotation">Object</span> <span class="parameter-name">effect</span></span>, [<span class="parameter" id="animate-param-timing"><span class="type-annotation">Object</span> <span class="parameter-name">timing</span></span>]) &#8594; <span class="returntype"><a href="dart-html/AnimationPlayer-class.html">AnimationPlayer</a></span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="append" class="callable"> <span class="name ">append</span><span class="signature">(<wbr><span class="parameter" id="append-param-newChild"><span class="type-annotation"><a href="polymer_app_layout/Node-class.html">Node</a></span> <span class="parameter-name">newChild</span></span>) &#8594; <span class="returntype"><a href="dart-html/Node-class.html">Node</a></span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Adds a node to the end of the child <a href="polymer_app_layout/Node/nodes.html">nodes</a> list of this node. </dd> <dt id="appendHtml" class="callable"> <span class="name ">appendHtml</span><span class="signature">(<wbr><span class="parameter" id="appendHtml-param-text"><span class="type-annotation">String</span> <span class="parameter-name">text</span></span>, {<span class="parameter" id="appendHtml-param-validator"><span class="type-annotation"><a href="polymer_app_layout/NodeValidator-class.html">NodeValidator</a></span> <span class="parameter-name">validator</span></span>, <span class="parameter" id="appendHtml-param-treeSanitizer"><span class="type-annotation"><a href="polymer_app_layout/NodeTreeSanitizer-class.html">NodeTreeSanitizer</a></span> <span class="parameter-name">treeSanitizer</span></span>}) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Parses the specified text as HTML and adds the resulting node after the last child of this element. </dd> <dt id="appendText" class="callable"> <span class="name ">appendText</span><span class="signature">(<wbr><span class="parameter" id="appendText-param-text"><span class="type-annotation">String</span> <span class="parameter-name">text</span></span>) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Adds the specified text after the last child of this element. </dd> <dt id="attached" class="callable"> <span class="name ">attached</span><span class="signature">(<wbr>) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Called by the DOM when this element has been inserted into the live document. </dd> <dt id="attributeChanged" class="callable"> <span class="name ">attributeChanged</span><span class="signature">(<wbr><span class="parameter" id="attributeChanged-param-name"><span class="type-annotation">String</span> <span class="parameter-name">name</span></span>, <span class="parameter" id="attributeChanged-param-oldValue"><span class="type-annotation">String</span> <span class="parameter-name">oldValue</span></span>, <span class="parameter" id="attributeChanged-param-newValue"><span class="type-annotation">String</span> <span class="parameter-name">newValue</span></span>) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Called by the DOM whenever an attribute on this has been changed. </dd> <dt id="blur" class="callable"> <span class="name ">blur</span><span class="signature">(<wbr>) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="checkValidity" class="callable"> <span class="name ">checkValidity</span><span class="signature">(<wbr>) &#8594; <span class="returntype">bool</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="click" class="callable"> <span class="name ">click</span><span class="signature">(<wbr>) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="clone" class="callable"> <span class="name ">clone</span><span class="signature">(<wbr><span class="parameter" id="clone-param-deep"><span class="type-annotation">bool</span> <span class="parameter-name">deep</span></span>) &#8594; <span class="returntype"><a href="dart-html/Node-class.html">Node</a></span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Returns a copy of this node. </dd> <dt id="contains" class="callable"> <span class="name ">contains</span><span class="signature">(<wbr><span class="parameter" id="contains-param-other"><span class="type-annotation"><a href="polymer_app_layout/Node-class.html">Node</a></span> <span class="parameter-name">other</span></span>) &#8594; <span class="returntype">bool</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Returns true if this node contains the specified node. </dd> <dt id="createFragment" class="callable"> <span class="name ">createFragment</span><span class="signature">(<wbr><span class="parameter" id="createFragment-param-html"><span class="type-annotation">String</span> <span class="parameter-name">html</span></span>, {<span class="parameter" id="createFragment-param-validator"><span class="type-annotation"><a href="polymer_app_layout/NodeValidator-class.html">NodeValidator</a></span> <span class="parameter-name">validator</span></span>, <span class="parameter" id="createFragment-param-treeSanitizer"><span class="type-annotation"><a href="polymer_app_layout/NodeTreeSanitizer-class.html">NodeTreeSanitizer</a></span> <span class="parameter-name">treeSanitizer</span></span>}) &#8594; <span class="returntype"><a href="dart-html/DocumentFragment-class.html">DocumentFragment</a></span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Create a DocumentFragment from the HTML fragment and ensure that it follows the sanitization rules specified by the validator or treeSanitizer. </dd> <dt id="createShadowRoot" class="callable"> <span class="name ">createShadowRoot</span><span class="signature">(<wbr>) &#8594; <span class="returntype"><a href="dart-html/ShadowRoot-class.html">ShadowRoot</a></span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="detached" class="callable"> <span class="name ">detached</span><span class="signature">(<wbr>) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Called by the DOM when this element has been removed from the live document. </dd> <dt id="dispatchEvent" class="callable"> <span class="name ">dispatchEvent</span><span class="signature">(<wbr><span class="parameter" id="dispatchEvent-param-event"><span class="type-annotation"><a href="polymer_app_layout/Event-class.html">Event</a></span> <span class="parameter-name">event</span></span>) &#8594; <span class="returntype">bool</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="enteredView" class="callable"> <span class="name deprecated">enteredView</span><span class="signature">(<wbr>) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Deprecated*: override <a href="polymer_app_layout/Element/attached.html">attached</a> instead. </dd> <dt id="focus" class="callable"> <span class="name ">focus</span><span class="signature">(<wbr>) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="getAnimationPlayers" class="callable"> <span class="name ">getAnimationPlayers</span><span class="signature">(<wbr>) &#8594; <span class="returntype">List&lt;<a href="dart-html/AnimationPlayer-class.html">AnimationPlayer</a>&gt;</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="getAttribute" class="callable"> <span class="name ">getAttribute</span><span class="signature">(<wbr><span class="parameter" id="getAttribute-param-name"><span class="type-annotation">String</span> <span class="parameter-name">name</span></span>) &#8594; <span class="returntype">String</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="getAttributeNS" class="callable"> <span class="name ">getAttributeNS</span><span class="signature">(<wbr><span class="parameter" id="getAttributeNS-param-namespaceURI"><span class="type-annotation">String</span> <span class="parameter-name">namespaceURI</span></span>, <span class="parameter" id="getAttributeNS-param-localName"><span class="type-annotation">String</span> <span class="parameter-name">localName</span></span>) &#8594; <span class="returntype">String</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="getBoundingClientRect" class="callable"> <span class="name ">getBoundingClientRect</span><span class="signature">(<wbr>) &#8594; <span class="returntype"><a href="dart-html/Rectangle-class.html">Rectangle</a></span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Returns the smallest bounding rectangle that encompasses this element's padding, scrollbar, and border. </dd> <dt id="getClientRects" class="callable"> <span class="name ">getClientRects</span><span class="signature">(<wbr>) &#8594; <span class="returntype">List&lt;<a href="dart-math/Rectangle-class.html">Rectangle</a>&gt;</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Returns a list of bounding rectangles for each box associated with this element. </dd> <dt id="getComputedStyle" class="callable"> <span class="name ">getComputedStyle</span><span class="signature">(<wbr>[<span class="parameter" id="getComputedStyle-param-pseudoElement"><span class="type-annotation">String</span> <span class="parameter-name">pseudoElement</span></span>]) &#8594; <span class="returntype"><a href="dart-html/CssStyleDeclaration-class.html">CssStyleDeclaration</a></span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> The set of all CSS values applied to this element, including inherited and default values. </dd> <dt id="getDestinationInsertionPoints" class="callable"> <span class="name ">getDestinationInsertionPoints</span><span class="signature">(<wbr>) &#8594; <span class="returntype">List&lt;<a href="dart-html/Node-class.html">Node</a>&gt;</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Returns a list of shadow DOM insertion points to which this element is distributed. </dd> <dt id="getElementsByClassName" class="callable"> <span class="name ">getElementsByClassName</span><span class="signature">(<wbr><span class="parameter" id="getElementsByClassName-param-classNames"><span class="type-annotation">String</span> <span class="parameter-name">classNames</span></span>) &#8594; <span class="returntype">List&lt;<a href="dart-html/Node-class.html">Node</a>&gt;</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Returns a list of nodes with the given class name inside this element. </dd> <dt id="getNamespacedAttributes" class="callable"> <span class="name ">getNamespacedAttributes</span><span class="signature">(<wbr><span class="parameter" id="getNamespacedAttributes-param-namespace"><span class="type-annotation">String</span> <span class="parameter-name">namespace</span></span>) &#8594; <span class="returntype">Map&lt;String,String&gt;</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Gets a map for manipulating the attributes of a particular namespace. </dd> <dt id="hasChildNodes" class="callable"> <span class="name ">hasChildNodes</span><span class="signature">(<wbr>) &#8594; <span class="returntype">bool</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Returns true if this node has any children. </dd> <dt id="insertAdjacentElement" class="callable"> <span class="name ">insertAdjacentElement</span><span class="signature">(<wbr><span class="parameter" id="insertAdjacentElement-param-where"><span class="type-annotation">String</span> <span class="parameter-name">where</span></span>, <span class="parameter" id="insertAdjacentElement-param-element"><span class="type-annotation"><a href="polymer_app_layout/Element-class.html">Element</a></span> <span class="parameter-name">element</span></span>) &#8594; <span class="returntype"><a href="dart-html/Element-class.html">Element</a></span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="insertAdjacentHtml" class="callable"> <span class="name ">insertAdjacentHtml</span><span class="signature">(<wbr><span class="parameter" id="insertAdjacentHtml-param-where"><span class="type-annotation">String</span> <span class="parameter-name">where</span></span>, <span class="parameter" id="insertAdjacentHtml-param-html"><span class="type-annotation">String</span> <span class="parameter-name">html</span></span>, {<span class="parameter" id="insertAdjacentHtml-param-validator"><span class="type-annotation"><a href="polymer_app_layout/NodeValidator-class.html">NodeValidator</a></span> <span class="parameter-name">validator</span></span>, <span class="parameter" id="insertAdjacentHtml-param-treeSanitizer"><span class="type-annotation"><a href="polymer_app_layout/NodeTreeSanitizer-class.html">NodeTreeSanitizer</a></span> <span class="parameter-name">treeSanitizer</span></span>}) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Parses text as an HTML fragment and inserts it into the DOM at the specified location. </dd> <dt id="insertAdjacentText" class="callable"> <span class="name ">insertAdjacentText</span><span class="signature">(<wbr><span class="parameter" id="insertAdjacentText-param-where"><span class="type-annotation">String</span> <span class="parameter-name">where</span></span>, <span class="parameter" id="insertAdjacentText-param-text"><span class="type-annotation">String</span> <span class="parameter-name">text</span></span>) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="insertAllBefore" class="callable"> <span class="name ">insertAllBefore</span><span class="signature">(<wbr><span class="parameter" id="insertAllBefore-param-newNodes"><span class="type-annotation">Iterable&lt;<a href="dart-html/Node-class.html">Node</a>&gt;</span> <span class="parameter-name">newNodes</span></span>, <span class="parameter" id="insertAllBefore-param-refChild"><span class="type-annotation"><a href="polymer_app_layout/Node-class.html">Node</a></span> <span class="parameter-name">refChild</span></span>) &#8594; <span class="returntype"><a href="dart-html/Node-class.html">Node</a></span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Inserts all of the nodes into this node directly before refChild. </dd> <dt id="insertBefore" class="callable"> <span class="name ">insertBefore</span><span class="signature">(<wbr><span class="parameter" id="insertBefore-param-newChild"><span class="type-annotation"><a href="polymer_app_layout/Node-class.html">Node</a></span> <span class="parameter-name">newChild</span></span>, <span class="parameter" id="insertBefore-param-refChild"><span class="type-annotation"><a href="polymer_app_layout/Node-class.html">Node</a></span> <span class="parameter-name">refChild</span></span>) &#8594; <span class="returntype"><a href="dart-html/Node-class.html">Node</a></span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Inserts all of the nodes into this node directly before refChild. </dd> <dt id="leftView" class="callable"> <span class="name deprecated">leftView</span><span class="signature">(<wbr>) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Deprecated*: override <a href="polymer_app_layout/Element/detached.html">detached</a> instead. </dd> <dt id="matches" class="callable"> <span class="name ">matches</span><span class="signature">(<wbr><span class="parameter" id="matches-param-selectors"><span class="type-annotation">String</span> <span class="parameter-name">selectors</span></span>) &#8594; <span class="returntype">bool</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="matchesWithAncestors" class="callable"> <span class="name ">matchesWithAncestors</span><span class="signature">(<wbr><span class="parameter" id="matchesWithAncestors-param-selectors"><span class="type-annotation">String</span> <span class="parameter-name">selectors</span></span>) &#8594; <span class="returntype">bool</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Checks if this element or any of its parents match the CSS selectors. </dd> <dt id="offsetTo" class="callable"> <span class="name ">offsetTo</span><span class="signature">(<wbr><span class="parameter" id="offsetTo-param-parent"><span class="type-annotation"><a href="polymer_app_layout/Element-class.html">Element</a></span> <span class="parameter-name">parent</span></span>) &#8594; <span class="returntype"><a href="dart-html/Point-class.html">Point</a></span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Provides the offset of this element's <a href="polymer_app_layout/Element/borderEdge.html">borderEdge</a> relative to the specified <code class="prettyprint lang-dart">parent</code>. </dd> <dt id="query" class="callable"> <span class="name deprecated">query</span><span class="signature">(<wbr><span class="parameter" id="query-param-relativeSelectors"><span class="type-annotation">String</span> <span class="parameter-name">relativeSelectors</span></span>) &#8594; <span class="returntype"><a href="dart-html/Element-class.html">Element</a></span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Alias for <a href="polymer_app_layout/Element/querySelector.html">querySelector</a>. Note this function is deprecated because its semantics will be changing in the future. </dd> <dt id="queryAll" class="callable"> <span class="name deprecated">queryAll</span><span class="signature">(<wbr><span class="parameter" id="queryAll-param-relativeSelectors"><span class="type-annotation">String</span> <span class="parameter-name">relativeSelectors</span></span>) &#8594; <span class="returntype"><a href="dart-html/ElementList-class.html">ElementList</a>&lt;<a href="dart-html/Element-class.html">Element</a>&gt;</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Alias for <a href="polymer_app_layout/Element/querySelectorAll.html">querySelectorAll</a>. Note this function is deprecated because its semantics will be changing in the future. </dd> <dt id="querySelector" class="callable"> <span class="name ">querySelector</span><span class="signature">(<wbr><span class="parameter" id="querySelector-param-selectors"><span class="type-annotation">String</span> <span class="parameter-name">selectors</span></span>) &#8594; <span class="returntype"><a href="dart-html/Element-class.html">Element</a></span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Finds the first descendant element of this element that matches the specified group of selectors. </dd> <dt id="querySelectorAll" class="callable"> <span class="name ">querySelectorAll</span><span class="signature">(<wbr><span class="parameter" id="querySelectorAll-param-selectors"><span class="type-annotation">String</span> <span class="parameter-name">selectors</span></span>) &#8594; <span class="returntype"><a href="dart-html/ElementList-class.html">ElementList</a>&lt;<a href="dart-html/Element-class.html">Element</a>&gt;</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Finds all descendent elements of this element that match the specified group of selectors. </dd> <dt id="remove" class="callable"> <span class="name ">remove</span><span class="signature">(<wbr>) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Removes this node from the DOM. </dd> <dt id="removeEventListener" class="callable"> <span class="name ">removeEventListener</span><span class="signature">(<wbr><span class="parameter" id="removeEventListener-param-type"><span class="type-annotation">String</span> <span class="parameter-name">type</span></span>, <span class="parameter" id="removeEventListener-param-listener"><span class="type-annotation">dynamic</span> <span class="parameter-name">listener</span>(<span class="parameter" id="EventListener-param-event"><span class="type-annotation"><a href="polymer_app_layout/Event-class.html">Event</a></span> <span class="parameter-name">event</span></span>)</span>, [<span class="parameter" id="removeEventListener-param-useCapture"><span class="type-annotation">bool</span> <span class="parameter-name">useCapture</span></span>]) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="replaceWith" class="callable"> <span class="name ">replaceWith</span><span class="signature">(<wbr><span class="parameter" id="replaceWith-param-otherNode"><span class="type-annotation"><a href="polymer_app_layout/Node-class.html">Node</a></span> <span class="parameter-name">otherNode</span></span>) &#8594; <span class="returntype"><a href="dart-html/Node-class.html">Node</a></span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Replaces this node with another node. </dd> <dt id="requestFullscreen" class="callable"> <span class="name ">requestFullscreen</span><span class="signature">(<wbr>) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="requestPointerLock" class="callable"> <span class="name ">requestPointerLock</span><span class="signature">(<wbr>) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="scrollIntoView" class="callable"> <span class="name ">scrollIntoView</span><span class="signature">(<wbr>[<span class="parameter" id="scrollIntoView-param-alignment"><span class="type-annotation"><a href="polymer_app_layout/ScrollAlignment-class.html">ScrollAlignment</a></span> <span class="parameter-name">alignment</span></span>]) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Scrolls this element into view. </dd> <dt id="setAttribute" class="callable"> <span class="name ">setAttribute</span><span class="signature">(<wbr><span class="parameter" id="setAttribute-param-name"><span class="type-annotation">String</span> <span class="parameter-name">name</span></span>, <span class="parameter" id="setAttribute-param-value"><span class="type-annotation">String</span> <span class="parameter-name">value</span></span>) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="setAttributeNS" class="callable"> <span class="name ">setAttributeNS</span><span class="signature">(<wbr><span class="parameter" id="setAttributeNS-param-namespaceURI"><span class="type-annotation">String</span> <span class="parameter-name">namespaceURI</span></span>, <span class="parameter" id="setAttributeNS-param-qualifiedName"><span class="type-annotation">String</span> <span class="parameter-name">qualifiedName</span></span>, <span class="parameter" id="setAttributeNS-param-value"><span class="type-annotation">String</span> <span class="parameter-name">value</span></span>) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="setCustomValidity" class="callable"> <span class="name ">setCustomValidity</span><span class="signature">(<wbr><span class="parameter" id="setCustomValidity-param-error"><span class="type-annotation">String</span> <span class="parameter-name">error</span></span>) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> </dd> <dt id="setInnerHtml" class="callable"> <span class="name ">setInnerHtml</span><span class="signature">(<wbr><span class="parameter" id="setInnerHtml-param-html"><span class="type-annotation">String</span> <span class="parameter-name">html</span></span>, {<span class="parameter" id="setInnerHtml-param-validator"><span class="type-annotation"><a href="polymer_app_layout/NodeValidator-class.html">NodeValidator</a></span> <span class="parameter-name">validator</span></span>, <span class="parameter" id="setInnerHtml-param-treeSanitizer"><span class="type-annotation"><a href="polymer_app_layout/NodeTreeSanitizer-class.html">NodeTreeSanitizer</a></span> <span class="parameter-name">treeSanitizer</span></span>}) &#8594; <span class="returntype">void</span> </span> </dt> <dd> <div> <span class="is-inherited">inherited</span> </div> Parses the HTML fragment and sets it as the contents of this element. This ensures that the generated content follows the sanitization rules specified by the validator or treeSanitizer. </dd> </dl> </section> </div> <!-- /.main-content --> <div class="col-xs-6 col-sm-6 col-md-3 sidebar sidebar-offcanvas-right"> <h5>HiddenInputElement</h5> <ol> <li class="section-title"><a href="polymer_app_layout.behaviors/HiddenInputElement-class.html#constructors">Constructors</a></li> <li><a href="polymer_app_layout.behaviors/HiddenInputElement/HiddenInputElement.html">HiddenInputElement</a></li> <li class="section-title"><a href="polymer_app_layout.behaviors/HiddenInputElement-class.html#methods">Methods</a></li> <li>addEventListener </li> <li>animate </li> <li>append </li> <li>appendHtml </li> <li>appendText </li> <li>attached </li> <li>attributeChanged </li> <li>blur </li> <li>checkValidity </li> <li>click </li> <li>clone </li> <li>contains </li> <li>createFragment </li> <li>createShadowRoot </li> <li>detached </li> <li>dispatchEvent </li> <li>enteredView </li> <li>focus </li> <li>getAnimationPlayers </li> <li>getAttribute </li> <li>getAttributeNS </li> <li>getBoundingClientRect </li> <li>getClientRects </li> <li>getComputedStyle </li> <li>getDestinationInsertionPoints </li> <li>getElementsByClassName </li> <li>getNamespacedAttributes </li> <li>hasChildNodes </li> <li>insertAdjacentElement </li> <li>insertAdjacentHtml </li> <li>insertAdjacentText </li> <li>insertAllBefore </li> <li>insertBefore </li> <li>leftView </li> <li>matches </li> <li>matchesWithAncestors </li> <li>offsetTo </li> <li>query </li> <li>queryAll </li> <li>querySelector </li> <li>querySelectorAll </li> <li>remove </li> <li>removeEventListener </li> <li>replaceWith </li> <li>requestFullscreen </li> <li>requestPointerLock </li> <li>scrollIntoView </li> <li>setAttribute </li> <li>setAttributeNS </li> <li>setCustomValidity </li> <li>setInnerHtml </li> </ol> </div><!--/.sidebar-offcanvas--> </div> <!-- container --> <footer> <div class="container-fluid"> <div class="container"> <p class="text-center"> <span class="no-break"> polymer_app_layout_template 0.1.0 api docs </span> &bull; <span class="copyright no-break"> <a href="https://www.dartlang.org"> <img src="static-assets/favicon.png" alt="Dart" title="Dart"width="16" height="16"> </a> </span> &bull; <span class="copyright no-break"> <a href="http://creativecommons.org/licenses/by-sa/4.0/">cc license</a> </span> </p> </div> </div> </footer> <script src="static-assets/prettify.js"></script> <script src="static-assets/script.js"></script> <!-- Do not remove placeholder --> <!-- Footer Placeholder --> </body> </html>
lejard-h/polymer_app_layout_templates
doc/api/polymer_app_layout.behaviors/HiddenInputElement-class.html
HTML
bsd-3-clause
157,313
// RobotBuilder Version: 2.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc3824.BetaBot.commands; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc3824.BetaBot.Robot; /** * */ public class JiggleBoulder extends Command { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS private Timer m_Timer; // Setup the Jiggle Boulder "state" machine // // Time: Outtake Stop Intake // _________|_____|______________| // 0.4 0.6 1.0 // 0.4 0.1 0.5 // private double outtakeTimeOn = 0.4; private double stopTransistionTime = 0.5; private double intakeTimeOn = 1.0; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR public JiggleBoulder() { // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES requires(Robot.shooter); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES } // Called just before this Command runs the first time protected void initialize() { // Create an instance of the Timer m_Timer = new Timer(); // Reset and start the timer m_Timer.reset(); m_Timer.start(); // Start the rear shooter wheels out with the front shooter wheels in to hold the boulder Robot.shooter.ShooterRearWheelControl(0.8); Robot.shooter.ShooterFrontWheelControl(-0.8); } // Called repeatedly when this Command is scheduled to run protected void execute() { double presentTimer = m_Timer.get(); // Check the state if (presentTimer > stopTransistionTime) Robot.shooter.ShooterRearWheelControl(-1.0); else if (presentTimer > outtakeTimeOn) Robot.shooter.ShooterRearWheelControl(0.0); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { // Determine if the routine is complete if (m_Timer.get() > intakeTimeOn) return true; return false; } // Called once after isFinished returns true protected void end() { // Stop the shooter wheels Robot.shooter.ShooterAllWheelControl(0); // Stop and reset the timer m_Timer.stop(); m_Timer.reset(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { this.end(); } }
HVA-FRC-3824/betaBot2016
src/org/usfirst/frc3824/BetaBot/commands/JiggleBoulder.java
Java
bsd-3-clause
3,162
/* * Copyright (c) 2021, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file includes the platform-specific initializers. * */ #ifndef PLATFORM_EFR32_H_ #define PLATFORM_EFR32_H_ #include <openthread/instance.h> #include "em_device.h" #include "em_system.h" #include "rail.h" // Global OpenThread instance structure extern otInstance *sInstance; // Global reference to rail handle extern RAIL_Handle_t emPhyRailHandle; // coex needs the emPhyRailHandle symbol. #define gRailHandle emPhyRailHandle // use gRailHandle in the OpenThread PAL. /** * This function performs all platform-specific initialization of * OpenThread's drivers. * */ void sl_ot_sys_init(void); /** * This function initializes the alarm service used by OpenThread. * */ void efr32AlarmInit(void); /** * This function provides the remaining time (in milliseconds) on an alarm service. * */ uint32_t efr32AlarmPendingTime(void); /** * This function checks if the alarm service is running. * * @param[in] aInstance The OpenThread instance structure. * */ bool efr32AlarmIsRunning(otInstance *aInstance); /** * This function performs alarm driver processing. * * @param[in] aInstance The OpenThread instance structure. * */ void efr32AlarmProcess(otInstance *aInstance); /** * This function initializes the radio service used by OpenThead. * */ void efr32RadioInit(void); /** * This function deinitializes the radio service used by OpenThead. * */ void efr32RadioDeinit(void); /** * This function performs radio driver processing. * * @param[in] aInstance The OpenThread instance structure. * */ void efr32RadioProcess(otInstance *aInstance); /** * This function performs UART driver processing. * */ void efr32UartProcess(void); /** * This function performs CPC driver processing. * */ void efr32CpcProcess(void); /** * Initialization of Misc module. * */ void efr32MiscInit(void); /** * Initialization of Logger driver. * */ void efr32LogInit(void); /** * Deinitialization of Logger driver. * */ void efr32LogDeinit(void); /** * Registers the sleep callback handler. The callback is used to check that * the application has no work pending and that it is safe to put the EFR32 * into a low energy sleep mode. * * The callback should return true if it is ok to enter sleep mode. Note * that the callback itself is run with interrupts disabled and so should * be kept as short as possible. Anny interrupt including those from timers * will wake the EFR32 out of sleep mode. * * @param[in] aCallback Callback function. * */ void efr32SetSleepCallback(bool (*aCallback)(void)); /** * Put the EFR32 into a low power mode. Before sleeping it will call a callback * in the application registered with efr32SetSleepCallback to ensure that there * is no outstanding work in the application to do. */ void efr32Sleep(void); #endif // PLATFORM_EFR32_H_
openthread/ot-efr32
src/src/platform-efr32.h
C
bsd-3-clause
4,469
def hanoi(n, source, helper, target): if n > 0: # move tower of size n - 1 to helper hanoi(n - 1, source, target, helper) # move disk from source peg to target peg if source: target.append(source.pop()) # move tower of size n-1 from helper to target hanoi(n - 1, helper, source, target) source = [9, 8, 7, 6, 5, 4, 3, 2, 1] target = [] helper = [] hanoi(len(source), source, helper, target) print source, helper, target
talapus/Ophidian
Games/Hanoi/hanoi_prototype4.py
Python
bsd-3-clause
486
#ligght ###The simple PHP router ligght is a PHP micro router that helps you to easily route your _HTTP Requests_. ligght is the easiest and fastest way to create an API. ##Features * Standard HTTP Methods * GET * POST * PUT * DELETE * PATCH * OPTIONS * HEAD * DEBUG * Custom HTTP Methods using `\ligght\Interfaces\HttpMethod` interface * Parameter routing ##Getting Started ###Required * PHP >= 5.3.* * Apache `mod_rewrite` ###Configure evironment You must include that snippet in `.htaccess` file: ``` Options -MultiViews RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule .* index.php?$0 [PT,L] ``` Or copy [this](./.htaccess) .htaccess file to the same folder of your index.php ###Hello World Tutorial Set a route like this: ```php \ligght\Router::getInstance()->route( \ligght\Router::GET, '/hello/:name', function($name){ print "Hello, $name"; }, array(':name') ); ``` And run the router: ```php \ligght\Router::getInstance()->run(); ``` ####Style Guide Full coded with [PSR-2](http://www.php-fig.org/psr/psr-2/) Coding Style
liamato/ligght
Readme.md
Markdown
bsd-3-clause
1,155
/* * Copyright (c) 2009-2012 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.shader; import com.jme3.asset.AssetManager; import com.jme3.material.ShaderGenerationInfo; import com.jme3.shader.Shader.ShaderType; /** * This shader Generator can generate Vertex and Fragment shaders from * ShaderNodes for GLESSL 3.0 * Nowdays it's just a subclass of Glsl150ShaderGenerator overriding the version * string because GLSL 1.5 is mostly compatible with GLESSL 3.0 * * @author Nehon * @author Joliver82 */ public class Glsl300ShaderGenerator extends Glsl150ShaderGenerator { /** * Creates a Glsl300ShaderGenerator * * @param assetManager the assetmanager */ public Glsl300ShaderGenerator(AssetManager assetManager) { super(assetManager); } @Override protected String getLanguageAndVersion(ShaderType type) { return "GLSL300"; } }
zzuegg/jmonkeyengine
jme3-core/src/main/java/com/jme3/shader/Glsl300ShaderGenerator.java
Java
bsd-3-clause
2,477
<?php namespace Laminas\Http\PhpEnvironment; use function array_diff; use function array_map; use function array_pop; use function explode; use function in_array; use function str_replace; use function strpos; use function strtoupper; /** * Functionality for determining client IP address. */ class RemoteAddress { /** * Whether to use proxy addresses or not. * * As default this setting is disabled - IP address is mostly needed to increase * security. HTTP_* are not reliable since can easily be spoofed. It can be enabled * just for more flexibility, but if user uses proxy to connect to trusted services * it's his/her own risk, only reliable field for IP address is $_SERVER['REMOTE_ADDR']. * * @var bool */ protected $useProxy = false; /** * List of trusted proxy IP addresses * * @var array */ protected $trustedProxies = []; /** * HTTP header to introspect for proxies * * @var string */ protected $proxyHeader = 'HTTP_X_FORWARDED_FOR'; /** * Changes proxy handling setting. * * This must be static method, since validators are recovered automatically * at session read, so this is the only way to switch setting. * * @param bool $useProxy Whether to check also proxied IP addresses. * @return $this */ public function setUseProxy($useProxy = true) { $this->useProxy = $useProxy; return $this; } /** * Checks proxy handling setting. * * @return bool Current setting value. */ public function getUseProxy() { return $this->useProxy; } /** * Set list of trusted proxy addresses * * @param array $trustedProxies * @return $this */ public function setTrustedProxies(array $trustedProxies) { $this->trustedProxies = $trustedProxies; return $this; } /** * Set the header to introspect for proxy IPs * * @param string $header * @return $this */ public function setProxyHeader($header = 'X-Forwarded-For') { $this->proxyHeader = $this->normalizeProxyHeader($header); return $this; } /** * Returns client IP address. * * @return string IP address. */ public function getIpAddress() { $ip = $this->getIpAddressFromProxy(); if ($ip) { return $ip; } // direct IP address if (isset($_SERVER['REMOTE_ADDR'])) { return $_SERVER['REMOTE_ADDR']; } return ''; } /** * Attempt to get the IP address for a proxied client * * @see http://tools.ietf.org/html/draft-ietf-appsawg-http-forwarded-10#section-5.2 * * @return false|string */ protected function getIpAddressFromProxy() { if ( ! $this->useProxy || (isset($_SERVER['REMOTE_ADDR']) && ! in_array($_SERVER['REMOTE_ADDR'], $this->trustedProxies)) ) { return false; } $header = $this->proxyHeader; if (! isset($_SERVER[$header]) || empty($_SERVER[$header])) { return false; } // Extract IPs $ips = explode(',', $_SERVER[$header]); // trim, so we can compare against trusted proxies properly $ips = array_map('trim', $ips); // remove trusted proxy IPs $ips = array_diff($ips, $this->trustedProxies); // Any left? if (empty($ips)) { return false; } // Since we've removed any known, trusted proxy servers, the right-most // address represents the first IP we do not know about -- i.e., we do // not know if it is a proxy server, or a client. As such, we treat it // as the originating IP. // @see http://en.wikipedia.org/wiki/X-Forwarded-For return array_pop($ips); } /** * Normalize a header string * * Normalizes a header string to a format that is compatible with * $_SERVER * * @param string $header * @return string */ protected function normalizeProxyHeader($header) { $header = strtoupper($header); $header = str_replace('-', '_', $header); if (0 !== strpos($header, 'HTTP_')) { $header = 'HTTP_' . $header; } return $header; } }
deforay/odkdash
vendor/laminas/laminas-http/src/PhpEnvironment/RemoteAddress.php
PHP
bsd-3-clause
4,437
/******************************************************************** * LGT tracker - The official C++ implementation of the LGT tracker * Copyright (C) 2013 Luka Cehovin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ********************************************************************/ /* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 4 -*- */ #include "lgt.h" #include "common/utils/utils.h" #include "common/canvas.h" namespace legit { namespace tracker { typedef struct CostPair_ { float cost; int index; } CostPair; bool __random_init = false; int compare_cost_pair (const void* i, const void* j) { float c = ( ((CostPair*)j)->cost - ((CostPair*)i)->cost ); return (c < 0) ? -1 : (c > 0) ? 1 : 0; } LGTTracker::LGTTracker(string inst) : patches(6, 30), modalities(), verbosity(0), probability_size(150), global_optimization(50, 300, 10, 10, 10, 0.001), local_optimization( 40, 40, 0, 5, 10, 0.001), motion(4, 2, 0) { patch_scale = 1.0; patches_max = 6; patches_min = 36 ; patches_persistence = 0.8; reweight_persistence = 0.5; reweight_similarity = 3; reweight_distance = 3; weight_remove_threshold = 0.1; merge_distance = 0.5; lambda_geometry = 0.03; lambda_visual = 1; optimization_global_M = 20; optimization_global_R = 0.03; optimization_global_S = 0.0001; optimization_local_M = 5; // TODO: probably needs rethinking median_size_min = 0; median_size_max = INT_MAX; median_persistence = 0.8; size_constraints.min_size.width = -1; size_constraints.min_size.height = -1; size_constraints.max_size.width = -1; size_constraints.max_size.height = -1; sampling_threshold = 0.2; addition_distance = 3.0; string patch_type_string = "histogram"; if (!__random_init) { RANDOM_SEED(time(NULL)); __random_init = true; } } LGTTracker::~LGTTracker() { } void LGTTracker::initialize(Image& image, cv::Rect region) { int proposed_patch_size = 6; // ceil(sqrt((double)(region.width * region.height))*0.15) ; patches.set_patch_size(proposed_patch_size); // FIXME int count = (int) round( (region.width * region.height) / pow((double)3 * patches.get_radius(), 2)); int count = (int) round( (float)(region.width * region.height) / std::pow( (float)(4 * 3), 2)); count = MIN(MAX(patches_min, count), patches_max); /* FIXME patches.set_patch_size((int)ceil( (patch_scale * (image.width() * 6) / 320))); // Woodoo? int count = (int) round( (region.width * region.height) / pow((double)3 * patches.get_radius(), 2));// Woodoo2? */ int sx, sy; if (region.width < region.height) { sx = floor(sqrt(count)) + 1; sy = ceil(sqrt(count)) + 1; } else { sy = floor(sqrt(count)) + 1; sx = ceil(sqrt(count)) + 1; } /* FIXME { sx = MAX(3, round(sqrt((float)count * ((float) region.width / (float) region.height)))); sy = MAX(3, round((float)count / (float) sx)); } else { sy = MAX(3, round(sqrt((float)count * ((float) region.height / (float) region.width)))); sx = MAX(3, round((float)count / (float) sy)); }*/ count = sx * sy; int dx = (region.width - 2 * patches.get_radius()) / (sx - 1); int dy = (region.height - 2 * patches.get_radius()) / (sy - 1); Mat_<float> positions = Mat_<float>(count, 3); int k = 0; for (int i = 0; i < sx; i++) { for (int j = 0; j < sy; j++) { positions.row(k++) << region.x + dx* i + patches.get_radius() + (i % 2), region.y + dy* j + patches.get_radius() + (j % 2), 0.5f; } } initialize(image, positions); } void LGTTracker::initialize(Image& image, Mat points) { //patches.flush(); int psize = patches.size(); for(int i = 0;i < psize;i++ ){ patches.remove(0); } for (int i = 0; i < points.rows; i++) { patches.add(image, patch_type, Point2f(points.at<float>(i, 0), points.at<float>(i, 1)), points.at<float>(i, 2)); } patches_capacity = patches.size(); Point2f* positions = new Point2f[patches.size()]; for (int i = 0; i < patches.size(); i++) { positions[i] = patches.get_position(i); } Matrix D = distances(positions, patches.size()); vector<double> medians; /* FIXME int k_m = MAX( ceil(D.cols * 0.1), 3 ) ; float md = 0.0 ; for (int p = 0; p < patches.size(); p++) { Matrix r = D.row(p); cv::sort(r, r, CV_SORT_ASCENDING) ; float dist_loc = 0.0 ; for (int i_k = 1; i_k < k_m+1 ; ++i_k) { dist_loc += r.at<double>(0,i_k) ; } dist_loc /= (float)k_m ; medians.push_back(dist_loc); } median_threshold = median(medians) * 1.2 ;*/ median_threshold = 20000; /* FIXME for (int p = 0; p < patches.size(); p++) { Matrix m = D.row(p); median_threshold = MAX(median_threshold, median(m)); }*/ modalities.flush(); cv::Rect region = patches.region(); Point2f mean = patches.mean_position(); float half, third ; float spectral_density, meas_noise ; float diagonal, delta_t2, delta_t3 ; float delta_t = 1.0 ; // for framerate 5 fps (for 3fps multiply by 1.6, for example) half = 0.5 ; third = 1.0 / 3.0 ; delta_t2 = delta_t* delta_t ; delta_t3 = delta_t* delta_t* delta_t ; diagonal = sqrt((float)region.width * region.width + (float)region.height * region.height) ; // set mesh deformation parameter //lambda_geometry = 0.002; // 1.0/(diagonal*0.08); //0.002 ; //0.0015 // initialize cross-entropy optimization //optimization_global_M = 20; // 4.0* diagonal*0.15; //20 ; //optimization_local_M = 5; // diagonal*0.05 ; //5 // initialize motion model motion.transitionMatrix = (Mat_<float>(4, 4) << 1, 0, delta_t, 0, 0, 1, 0, delta_t, 0, 0, 1, 0, 0, 0, 0, 1); motion.measurementMatrix = (Mat_<float>(2, 4) << 1, 0, 0, 0, 0, 1, 0, 0); // intitialize process noise meas_noise = diagonal * 0.1 * 10; meas_noise = meas_noise * meas_noise ; //10.0 ; 0.01 spectral_density = diagonal * 0.2 * 10; spectral_density = spectral_density * spectral_density ; // 0.2 5.0*5.0; // motion.processNoiseCov = (Mat_<float>(4, 4) << third * delta_t3, 0, half * delta_t2, 0, 0, third * delta_t3, 0, half * delta_t2, half * delta_t2, 0, delta_t, 0, 0, half * delta_t2, 0, delta_t) ; motion.processNoiseCov = motion.processNoiseCov * spectral_density ; // initialize measurement noise setIdentity(motion.measurementNoiseCov, Scalar(meas_noise)); // initialize the posterior state motion.statePost = (Mat_<float>(4, 1) << mean.x, mean.y, 0, 0) ; motion.statePre = (Mat_<float>(4, 1) << mean.x, mean.y, 0, 0) ; // initialize posterior covariances setIdentity(motion.errorCovPost, Scalar(meas_noise * 4.0)); setIdentity(motion.errorCovPre, Scalar(meas_noise * 4.0)); track(image, false, false); delete [] positions; } void LGTTracker::update(Image& image) { track(image, true, true); } int LGTTracker::patch_num(){ return patches.size(); } void LGTTracker::track(Image& image, bool announce, bool push) { if (push) { patches.push(); } // allocate new state for patches Mat kalman_prediction = motion.predict(); Point2f move; Point2f center = patches.mean_position(); move.x = kalman_prediction.at<float>(0, 0) - center.x ; move.y = kalman_prediction.at<float>(1, 0) - center.y ; /*move.x = kalman_prediction.at<float>(2, 0)*3 ; move.y = kalman_prediction.at<float>(3, 0)*3 ;*/ patches.move(move); stage_optimization(image, announce, push); /******************************************************************************** * **** UPDATE WEIGHTS **** * *********************************************************************************/ stage_update_weights(image, announce, push); // recalculate center, update Kalman center = patches.mean_position(); motion.correct((Mat_<float>(2, 1) << center.x, center.y)); /******************************************************************************** * **** UPDATE MODALITIES **** * *********************************************************************************/ stage_update_modalities(image, announce, push); /******************************************************************************** * **** ADD PATCHES **** * *********************************************************************************/ stage_add_patches(image, announce, push); } void LGTTracker::stage_optimization(Image& image, bool announce, bool push) { /******************************************************************************** **** GLOBAL OPTIMIZATION **** *********************************************************************************/ cv::Point2f center = patches.mean_position(); OptimizationStatus status(patches); if (optimization_global_R < 0.00001 && optimization_global_S < 0.00001) { Matrix globalC = Mat::diag( (Mat_<double>(2, 1) << optimization_global_M, optimization_global_M)); Matrix globalM = (Matrix(1, 2) << 0, 0); cross_entropy_global_move(image, patches, globalM, globalC, global_optimization, status); } else { Matrix globalC = Mat::diag( (Mat_<double>(5, 1) << optimization_global_M, optimization_global_M, optimization_global_R, optimization_global_S, optimization_global_S)); Matrix globalM = (Matrix(1, 5) << 0, 0, 0, 1, 1); cross_entropy_global_affine(image, patches, globalM, globalC, global_optimization, size_constraints, status); } for (int i = 0; i < status.size(); i++) { // if (status[i].flags & OPTIMIZATION_CONVERGED) { //printpoint(status[i].position); PatchStatus ps = status.get(i); patches.set_position(i, ps.position); float value = exp(-patches.response(image, i, ps.position)); // // if (value > 0.8) status.set_flags(i, OPTIMIZATION_FIXED); // Zakaj mora biti vecji ravno od 0.8 // } } /******************************************************************************** **** LOCAL OPTIMIZATION **** *********************************************************************************/ if (patches.size() > 4) { DelaunayConstraints* cn = new DelaunayConstraints(patches); cross_entropy_local_refine(image, patches, *cn, optimization_local_M, lambda_geometry, lambda_visual, local_optimization, status); delete cn; for (int i = 0; i < status.size(); i++) { PatchStatus ps = status.get(i); // if (status[i].flags & OPTIMIZATION_CONVERGED) { //if (announce) notify_observers(OBSERVER_CHANNEL_OPTIMIZATION, & status[i]); patches.set_position(i, ps.position); // } } } } void LGTTracker::stage_update_weights(Image& image, bool announce, bool push) { Point2f* positions = new Point2f[patches.size()]; vector<float> similarity_score; vector<float> proximity_score; for (int i = 0; i < patches.size(); i++) { float similarity = exp(- patches.response(image, i, patches.get_position(i)) * reweight_similarity); similarity_score.push_back(similarity); positions[i] = patches.get_position(i); } Matrix D = distances(positions, patches.size()); vector<double> medians; for (int p = 0; p < patches.size(); p++) { Matrix r = D.row(p); float m = median(r); medians.push_back(m); } for (int p = 0; p < patches.size(); p++) { proximity_score.push_back(1 / (1 + exp((medians[p] - median_threshold) * reweight_distance))); } PatchReweight reweight; for (int i = 0; i < patches.size(); i++) { reweight.id = patches.get_id(i); reweight.weights.clear(); patches.set_weight(i, reweight_persistence * patches.get_weight(i) + (1 - reweight_persistence) * similarity_score[i] * proximity_score[i]); reweight.weights.push_back(similarity_score[i]); reweight.weights.push_back(proximity_score[i]); } // Merging or inhibition float merge_threshold = merge_distance * patches.get_radius(); vector<int> selection; while (true) { for (int i = 0; i < patches.size(); i++) { positions[i] = patches.get_position(i); } D = distances(positions, patches.size()); int p; for (p = 0; p < patches.size(); p++) { selection.clear(); for (int m = p; m < patches.size(); m++) { if (D(p, m) < merge_threshold) { selection.push_back(m); } } if (selection.size() > 1) { patches.merge(image, selection, patch_type); break; } } if (p == patches.size()) { break; } } delete [] positions; // remove patches WeightLowerFilter remove_filter(weight_remove_threshold); int removed = patches.remove(remove_filter); } void LGTTracker::stage_update_modalities(Image& image, bool announce, bool push) { modalities.update(image, &patches, patches.region()); } void LGTTracker::stage_add_patches(Image& image, bool announce, bool push) { cv::Point2f center = patches.mean_position(); cv::Rect region = intersection(cv::Rect(0, 0, image.width(), image.height()), cv::Rect((int)center.x - probability_size / 2, (int)center.y - probability_size / 2, probability_size, probability_size)); Image crop(image, region); int patches_new = MAX( MIN((int)round(patches_capacity) - (float)patches.size() + 1, patches_max - patches.size()), patches_min - patches.size()); Mat mask; patch_create(mask, (float)patches.get_patch_size() * addition_distance, (float)patches.get_patch_size() * addition_distance, PATCH_CONE, FLAG_INVERT); if (patches_new > 0) { Mat map; modalities.probability(crop, map); if (!map.empty()) { double max; minMaxLoc(map, NULL, &max, NULL, NULL, Mat()); supress_noise(map, max * sampling_threshold, 5, 1); // now we mask out the positions of existing patches in the probability for (int i = 0; i < patches.size(); i++) { cv::Point p = patches.get_relative_position(i, region.tl()); patch_operation(map, mask, p, OPERATION_MULTIPLY); } // add new patches if possible for (int i = 0; i < patches_new; i++) { double total = sum(map)[0]; if (total < 1e-16) //TODO: hardcoded { break; } map /= total; // normalize masked probability cv::Point p; float value; sample_map(map, &p, 1, &value); if (p.x == -1) { break; } if (map.at<float>(p.y, p.x) < 0.00001) { break; } // mask again patch_operation(map, mask, p, OPERATION_MULTIPLY); patches.add(image, patch_type, p + region.tl(), 0.5); //TODO: hardcoded } } } patches_capacity = (patches_persistence) * patches_capacity + (1 - patches_persistence) * patches.size(); } cv::Rect LGTTracker::region() { //return bounds; return patches.region(); } Point2f LGTTracker::position() { //return Point2f(bounds.x + bounds.width / 2, bounds.y + bounds.height); return patches.mean_position(); } #define VISUALIZE_MOTION_HISTORY 300 void LGTTracker::visualize(Canvas& canvas) { if (verbosity < 1) { return; } int psize2 = patches.get_patch_size() / 2; float max_weight = 0; Point2f buffer[VISUALIZE_MOTION_HISTORY]; max_weight = 1; for (int i = 0; i < patches.size(); i++) { Point2f p = patches.get_position(i); int tint = MIN((int) ((patches.get_weight(i) * 255) / max_weight), 255); canvas.rectangle(cv::Point(p.x - psize2, p.y - psize2), cv::Point(p.x + psize2, p.y + psize2), Scalar(tint, 0, tint, 10), 1); if (verbosity > 2) { int history = patches.get_motion_history(i, buffer, VISUALIZE_MOTION_HISTORY); for (int j = 0; j < history - 1; j++) { canvas.line(buffer[j], buffer[j + 1], Scalar(0, 255, 0), 1); } } } if (verbosity > 1) { Mat statePost = motion.statePost ; Mat errorCovPost = motion.errorCovPost ; Point2f mean, pred ; Matrix2f cov ; mean.x = statePost.at<float>(0, 0) ; mean.y = statePost.at<float>(1, 0) ; cov.m00 = errorCovPost.at<float>(0, 0) ; cov.m11 = errorCovPost.at<float>(1, 1) ; cov.m01 = errorCovPost.at<float>(0, 1) ; cov.m10 = errorCovPost.at<float>(1, 0) ; canvas.ellipse(mean, cov, Scalar(0, 0, 255)); canvas.rectangle(region(), Scalar(0, 255, 0), 2); float ppx = statePost.at<float>(2, 0) ; float ppy = statePost.at<float>(3, 0) ; pred.x = mean.x + statePost.at<float>(2, 0) * motion.transitionMatrix.at<float>(0, 2) ; pred.y = mean.y + statePost.at<float>(3, 0) * motion.transitionMatrix.at<float>(1, 3) ; canvas.line(mean, pred, Scalar(100, 255, 120), 2); } } vector<cv::Point> LGTTracker::get_patch_positions() { vector<cv::Point> positions(patches.size()); for (int i = 0; i < patches.size(); i++) { Point2f p = patches.get_position(i); positions.push_back(p); } return positions; } bool LGTTracker::is_tracking() { return patches.size() > 0; } string LGTTracker::get_name() { return "LG tracker"; } void supress_noise(Mat& mat, float threshold, int window, float percent, IntegralImage* integral) { int window_threshold = ((float) window * window) * percent; IntegralImage* temp = NULL; int window_offset = ceil( ((float) window) / 2); if (integral) { temp = integral; temp->update(mat, threshold); } else { temp = new IntegralImage(mat, threshold); } for (int i = 0; i < mat.rows; i++) { float* data = (float*) mat.ptr(i); if (i - window_offset <= 0 || i + window_offset >= mat.cols - 1) { memset(data, 0, sizeof(float) * mat.cols); } else { for (int j = 0; j < window_offset; j++) { data[j] = 0; data[mat.cols - 1 - j] = 0; } for (int j = 0; j < mat.cols - window; j++) { if (temp->sum(MAX(0, j), MAX(0, i), MIN(mat.cols - 1, j + window), MIN(mat.rows - 1, i + window)) < window_threshold) { data[j + window_offset] = 0; } } } } if (!integral) { delete temp; } } } }
tracedev/legit
src/trackers/lgt/lgt.cpp
C++
bsd-3-clause
23,995
<?php declare(strict_types=1); namespace PhpParser\Comment; class Doc extends \PhpParser\Comment { }
cwi-swat/PHP-Parser
lib/PhpParser/Comment/Doc.php
PHP
bsd-3-clause
102
subroutine SHRead(filename, cilm, lmax, skip, header, error, exitstatus) !------------------------------------------------------------------------------ ! ! This subroutine will open an ascii file, and read in all of the ! spherical harmonic coefficients. If the option "header" ! is specified, then the first Length(header) records of the ! spherical harmonic file will be retuned in the array header. ! ! The file will be read until the end of the file is encountered ! or until the maximum length of cilm (as dimensioned in the calling ! program) is reached. ! ! Calling Parameters ! ! IN ! filename Character name of the ascii file. ! ! OUT ! cilm Spherical harmonic coeficients with dimensions ! (2, lmax+1, lmax+1). ! lmax Maximum spherical harmonic degree of cilm. ! ! OPTIONAL ! header Array of the first length(header) data records ! in the file. Called as header = header, or ! header = header(1:number_of_header_records). ! skip Number of lines to skip ! error Error of the spherical harmonic coefficients, assumed ! to in the format (l, m, c1lm, c2lm, error1lm, error2lm). ! exitstatus If present, instead of executing a STOP when an error ! is encountered, the variable exitstatus will be ! returned describing the error. ! 0 = No errors; ! 1 = Improper dimensions of input array; ! 2 = Improper bounds for input variable; ! 3 = Error allocating memory; ! 4 = File IO error. ! ! Copyright (c) 2016, SHTOOLS ! All rights reserved. ! !------------------------------------------------------------------------------ implicit none character(*), intent(in) :: filename integer, intent(out) :: lmax real*8, intent(out) :: cilm(:,:,:) real*8, intent(out), optional :: header(:), error(:,:,:) integer, intent(in), optional :: skip integer, intent(out), optional :: exitstatus integer :: l, m, stat, ll, mm, lmax2, lstart, headlen, fu if (present(exitstatus)) exitstatus = 0 lmax = 0 cilm = 0.0d0 fu = 101 if (size(cilm(:,1,1)) < 2 ) then print*, "Error --- SHRead" print*, "CILM must be dimensioned (2, *, *)." print*, "Input array is dimensioned ", size(cilm(:,1,1)), & size(cilm(1,:,1)), size(cilm(1,1,:)) if (present(exitstatus)) then exitstatus = 1 return else stop end if end if lmax2 = min(size(cilm(1,1,:) ) - 1, size(cilm(1,:,1) ) - 1) open(fu, file=filename, status="old") if (present(header)) headlen = size(header) !-------------------------------------------------------------------------- ! ! Skip lines and read header information ! !-------------------------------------------------------------------------- if (present(skip) ) then do l = 1, skip, 1 read(fu,*, iostat=stat) if (stat /= 0 ) then print*, "Error --- SHRead" print*, "Problem skipping first lines of ", filename print*, "Line number = ", l print*, "Number of lines to skip = ", skip if (present(exitstatus)) then exitstatus = 4 return else stop end if end if end do end if if (present(header) ) then read(fu,*, iostat=stat) (header(l), l=1, headlen,1) if (stat /= 0 ) then print*, "Error --- SHRead" print*, "Problem reading header line ", filename if (present(exitstatus)) then exitstatus = 4 return else stop end if end if end if !-------------------------------------------------------------------------- ! ! Determine first l value ! !-------------------------------------------------------------------------- read(fu,*, iostat=stat) ll if (stat /= 0) then print*, "Error --- SHRead" print*, "Problem reading first line of ", filename if (present(exitstatus)) then exitstatus = 4 return else stop end if end if lstart = ll rewind (fu) if (present(skip)) then do l = 1, skip, 1 read(fu,*, iostat=stat) end do endif if (present(header)) then read(fu,*, iostat=stat) (header(l), l=1, headlen) end if !-------------------------------------------------------------------------- ! ! Read coefficients ! !-------------------------------------------------------------------------- do l = lstart, lmax2, 1 do m = 0, l if (present(error)) then read(fu,*,iostat=stat) ll, mm, cilm(1,l+1,m+1), & cilm(2,l+1,m+1), error(1,l+1,m+1), error(2,l+1,m+1) else if (m == 0) then read(fu,*,iostat=stat) ll, mm, cilm(1,l+1,m+1) else read(fu,*,iostat=stat) ll, mm, cilm(1,l+1,m+1), & cilm(2,l+1,m+1) end if end if if (stat < 0) then exit else if (stat > 0) then print*, "Error --- SHRead" print*, "Problem reading file ", filename if (present(exitstatus)) then exitstatus = 1 return else stop end if else if (ll /=l .or. mm /= m) then print*, "Error --- SHRead" print*, "Problem reading file ", filename print*, "Expected indices (l,m) = ", l, m print*, "Read indices (l,m) = ", ll, mm if (present(exitstatus)) then exitstatus = 1 return else stop end if end if end do if (stat < 0) exit lmax = l end do close (fu) end subroutine SHRead
ioshchepkov/SHTOOLS
src/SHRead.f95
FORTRAN
bsd-3-clause
6,506
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_methods &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../_static/material.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_univariate" href="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_univariate.html" /> <link rel="prev" title="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_method" href="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_method.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_methods" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.12.2</span> <span class="md-header-nav__topic"> statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_methods </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../_static/versions.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../statespace.html" class="md-tabs__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a></li> <li class="md-tabs__item"><a href="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.html" class="md-tabs__link">statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.12.2</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../tsa.html" class="md-nav__link">Time Series analysis <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa</span></code></a> </li> <li class="md-nav__item"> <a href="../statespace.html" class="md-nav__link">Time Series Analysis by State Space Methods <code class="xref py py-mod docutils literal notranslate"><span class="pre">statespace</span></code></a> </li> <li class="md-nav__item"> <a href="../vector_ar.html" class="md-nav__link">Vector Autoregressions <code class="xref py py-mod docutils literal notranslate"><span class="pre">tsa.vector_ar</span></code></a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_methods.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <h1 id="generated-statsmodels-tsa-statespace-kalman-smoother-kalmansmoother-smooth-methods--page-root">statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_methods<a class="headerlink" href="#generated-statsmodels-tsa-statespace-kalman-smoother-kalmansmoother-smooth-methods--page-root" title="Permalink to this headline">¶</a></h1> <dl class="py attribute"> <dt id="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_methods"> <code class="sig-prename descclassname">KalmanSmoother.</code><code class="sig-name descname">smooth_methods</code><em class="property"> = ['smooth_conventional', 'smooth_alternative', 'smooth_classical']</em><a class="headerlink" href="#statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_methods" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_method.html" title="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_method" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_method </span> </div> </a> <a href="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_univariate.html" title="statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_univariate" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_univariate </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Feb 02, 2021. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 3.4.3. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
statsmodels/statsmodels.github.io
v0.12.2/generated/statsmodels.tsa.statespace.kalman_smoother.KalmanSmoother.smooth_methods.html
HTML
bsd-3-clause
18,165
/* Copyright (c) 2014, Sebastian Eriksson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sebastian Eriksson nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL SEBASTIAN ERIKSSON BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef MESH_IMPORTER_H #define MESH_IMPORTER_H #include "Mesh.h" #include <list> #include <string> namespace Raytracer2 { //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// class MeshImporter { public: enum ImporterFlags { FlatShading = 0x1, // Force face normals, even if vertex normals are available CalculateVertexNormals = 0x2, // (Re)calculates vertex normals Default = 0 }; MeshImporter() {} virtual bool accepts(const std::string & ext) const = 0; virtual MeshPtr loadFromFile(const std::string & filename, int flags) const = 0; static MeshPtr load(const std::string & filename, int flags = ImporterFlags::Default); }; typedef std::shared_ptr<MeshImporter> MeshImporterPtr; //////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////// class MeshImporterRegistry { public: static MeshImporterRegistry & instance(); void registerImporter(MeshImporterPtr importer); MeshImporterPtr find(const std::string & filename) const; private: MeshImporterRegistry(); MeshImporterRegistry(const MeshImporterRegistry &); void operator=(const MeshImporterRegistry &); std::list<MeshImporterPtr> m_importers; }; template <typename T> struct MeshImporterRegistrar { MeshImporterRegistrar() { MeshImporterRegistry::instance().registerImporter(std::make_shared<T>()); } ~MeshImporterRegistrar() { // TODO: unregister } }; #define REGISTER_IMPORTER(type) template class MeshImporterRegistrar<type>; \ MeshImporterRegistrar<type> Registered ## type; } #endif // MESH_IMPORTER_H
sebis/Raytracer
raytracer2/Raytracer2/MeshImporter.h
C
bsd-3-clause
3,625
/* * Copyright (C)2015,2016,2017 Amos Brocco (amos.brocco@supsi.ch) * Scuola Universitaria Professionale della * Svizzera Italiana (SUPSI) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Scuola Universitaria Professionale della Svizzera * Italiana (SUPSI) nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "MetadataFilter.h" #include <boost/lexical_cast.hpp> DEFAULT_EXPORT_ALL(MetadataFilter, "Filter blobs depending on JSON values", "", false) static bool compare_string_equal(std::string& a, std::string& b) { return a == b; } static bool compare_string_not_equal(std::string& a, std::string& b) { return a != b; } static bool compare_double_equal(double a, double b) { return a == b; } static bool compare_double_not_equal(double a, double b) { return a != b; } static bool compare_double_gt(double a, double b) { return a > b; } static bool compare_double_ge(double a, double b) { return a >= b; } static bool compare_double_lt(double a, double b) { return a < b; } static bool compare_double_le(double a, double b) { return a <= b; } MetadataFilter::MetadataFilter(const std::string& mid) : poma::Module<MetadataFilter, PomaDataType>(mid) {} void MetadataFilter::setup_cli(boost::program_options::options_description& desc) const { boost::program_options::options_description options("JSON Filter Capture Options"); options.add_options() ("field", boost::program_options::value<std::string>()->required(), "JSON field to be compared") ("op", boost::program_options::value<std::string>()->required(), "Comparison operation (>,<,=,!=,<=,>=)") ("value", boost::program_options::value<std::string>()->required(), "Value to compare to"); desc.add(options); } void MetadataFilter::process_cli(boost::program_options::variables_map& vm) { m_field = vm["field"].as<std::string>(); m_op = vm["op"].as<std::string>(); m_value_string = vm["value"].as<std::string>(); try { m_value_double = boost::lexical_cast<double>(m_value_string); m_string_comparison = false; } catch(...) { m_string_comparison = true; } if (m_string_comparison) { if (m_op == "=") { m_string_comparison_fn = compare_string_equal; } else if (m_op == "!=") { m_string_comparison_fn = compare_string_not_equal; } else { std::cerr << "Invalid string operator " << m_op << std::endl; exit(1); } } else { if (m_op == "=") { m_double_comparison_fn = compare_double_equal; } else if (m_op == "!=") { m_double_comparison_fn = compare_double_not_equal; } else if (m_op == "<") { m_double_comparison_fn = compare_double_lt; } else if (m_op == "<=") { m_double_comparison_fn = compare_double_le; } else if (m_op == ">") { m_double_comparison_fn = compare_double_gt; } else if (m_op == ">=") { m_double_comparison_fn = compare_double_ge; } else { std::cerr << "Invalid double operator " << m_op << std::endl; exit(1); } } } void MetadataFilter::on_incoming_data(PomaPacketType& dta, const std::string& channel) { if (m_string_comparison) { std::string data = dta.m_properties.get(m_field, ""); if (!m_string_comparison_fn(data, m_value_string)) { submit_data(dta, "fail"); } else { submit_data(dta); } } else { double data = dta.m_properties.get(m_field, -1.0); if (!m_double_comparison_fn(data, m_value_double)) { submit_data(dta, "fail"); } else { submit_data(dta); } } }
slashdotted/PomaPure
Modules/MetadataFilter/src/MetadataFilter.cpp
C++
bsd-3-clause
5,222
shared_examples_for 'stats query' do it 'does not use stats unless requested' do search expect(connection).not_to have_last_search_with(:stats) end it 'uses stats when requested' do search do stats :average_rating end expect(connection).to have_last_search_with(:stats => true) end it 'requests single field stats' do search do stats :average_rating end expect(connection).to have_last_search_with(:"stats.field" => %w{average_rating_ft}) end it 'requests multiple field stats' do search do stats :average_rating, :published_at end expect(connection).to have_last_search_with(:"stats.field" => %w{average_rating_ft published_at_dt}) end it 'facets on a stats field' do search do stats :average_rating do facet :featured end end expect(connection).to have_last_search_with(:"f.average_rating_ft.stats.facet" => %w{featured_bs}) end it 'only facets on a stats field when requested' do search do stats :average_rating end expect(connection).not_to have_last_search_with(:"f.average_rating_ft.stats.facet") end it 'facets on multiple stats fields' do search do stats :average_rating, :published_at do facet :featured end end expect(connection).to have_last_search_with( :"f.average_rating_ft.stats.facet" => %w{featured_bs}, :"f.published_at_dt.stats.facet" => %w{featured_bs} ) end it 'supports facets on stats field' do search do stats :average_rating do facet :featured, :primary_category_id end end expect(connection).to have_last_search_with( :"f.average_rating_ft.stats.facet" => %w{featured_bs primary_category_id_i} ) end end
hafeild/alice
vendor/bundle/ruby/2.3.0/gems/sunspot-2.3.0/spec/api/query/stats_examples.rb
Ruby
bsd-3-clause
1,771
<?php /** * Created by PhpStorm. * User: Rem * Date: 18.09.2016 * Time: 19:15 * * @var components\View $this */ $flashes = Yii::$app->session->allFlashes; ?> <?php if (!empty($flashes)) : ?> <div class="row"> <div class="col-lg-5"> <?php foreach ($flashes as $key => $messages) : ?> <?php $messages = (array)$messages; switch ($key) { case 'error': $class = 'alert alert-danger'; $icon = 'glyphicon glyphicon-remove-sign'; break; case 'warning': $class = 'alert alert-warning'; $icon = 'glyphicon glyphicon-exclamation-sign'; break; case 'info': $class = 'alert alert-info'; $icon = 'glyphicon glyphicon-info-sign'; break; default: $class = 'alert alert-success'; $icon = 'glyphicon glyphicon-ok-sign'; break; } ?> <?php foreach ($messages as $message) : ?> <div class="<?= $class ?>" role="alert"> <span class="<?= $icon ?>" aria-hidden="true"></span> <?= $message ?> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> </div> <?php endforeach ?> <?php endforeach ?> </div> </div> <div class="col-lg-7"></div> <?php endif ?>
remk-wadriga/ira-site
themes/main/layouts/partials/flash-message.php
PHP
bsd-3-clause
1,746
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 800 {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} #endif module Text.RE.PCRE.ByteString ( -- * Tutorial -- $tutorial -- * The Match Operators (*=~) , (?=~) , (=~) , (=~~) -- * The Toolkit -- $toolkit , module Text.RE -- * The 'RE' Type -- $re , module Text.RE.PCRE.RE ) where import Prelude.Compat import qualified Data.ByteString as B import Data.Typeable import Text.Regex.Base import Text.RE import Text.RE.Internal.AddCaptureNames import Text.RE.PCRE.RE import qualified Text.Regex.PCRE as PCRE -- | find all matches in text (*=~) :: B.ByteString -> RE -> Matches B.ByteString (*=~) bs rex = addCaptureNamesToMatches (reCaptureNames rex) $ match (reRegex rex) bs -- | find first match in text (?=~) :: B.ByteString -> RE -> Match B.ByteString (?=~) bs rex = addCaptureNamesToMatch (reCaptureNames rex) $ match (reRegex rex) bs -- | the regex-base polymorphic match operator (=~) :: ( Typeable a , RegexContext PCRE.Regex B.ByteString a , RegexMaker PCRE.Regex PCRE.CompOption PCRE.ExecOption String ) => B.ByteString -> RE -> a (=~) bs rex = addCaptureNames (reCaptureNames rex) $ match (reRegex rex) bs -- | the regex-base monadic, polymorphic match operator (=~~) :: ( Monad m , Functor m , Typeable a , RegexContext PCRE.Regex B.ByteString a , RegexMaker PCRE.Regex PCRE.CompOption PCRE.ExecOption String ) => B.ByteString -> RE -> m a (=~~) bs rex = addCaptureNames (reCaptureNames rex) <$> matchM (reRegex rex) bs instance IsRegex RE B.ByteString where matchOnce = flip (?=~) matchMany = flip (*=~) regexSource = reSource -- $tutorial -- We have a regex tutorial at <http://tutorial.regex.uk>. These API -- docs are mainly for reference. -- $toolkit -- -- Beyond the above match operators and the regular expression type -- below, "Text.RE" contains the toolkit for replacing captures, -- specifying options, etc. -- $re -- -- "Text.RE.PCRE.RE" contains the toolkit specific to the 'RE' type, -- the type generated by the gegex compiler.
cdornan/idiot
Text/RE/PCRE/ByteString.hs
Haskell
bsd-3-clause
2,516
<?php namespace Album\Model; use Zend\Db\ResultSet\ResultSet; use Zend\Db\Sql\Select; use Zend\Db\TableGateway\TableGateway; class AlbumTable { protected $tableGateway; public function __construct(TableGateway $tableGateway) { $this->tableGateway = $tableGateway; } public function fetchAll() { $resultSet = $this->tableGateway->select(); return $resultSet; } public function fetchAlbumsForSale() { $resultSet = $this->tableGateway->select(function (Select $select) { $select->where('for_sale', 1); }); return $resultSet; } /** * @param \DateTime $from * @param \DateTime $to * @return ResultSet */ public function fetchAlbumsForSaleWithReleaseDatesBetween(\DateTime $from, \DateTime $to) { $sfrom = $from->format("Y-m-d H:i:s"); $sto = $to->format("Y-m-d H:i:s"); $resultSet = $this->tableGateway->select(function (Select $select) use($sfrom, $sto) { $select->where->between('release_date', $sfrom, $sto); $select->where('for_sale', 1); }); return $resultSet; } public function getAlbum($id) { $id = (int) $id; $rowset = $this->tableGateway->select(array('id' => $id)); $row = $rowset->current(); if (!$row) { throw new \Exception("Could not find row $id"); } return $row; } public function saveAlbum(Album $album) { $data = array( 'artist' => $album->artist, 'title' => $album->title, ); $id = (int)$album->id; if ($id == 0) { $this->tableGateway->insert($data); } else { if ($this->getAlbum($id)) { $this->tableGateway->update($data, array('id' => $id)); } else { throw new \Exception('Form id does not exist'); } } } public function deleteAlbum($id) { $this->tableGateway->delete(array('id' => $id)); } }
asgrim/zf2-test-modules
module/Album/src/Album/Model/AlbumTable.php
PHP
bsd-3-clause
1,741
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <script type="text/javascript"> function show(elementName) { hp = document.getElementById(elementName); hp.style.visibility = "Visible"; } function hide(elementName) { hp = document.getElementById(elementName); hp.style.visibility = "Hidden"; } </script> <title> Application breakdown analysis </title> <style type="text/css" media="screen"> @import url('goog.css'); @import url('inlay.css'); @import url('soyc.css'); </style> </head> <body> <div class="g-doc"> <div id="hd" class="g-section g-tpl-50-50 g-split"> <div class="g-unit g-first"> <p> <a href="index.html" id="gwt-logo" class="soyc-ir"> <span>Google Web Toolkit</span> </a> </p> </div> <div class="g-unit"> </div> </div> <div id="soyc-appbar-lrg"> <div class="g-section g-tpl-75-25 g-split"> <div class="g-unit g-first"> <h1>Application breakdown analysis</h1> </div> <div class="g-unit"></div> </div> </div> <div id="bd"> <h2> <a style="cursor:default;" onMouseOver="show('packageBreakdownPopup');" onMouseOut="hide('packageBreakdownPopup');">Package breakdown</a> </h2></div> <div class="soyc-popup" id="packageBreakdownPopup"> <table> <tr><th><b>Package breakdown</b></th></tr> <tr><td>The package breakdown blames pieces of JavaScript code on Java packages wherever possible. Note that this is not possible for all code, so the sizes of the packages here will not normally add up to the full code size. More specifically, the sum will exclude strings, whitespace, and a few pieces of JavaScript code that are produced during compilation but cannot be attributed to any Java package.</td></tr> </table> </div> <iframe class='soyc-iframe-package' src="initial-6-packageBreakdown.html" scrolling=auto></iframe> <h2> <a style="cursor:default;" onMouseOver="show('codeTypeBreakdownPopup');" onMouseOut="hide('codeTypeBreakdownPopup');">Code Type Breakdown</a> </h2> <div class="soyc-popup" id="codeTypeBreakdownPopup"> <table> <tr><th><b>Code Type Breakdown</b></th></tr> <tr><td>The code type breakdown breaks down the JavaScript code according to its type or function. For example, it tells you how much of your code can be attributed to JRE, GWT-RPC, etc. As above, strings and some other JavaScript snippets are not included in the breakdown.</td></tr> </table> </div> <iframe class='soyc-iframe-code' src="initial-6-codeTypeBreakdown.html" scrolling=auto></iframe> </div> </div> </body> </html>
ToonTalk/mopix2
MoPiX/extras/Model/soycReport/compile-report/initial-6-overallBreakdown.html
HTML
bsd-3-clause
2,472
<!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.6.0_07) on Thu May 19 10:19:18 CEST 2011 --> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <TITLE> obvious.demo.sandbox (obvious-example 0.0.1-SNAPSHOT API) </TITLE> <META NAME="date" CONTENT="2011-05-19"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../obvious/demo/sandbox/package-summary.html" target="classFrame">obvious.demo.sandbox</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="IvtkTableAndPrefuseScatterplotDemo.html" title="class in obvious.demo.sandbox" target="classFrame">IvtkTableAndPrefuseScatterplotDemo</A> <BR> <A HREF="PrefuseNetworkAndJungNetworkVisDemo.html" title="class in obvious.demo.sandbox" target="classFrame">PrefuseNetworkAndJungNetworkVisDemo</A> <BR> <A HREF="PrefuseNetworkAndPolylithciPrefuseNetworkVisDemo.html" title="class in obvious.demo.sandbox" target="classFrame">PrefuseNetworkAndPolylithciPrefuseNetworkVisDemo</A> <BR> <A HREF="PrefuseTableAndPolylithicPrefuseScatterplotVisDemo.html" title="class in obvious.demo.sandbox" target="classFrame">PrefuseTableAndPolylithicPrefuseScatterplotVisDemo</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
jdfekete/obvious
obvious-example/target/site/apidocs/obvious/demo/sandbox/package-frame.html
HTML
bsd-3-clause
1,580
/* COPYRIGHT (C) 2012-2013 Alexander Taran. All Rights Reserved. */ /* Use of this source code is governed by a BSD-style license that can be found in the LICENSE file */ package alex.taran.opengl.mesh; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import android.opengl.GLES20; public class Mesh { public final Map<VertexAttribute, List<Float>> data = new HashMap<VertexAttribute, List<Float>>(); public int primitiveType; public boolean validate() { int primitiveSize = getPrimitiveSize(); if (primitiveSize == 0) { return false; } if (data.size() == 0) { return false; } int primitiveCount = -1; for (Entry<VertexAttribute, List<Float>> e: data.entrySet()) { if (e.getValue().size() % (primitiveSize * e.getKey().size()) != 0) { return false; } else if (primitiveCount < 0) { // calculate first time by any attribute primitiveCount = e.getValue().size() / (primitiveSize * e.getKey().size()); } else { // compare with already calculatedPrimitiveCount if (e.getValue().size() / (primitiveSize * e.getKey().size()) != primitiveCount) { return false; } } } return true; } public List<Float> generateVertexBuffer() { if (!validate()) { throw new RuntimeException("Bad Mesh"); } List<Float> buffer = new ArrayList<Float>(); for (Entry<VertexAttribute, List<Float>> e: data.entrySet()) { buffer.addAll(e.getValue()); } return buffer; } public MeshMeta generateMeshMeta() { if (!validate()) { throw new RuntimeException("Bad Mesh"); } int primitiveSize = getPrimitiveSize(); Entry<VertexAttribute, List<Float>> anAttribute = data.entrySet().iterator().next(); int primitiveCount = anAttribute.getValue().size() / (primitiveSize * anAttribute.getKey().size()); MeshMeta meshMeta = new MeshMeta(primitiveCount * primitiveSize, primitiveType); int offset = 0; for (Entry<VertexAttribute, List<Float>> e: data.entrySet()) { VertexAttributeParams params = new VertexAttributeParams(e.getKey().size(), offset); meshMeta.attributes.put(e.getKey().type(), params); // Size of a "float" * number of floats offset += 4 * e.getValue().size(); } return meshMeta; } private int getPrimitiveSize() { switch(primitiveType) { case GLES20.GL_POINTS: return 1; case GLES20.GL_LINES: return 2; case GLES20.GL_TRIANGLES: return 3; default: return 0; } } }
AlexTaran/picworld
AndroidOpenGL/src/alex/taran/opengl/mesh/Mesh.java
Java
bsd-3-clause
2,469
import itertools import numpy as np import pandas as pd import pytest from numpy.testing import assert_allclose from pvlib import atmosphere from pvlib import solarposition latitude, longitude, tz, altitude = 32.2, -111, 'US/Arizona', 700 times = pd.date_range(start='20140626', end='20140626', freq='6h', tz=tz) ephem_data = solarposition.get_solarposition(times, latitude, longitude) # need to add physical tests instead of just functional tests def test_pres2alt(): atmosphere.pres2alt(100000) def test_alt2press(): atmosphere.pres2alt(1000) @pytest.mark.parametrize("model", ['simple', 'kasten1966', 'youngirvine1967', 'kastenyoung1989', 'gueymard1993', 'young1994', 'pickering2002']) def test_airmass(model): out = atmosphere.relativeairmass(ephem_data['zenith'], model) assert isinstance(out, pd.Series) out = atmosphere.relativeairmass(ephem_data['zenith'].values, model) assert isinstance(out, np.ndarray) def test_airmass_scalar(): assert not np.isnan(atmosphere.relativeairmass(10)) def test_airmass_scalar_nan(): assert np.isnan(atmosphere.relativeairmass(100)) def test_airmass_invalid(): with pytest.raises(ValueError): atmosphere.relativeairmass(ephem_data['zenith'], 'invalid') def test_absoluteairmass(): relative_am = atmosphere.relativeairmass(ephem_data['zenith'], 'simple') atmosphere.absoluteairmass(relative_am) atmosphere.absoluteairmass(relative_am, pressure=100000) def test_absoluteairmass_numeric(): atmosphere.absoluteairmass(2) def test_absoluteairmass_nan(): np.testing.assert_equal(np.nan, atmosphere.absoluteairmass(np.nan)) def test_gueymard94_pw(): temp_air = np.array([0, 20, 40]) relative_humidity = np.array([0, 30, 100]) temps_humids = np.array( list(itertools.product(temp_air, relative_humidity))) pws = atmosphere.gueymard94_pw(temps_humids[:, 0], temps_humids[:, 1]) expected = np.array( [ 0.1 , 0.33702061, 1.12340202, 0.1 , 1.12040963, 3.73469877, 0.1 , 3.44859767, 11.49532557]) assert_allclose(pws, expected, atol=0.01) @pytest.mark.parametrize("module_type,expect", [ ('cdte', np.array( [[ 0.9905102 , 0.9764032 , 0.93975028], [ 1.02928735, 1.01881074, 0.98578821], [ 1.04750335, 1.03814456, 1.00623986]])), ('monosi', np.array( [[ 0.9776977 , 1.02043409, 1.03574032], [ 0.98630905, 1.03055092, 1.04736262], [ 0.98828494, 1.03299036, 1.05026561]])), ('polysi', np.array( [[ 0.9770408 , 1.01705849, 1.02613202], [ 0.98992828, 1.03173953, 1.04260662], [ 0.99352435, 1.03588785, 1.04730718]])), ('cigs', np.array( [[ 0.9745919 , 1.02821696, 1.05067895], [ 0.97529378, 1.02967497, 1.05289307], [ 0.97269159, 1.02730558, 1.05075651]])), ('asi', np.array( [[ 1.0555275 , 0.87707583, 0.72243772], [ 1.11225204, 0.93665901, 0.78487953], [ 1.14555295, 0.97084011, 0.81994083]])) ]) def test_first_solar_spectral_correction(module_type, expect): ams = np.array([1, 3, 5]) pws = np.array([1, 3, 5]) ams, pws = np.meshgrid(ams, pws) out = atmosphere.first_solar_spectral_correction(pws, ams, module_type) assert_allclose(out, expect, atol=0.001) def test_first_solar_spectral_correction_supplied(): # use the cdte coeffs coeffs = (0.87102, -0.040543, -0.00929202, 0.10052, 0.073062, -0.0034187) out = atmosphere.first_solar_spectral_correction(1, 1, coefficients=coeffs) expected = 0.99134828 assert_allclose(out, expected, atol=1e-3) def test_first_solar_spectral_correction_ambiguous(): with pytest.raises(TypeError): atmosphere.first_solar_spectral_correction(1, 1) def test_kasten96_lt(): """Test Linke turbidity factor calculated from AOD, Pwat and AM""" amp = np.array([1, 3, 5]) pwat = np.array([0, 2.5, 5]) aod_bb = np.array([0, 0.1, 1]) lt_expected = np.array( [[[1.3802, 2.4102, 11.6802], [1.16303976, 2.37303976, 13.26303976], [1.12101907, 2.51101907, 15.02101907]], [[2.95546945, 3.98546945, 13.25546945], [2.17435443, 3.38435443, 14.27435443], [1.99821967, 3.38821967, 15.89821967]], [[3.37410769, 4.40410769, 13.67410769], [2.44311797, 3.65311797, 14.54311797], [2.23134152, 3.62134152, 16.13134152]]] ) lt = atmosphere.kasten96_lt(*np.meshgrid(amp, pwat, aod_bb)) assert np.allclose(lt, lt_expected, 1e-3) return lt def test_angstrom_aod(): """Test Angstrom turbidity model functions.""" aod550 = 0.15 aod1240 = 0.05 alpha = atmosphere.angstrom_alpha(aod550, 550, aod1240, 1240) assert np.isclose(alpha, 1.3513924317859232) aod700 = atmosphere.angstrom_aod_at_lambda(aod550, 550, alpha) assert np.isclose(aod700, 0.10828110997681031) def test_bird_hulstrom80_aod_bb(): """Test Bird_Hulstrom broadband AOD.""" aod380, aod500 = 0.22072480948195175, 0.1614279181106312 bird_hulstrom = atmosphere.bird_hulstrom80_aod_bb(aod380, aod500) assert np.isclose(0.11738229553812768, bird_hulstrom)
uvchik/pvlib-python
pvlib/test/test_atmosphere.py
Python
bsd-3-clause
5,239
from django.conf.urls import patterns, url from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from django.template.response import TemplateResponse from django.utils.decorators import method_decorator from ..core.app import SatchlessApp from . import models class OrderApp(SatchlessApp): app_name = 'order' namespace = 'order' order_model = models.Order order_details_templates = [ 'satchless/order/view.html', 'satchless/order/%(order_model)s/view.html' ] order_list_templates = [ 'satchless/order/my_orders.html', 'satchless/order/%(order_model)s/my_orders.html' ] @method_decorator(login_required) def index(self, request): orders = self.order_model.objects.filter(user=request.user) context = self.get_context_data(request, orders=orders) format_data = { 'order_model': self.order_model._meta.model_name } templates = [p % format_data for p in self.order_list_templates] return TemplateResponse(request, templates, context) def details(self, request, order_token): order = self.get_order(request, order_token=order_token) context = self.get_context_data(request, order=order) format_data = { 'order_model': order._meta.model_name } templates = [p % format_data for p in self.order_details_templates] return TemplateResponse(request, templates, context) def get_order(self, request, order_token): if request.user.is_authenticated(): orders = self.order_model.objects.filter(user=request.user) else: orders = self.order_model.objects.filter(user=None) order = get_object_or_404(orders, token=order_token) return order def get_urls(self, prefix=None): prefix = prefix or self.app_name return patterns('', url(r'^$', self.index, name='index'), url(r'^(?P<order_token>[0-9a-zA-Z]+)/$', self.details, name='details'), ) order_app = OrderApp()
fusionbox/satchless
satchless/order/app.py
Python
bsd-3-clause
2,122
#ifndef DOUBANGO_CONFIG_H #define DOUBANGO_CONFIG_H #define DOUBANGO_IS_ALIGNED(p, a) (!((uintptr_t)(p) & ((a) - 1))) #define DOUBANGO_ASM_INLINE 1 #define DOUBANGO_INTRINSIC 1 #endif /* DOUBANGO_CONFIG_H */
DoubangoTelecom/libvpx_fast
source/config/win/ia32/doubango_config.h
C
bsd-3-clause
211
CPUFriend Installation & Usage =================================== ## WARNING **CPUFriend is most likely _NOT_ required when not sure whether or not to use it.** In most cases the native CPU power management data from `ACPI_SMC_PlatformPlugin` or `X86PlatformPlugin` work out of the box. Do NOT use CPUFriend for data customization until one knows clearly what *power management data* really is. Instead, changing SMBIOS, which results in other data being used, can be more reasonable. [FrequencyVectors.bt](https://github.com/acidanthera/CPUFriend/blob/master/Tools/FrequencyVectors.bt) can be a good start for the analysis of `FrequencyVectors`. *Another thing worth mentioning is that CPUFriend should NOT be used only for patching LFM (Low Frequency Mode), particularly on mobile models including MacBook series.* #### Technical background - Function `configResourceCallback()` from `ACPI_SMC_PlatformPlugin` or `X86PlatformPlugin` is hooked so as to handle customized CPU power management data from user. If nothing is provided, CPUFriend does nothing and the original data is to be used as if this kext is not installed. #### Installation Injection via bootloader is highly recommended, or [LiluFriend](https://github.com/PMheart/LiluFriend) may be needed to ensure full functionality when installing to system folders such as `/Library/Extensions`. Both `ACPI_SMC_PlatformPlugin` and `X86PlatformPlugin` should remain untouched. #### Available kernel flags Add `-cpufdbg` to enable debug logging (ONLY available in DEBUG binaries). Add `-cpufoff` to disable CPUFriend entirely. Add `-cpufbeta` to enable CPUFriend on unsupported OS versions. #### Configuration `Tools/ResourceConverter.sh` is meant to generate a working copy of either `CPUFriendDataProvider.kext` or `ssdt_data.dsl`, from which CPUFriend reads data. **NOTE:** Where there is another SSDT generated by [ssdtPRGen.sh](https://github.com/Piker-Alpha/ssdtPRGen.sh), combination between `ssdt_data.dsl` and the SSDT table produced by this script is required. See [Data Combination](https://github.com/acidanthera/CPUFriend/blob/master/Instructions.md#data-combination) for further details. For simplicity, `CPUFriendDataProvider.kext` is preferred in this case. #### Usage of ResourceConverter.sh `--kext /path/to/file` Create `CPUFriendDataProvider.kext` with information provided by `file`. `--acpi /path/to/file` Create `ssdt_data.dsl` with information provided by `file`. **NOTE:** - The kext/ssdt produced is located at the current working directory that can be revealed with `pwd`. - `file` should be a ***complete plist*** from `Recources` inside `ACPI_SMC_PlatformPlugin` or `X86PlatformPlugin` ***with certain modifications*** (Otherwise why is CPUFriend even required?) instead of something like a raw `FrequencyVectors` entry. #### Data Combination 1. Generate a correct copy of `ssdt_data.dsl` with `./ResourceConverter.sh --acpi /path/to/file`. 2. Open SSDT previously generated by [ssdtPRGen.sh](https://github.com/Piker-Alpha/ssdtPRGen.sh), and search for `Method (_DSM, 4, NotSerialized)` in a text editor. 3. Paste `"cf-frequency-data"` entry from `ssdt_data.dsl` to the SSDT generated by [ssdtPRGen.sh](https://github.com/Piker-Alpha/ssdtPRGen.sh). A glance at the final work looks as follows. ``` // // Context of the SSDT generated by ssdtPRGen.sh // Method (_DSM, 4, NotSerialized) { If (LEqual (Arg2, Zero)) { Return (Buffer (One) { 0x03 }) } Return (Package () // size removed { "plugin-type", One, // // Paste it from ssdt_data.dsl // "cf-frequency-data", Buffer () // size removed { // Data from ssdt_data.dsl } }) } // // Context of the SSDT generated by ssdtPRGen.sh // ```
PMheart/CPUFriend
Instructions.md
Markdown
bsd-3-clause
3,756
module SlaeGauss where import Data.Bifunctor import qualified Data.Matrix as Mx import qualified Data.Vector as Vec import Library compute :: Matrix -> Either ComputeError Vector compute = fmap backtrackPermuted . triangulate where backtrackPermuted (mx, permutations) = Vec.map (backtrack mx Vec.!) permutations triangulate :: Matrix -> Either ComputeError (Matrix, Permutations) triangulate mx = first Mx.fromRows <$> go 0 permutations rows where rows = Mx.toRows mx permutations = Vec.fromList [0..(length rows - 1)] go :: Int -> Permutations -> [Vector] -> Either ComputeError ([Vector], Permutations) go _ ps [] = Right ([], ps) go j ps m@(as:ass) | isLastCol = Right (m, ps) | isZeroPivot = Left SingularMatrix | otherwise = first (as':) <$> go (j + 1) ps' (map updRow ass') where isLastCol = j + 2 >= Vec.length as isZeroPivot = nearZero as'j as'j = as' Vec.! j (as':ass', ps') = permuteToMax j ps m updRow bs = Vec.zipWith op as' bs where k = bs Vec.! j / as'j op a b = b - a * k permuteToMax :: Int -> Permutations -> [Vector] -> ([Vector], Permutations) permuteToMax col ps m = ( Mx.toRows $ permuteRows 0 i $ permuteCols col j $ Mx.fromRows m , swapComponents col j ps ) where (i, j, _) = foldr imax (0, 0, 0) $ zip [0..] m imax :: (Int, Vec.Vector Double) -> (Int, Int, Double) -> (Int, Int, Double) imax (i, v) oldMax@(_, _, max) | rowMax > max = (i, j + col, rowMax) | otherwise = oldMax where (j, rowMax) = Vec.ifoldl vimax (0, 0) (Vec.drop col $ Vec.init v) vimax :: (Int, Double) -> Int -> Double -> (Int, Double) vimax (i, max) k a | a > max = (k, a) | otherwise = (i, max) permuteRows :: Int -> Int -> Matrix -> Matrix permuteRows i k = Mx.fromColumns . map (swapComponents i k) . Mx.toColumns permuteCols :: Int -> Int -> Matrix -> Matrix permuteCols i k = Mx.fromRows . map (swapComponents i k) . Mx.toRows swapComponents :: Int -> Int -> Vec.Vector a -> Vec.Vector a swapComponents i k v = Vec.imap cmpSelector v where cmpSelector j el | j == i = v Vec.! k | j == k = v Vec.! i | otherwise = el backtrack :: Matrix -> Vector backtrack = foldr eqSolver Vec.empty . Mx.toRows eqSolver :: Vector -> Vector -> Vector eqSolver as xs = Vec.cons ((Vec.last as' - Vec.sum (resolveKnown as' xs)) / Vec.head as') xs where as' = Vec.dropWhile nearZero as resolveKnown :: Vector -> Vector -> Vector resolveKnown as xs = Vec.zipWith (*) xs (Vec.tail $ Vec.init as)
hrsrashid/nummet
lib/SlaeGauss.hs
Haskell
bsd-3-clause
2,689
// ***************************************************************************** // // Copyright (c) 2014, Southwest Research Institute® (SwRI®) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Southwest Research Institute® (SwRI®) nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // ***************************************************************************** #include <ros/ros.h> #include <nodelet/loader.h> int main(int argc, char **argv) { ros::init(argc, argv, "scale_image", ros::init_options::AnonymousName); nodelet::Loader manager(false); nodelet::M_string remappings; nodelet::V_string my_argv; manager.load(ros::this_node::getName(), "image_util/scale_image", remappings, my_argv); ros::spin(); return 0; }
malban/marti_common
image_util/src/nodes/scale_image.cpp
C++
bsd-3-clause
2,167
"""Utility functions for handling and fetching repo archives in zip format.""" from __future__ import absolute_import import os import tempfile from zipfile import ZipFile import requests try: # BadZipfile was renamed to BadZipFile in Python 3.2. from zipfile import BadZipFile except ImportError: from zipfile import BadZipfile as BadZipFile from cookiecutter.exceptions import InvalidZipRepository from cookiecutter.prompt import read_repo_password from cookiecutter.utils import make_sure_path_exists, prompt_and_delete def unzip(zip_uri, is_url, clone_to_dir='.', no_input=False, password=None): """Download and unpack a zipfile at a given URI. This will download the zipfile to the cookiecutter repository, and unpack into a temporary directory. :param zip_uri: The URI for the zipfile. :param is_url: Is the zip URI a URL or a file? :param clone_to_dir: The cookiecutter repository directory to put the archive into. :param no_input: Suppress any prompts :param password: The password to use when unpacking the repository. """ # Ensure that clone_to_dir exists clone_to_dir = os.path.expanduser(clone_to_dir) make_sure_path_exists(clone_to_dir) if is_url: # Build the name of the cached zipfile, # and prompt to delete if it already exists. identifier = zip_uri.rsplit('/', 1)[1] zip_path = os.path.join(clone_to_dir, identifier) if os.path.exists(zip_path): download = prompt_and_delete(zip_path, no_input=no_input) else: download = True if download: # (Re) download the zipfile r = requests.get(zip_uri, stream=True) with open(zip_path, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) else: # Just use the local zipfile as-is. zip_path = os.path.abspath(zip_uri) # Now unpack the repository. The zipfile will be unpacked # into a temporary directory try: zip_file = ZipFile(zip_path) if len(zip_file.namelist()) == 0: raise InvalidZipRepository( 'Zip repository {} is empty'.format(zip_uri) ) # The first record in the zipfile should be the directory entry for # the archive. If it isn't a directory, there's a problem. first_filename = zip_file.namelist()[0] if not first_filename.endswith('/'): raise InvalidZipRepository( 'Zip repository {} does not include ' 'a top-level directory'.format(zip_uri) ) # Construct the final target directory project_name = first_filename[:-1] unzip_base = tempfile.mkdtemp() unzip_path = os.path.join(unzip_base, project_name) # Extract the zip file into the temporary directory try: zip_file.extractall(path=unzip_base) except RuntimeError: # File is password protected; try to get a password from the # environment; if that doesn't work, ask the user. if password is not None: try: zip_file.extractall( path=unzip_base, pwd=password.encode('utf-8') ) except RuntimeError: raise InvalidZipRepository( 'Invalid password provided for protected repository' ) elif no_input: raise InvalidZipRepository( 'Unable to unlock password protected repository' ) else: retry = 0 while retry is not None: try: password = read_repo_password('Repo password') zip_file.extractall( path=unzip_base, pwd=password.encode('utf-8') ) retry = None except RuntimeError: retry += 1 if retry == 3: raise InvalidZipRepository( 'Invalid password provided ' 'for protected repository' ) except BadZipFile: raise InvalidZipRepository( 'Zip repository {} is not a valid zip archive:'.format(zip_uri) ) return unzip_path
luzfcb/cookiecutter
cookiecutter/zipfile.py
Python
bsd-3-clause
4,640
from base import StreetAddressValidation, AddressValidation UPS_XAV_CONNECTION = 'https://onlinetools.ups.com/ups.app/xml/XAV' UPS_XAV_CONNECTION_TEST = 'https://wwwcie.ups.com/ups.app/xml/XAV' UPS_AV_CONNECTION = 'https://onlinetools.ups.com/ups.app/xml/AV' UPS_AV_CONNECTION_TEST = 'https://wwwcie.ups.com/ups.app/xml/AV'
cuker/python-ups
ups/addressvalidation/__init__.py
Python
bsd-3-clause
326
<div> <ng-form class="form-horizontal" name="settingForm" os-form-validator="settingForm" novalidate> <div class="form-group"> <label class="col-xs-2 control-label" translate="settings.property">Property</label> <div class="form-value col-xs-10"> <span>{{'settings.' + setting.module + '.' + setting.name | translate}}</span> </div> </div> <div class="form-group"> <label class="col-xs-2 control-label" translate="settings.description">Description</label> <div class="form-value col-xs-10"> <span>{{'settings.' + setting.module + '.' + setting.name + '_desc' | translate}}</span> </div> </div> <div class="form-group"> <label class="col-xs-2 control-label" translate="settings.existing_value">Existing Value</label> <div class="form-value col-xs-10" ng-switch on="setting.type"> <span ng-switch-when="BOOLEAN"> {{existingSetting.value | osBoolValue: 'common.enabled': 'common.disabled': 'common.not_specified'}} </span> <span ng-switch-when="CHAR" ng-switch on="existingSetting.value.charCodeAt(0) <= 32"> <span ng-switch-when="true">Code: {{existingSetting.value.charCodeAt(0)}}</span> <span ng-switch-default>{{existingSetting.value | osNoValue}}</span> </span> <span ng-switch-default> {{existingSetting.value | osNoValue}} </span> </div> </div> <div class="form-group"> <label class="col-xs-2 control-label" translate="settings.last_updated">Last Updated</label> <div class="form-value col-xs-10"> <span translate="{{setting.activationDate | date: global.dateFmt}}"></span> </div> </div> <div class="form-group"> <label class="col-xs-2 control-label" translate="settings.new_value">New Value</label> <div class="col-xs-10"> <input type="text" name="value" class="form-control" ng-model="setting.value" ng-if="setting.type == 'STRING' && !setting.secured"></input> <input type="password" name="value" class="form-control" ng-model="setting.value" ng-if="setting.type == 'STRING' && setting.secured"></input> <input type="text" name="value" class="form-control" ng-model="setting.value" ng-maxlength="1" ng-if="setting.type == 'CHAR'" ng-trim="false"></input> <input type="text" name="value" class="form-control" ng-model="setting.value" ng-pattern="/^[0-9]*$/" ng-if="setting.type == 'INT'"></input> <div ng-if="setting.type == 'BOOLEAN'"> <div class="btn-group"> <button type="button" class="btn btn-default" name="value" ng-model="setting.value" btn-radio="'true'" required translate="common.enabled">Enabled</button> <button type="button" class="btn btn-default" name="value" ng-model="setting.value" btn-radio="'false'" required translate="common.disabled">Disabled</button> </div> </div> <div ng-if="setting.type == 'FILE'"> <form action="{{fileCtx.uploadUrl}}"> <div os-file-upload ctrl="fileCtx.ctrl"></div> </form> </div> <div os-field-error field="settingForm.value"></div> </div> </div> <div class="os-divider"></div> <div class="form-group"> <div class="col-xs-offset-2 col-xs-10"> <button type="submit" class="btn btn-primary" os-form-submit="submit()"> <span translate="common.buttons.update">Update</span> </button> <button class="btn os-btn-text" os-form-cancel="cancel()"> <span translate="common.buttons.cancel">Cancel</span> </button> </div> </div> </ng-form> </div>
krishagni/openspecimen
www/app/modules/administrative/settings/edit-setting.html
HTML
bsd-3-clause
3,764
<?php namespace R2Crm\Entity; class Project { }
mediaforce/ecomart
module/R2Crm/src/R2Crm/Entity/Project.php
PHP
bsd-3-clause
49
# `dev-master` * [#470](https://github.com/atoum/atoum/pull/470) Add `isNotEmpty` asserter on `array` ([@metalaka]) # 2.1.0 - 2015-05-08 * [#459](https://github.com/atoum/atoum/issues/459) Support branches and paths coverage with [Xdebug](http://xdebug.org/) 2.3 ([@jubianchi]) * [#436](https://github.com/atoum/atoum/issues/436) Support old-style constructors in mocks ([@jubianchi]) * [#453](https://github.com/atoum/atoum/issues/453) `phpClass` asserter will throw atoum's logic exceptions instead of native reflection exceptions ([@jubianchi]) * [#340](https://github.com/atoum/atoum/issues/340) Fixed an error when using `DebugClassLoader` autoloader and [atoum-bundle](https://github.com/atoum/AtoumBundle) ([@jubianchi]) * [#454](https://github.com/atoum/atoum/pull/454) Rename asserters classes for PHP7 ([@jubianchi]) * [#457](https://github.com/atoum/atoum/pull/457) Removed usage of die in deprecated methods ([@jubianchi]) * [#442](https://github.com/atoum/atoum/issues/442) [#444](https://github.com/atoum/atoum/pull/444) Properly report skipped method due to a missing extension ([@jubianchi]) * [#441](https://github.com/atoum/atoum/pull/441) Add PHP 7.0 in the build matrix ([@jubianchi]) * [#399](https://github.com/atoum/atoum/pull/399) Add the `let` assertion handler ([@hywan]) * [#443](https://github.com/atoum/atoum/pull/443) Autoloader should resolve classes step by step ([@jubianchi]) # 2.0.1 - 2015-02-27 * [#440](https://github.com/atoum/atoum/pull/440) `--configurations` option should be handled first ([@jubianchi]) * [#439](https://github.com/atoum/atoum/pull/439) Since atoum is 2.*, branch-alias must follow ([@hywan]) * [#437](https://github.com/atoum/atoum/pull/437) Autoloader should not try to resolve alias if requested class exists ([@jubianchi]) * Generalize method call checking in mock ([@mageekguy]) * [#435](https://github.com/atoum/atoum/pull/435) Partially revert BC break introduced in [#420](https://github.com/atoum/atoum/pull/420) ([@mageekguy]) # 2.0.0 - 2015-02-13 ## BC break updates * [#420](https://github.com/atoum/atoum/pull/420) `atoum\test::beforeTestMethod` is called before the tested class is loaded (@mageekguy) ## Other updates * [#431](https://github.com/atoum/atoum/pull/431) Tested class should not be mock as an interface. (@mageekguy) * [#430](https://github.com/atoum/atoum/pull/430) Add `atoum\mock\generator::allIsInterface()` to definitely disable all parent classes' behaviors in mocks (@mageekguy) * [#427](https://github.com/atoum/atoum/pull/427) `atoum\asserters\mock::receive` is an alias to `atoum\asserters\mock::call` (@mageekguy) # 1.2.2 - 2015-01-12 * #415 Fix a bug in the coverage report with excluded classes (@mageekguy) * #406 Fix a bug in the HTML coverage with stylesheet URLs (@jubianchi) * #418 Fix a bug when a mocked method returns a reference (@hywan) # 1.2.1 - 2015-01-09 * #413 Fix a bug in the exit code management (@mageekguy) * #412 Use semantics dates in `CHANGELOG.md` (@hywan) # 1.2.0 - 2014-12-28 * #408 Extract mock autoloader (@jubianchi) * #403 Fix a bug when setting the default mock namespace (@hywan) * #387 Support assertion without parenthesis on `dateInterval`, `error`, `extension` and `hash` asserters (@jubianchi) * #401 Use new Travis container infrastructure (@jubianchi) * #405 Add the Santa report and an example configuration file (@jubianchi) * #394 Mock generator now handles variadic arguments in method (@jubianchi) * #398 Replace broken documentation links (@jubianchi) * #396 Rename `match` to `matches` on the string asserter (@hywan) * #385 Rename the PHAR to `atoum.phar` (@hywan) * #392 Fix broken links in `README.md` (@evert) * #391 Add dates in `CHANGELOG.md` (@hywan) * #379 Fix `newTestedInstance` assertion when constructor contains a variable-length argument (@mageekguy) # 1.1.0 - 2014-12-09 * #377 Hide error when publishing report to coveralls.io fails (@jubianchi) * #368 Improve dataset key reporting in case of failure (@mageekguy) * #376 Add branch-alias (@stephpy, @hywan) * #367 Add the `isFinal` assertion on the `phpClass`/`class`/`testedClass` asserters (@mageekguy) # 1.0.0 - 2014-12-01 * Allow/Disallow mocking undefined methods * Pass test instance as first parameters of closures in `exception`, `when`, `output` * Add `--fail-if-void-methods` and `--fail-if-skipped-methods` * `--init` option now accepts a path to a directory to initialize with atoum configuration * Add coverage script to automatically produce reports * Add `isFluent` * Add `isNull`, `isNotNull`, `isCallable`, `isNotCallable`, `isNotTrue`, `isNotFalse` assertions on `variable` * Add `isTestedInstance` assertion on `object` asserter * Add `testedInstance` helper * Add `newTestedInstance` and `newInstance` helpers * Add `isNotInstanceOf` assertion on `object` asserter * Alias assertions from test classes * Register asserters from test classes * Define new assertion directly from test classes * Change test method prefix using `@methodPrefix` on test classes * Add `CHANGELOG.md` # 0.0.1 - 2013-11-05 [@mageekguy]: https://github.com/mageekguy [@jubianchi]: https://github.com/jubianchi [@hywan]: https://github.com/hywan [@metalaka]: https://github.com/metalaka
tejerka/atoum
CHANGELOG.md
Markdown
bsd-3-clause
5,215
.cell { position: relative; display: flex; align-content: flex-start; flex-direction: column; } .text > .main-content { padding-left: 8px; } .inputarea, .text-top-div { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit-flex-flow: row; flex-flow: row; } .code .inputarea { /* editor resizes to this height on focus*/ min-height: 24px; } .markdown { flex: 1; } .editor { flex: 1; } .formview { padding: 4px 8px; flex: 1; } .formview-input { width: 70% } .formview-full { width: 100%; } .dragitem { visibility: hidden; height: 20px; } pre { margin-top: 2px; margin-bottom: 2px; white-space: pre-wrap; } .completions { position: absolute; z-index: 10; overflow: hidden; border: 1px solid #ababab; border-radius: 4px; -webkit-box-shadow: 0px 6px 10px -1px #adadad; -moz-box-shadow: 0px 6px 10px -1px #adadad; box-shadow: 0px 6px 10px -1px #adadad; } .execution-count { min-width: 32px; text-align: center; background-color: white; font-family: monospace; padding: 4px 0 0 4px; margin-top: 7px; } .code.out-of-date * .output-info > .collaborator-img-me { opacity: .4; } .code.up-to-date * .output-info > .collaborator-img-me { opacity: 1.0; } .code.out-of-date * .execution-count { color: gray; } .code.up-to-date * .execution-count { color: black; } .code .editor { border: 1px solid #ededed; background: #f7f7f7; margin: 4px; padding: 4px; } .text * .editor { display: none; } .text.edit * .editor { border-top: 1px dashed grey; display: block; } .main-content { background: white; } .paper-shadow-bottom, .paper-shadow-top { pointer-events: none; } .paper-shadow-top { border-radius: inherit; position: absolute; left: 0; right: 0; top: 0; bottom: 0; } .main-content > .paper-shadow-bottom, .main-content > .paper-shadow-top { bottom: 8px; } .cell-collaborators > .paper-shadow-bottom, .cell-collaborators > .paper-shadow-top { right: 4px; } .code * .main-content { border-radius: 2px; } .code * .editor.non-trusted * .CodeMirror-gutters { background: #ECC4C4; } .code * .editor.non-trusted * .CodeMirror-linenumber { color: black; pointer-events: none; } .output { font-family: monospace; font-size: 10pt; } .output-content { padding: 4px 0 4px 0; display: flex; } .output-info { width: 40px; text-align: center; } .output-iframe-container { flex: 1; } .output-iframe-container > iframe { width: 100%; border: 0px; } .raw-input-container { font-family: monospace; font-size: 10pt; margin-left: 40px; } .editor > .CodeMirror { background: transparent; } .CodeMirror { height: auto; overflow-x: hidden; line-height: 1.08; } .CodeMirror-scroll { height: auto; overflow-y: hidden; overflow-x: hidden; } .CodeMirror-hscrollbar { overflow-x:hidden } .cell-collaborators { position: absolute; right: -30px; z-index: 12; /* make sure the collaborators stays behind the header */ } .cell-comments { width: 130px; height: 50px; position: relative; display: inline-block; background: #fff; border: solid 1px #cbcbcb; box-shadow: 0 2px 4px rgba(0,0,0,.2); padding: 0 10px 0 10px; } .cell-spacer{ display: inline-block; width: 10px; position: relative; } .cell-comments-area { display: none; position: absolute; top: 30px; right: -200px; z-index: 12; /* make sure the collaborators stays behind the header */ } .selected > .cell-comments-area { display: block; } div.formview-title { display: inline-flex; justify-content: space-between; width: 100%; } div.formview-title-text { font-size: 12pt; font-weight: 700; } div.formview-title > .goog-button { background: white; border: 1px solid black; } div.formview-title > .goog-button:hover { background: lightgrey; } .add-cell { height: 16px; z-index: 20; margin-top: -4px; margin-bottom: -4px; margin-right: 4px; } .add-cell:hover { background: #f9f9f9; } .notebook-content > .add-cell { position: relative; } .add-cell > hr { margin: 7px auto 0 auto; width: 144px; border-style: solid; border-top: none; border-color: lightgrey; visibility: hidden; border-width: 2px; } .add-cell:hover > hr { visibility: visible; } .notebook-content > .add-cell > hr { padding-top: 8px; border-left: none; border-right: none; } .add-button { position: absolute; width: 32px; height: 32px; margin-top: -8px; border-radius: 50%; background-color: white; text-align: center; line-height: 32px; font-size: 12pt; font-weight: 500; border: 1px solid transparent !important; } .add-code { left: 0; font-family: monospace; } .add-text { left: 100px; } .add-button:hover { cursor: default; border: 1px solid #a1badf !important; }
jupyter/colaboratory
colaboratory/resources/colab/css/cell.css
CSS
bsd-3-clause
4,874
<div class="User-default-index"> <h1><?= $this->context->action->uniqueId ?></h1> <p> This is the view content for action "<?= $this->context->action->id ?>". The action belongs to the controller "<?= get_class($this->context) ?>" in the "<?= $this->context->module->id ?>" module. </p> <p> <h4 style="color:blue;">根据之前的module进行整合,无法使用app定位,故将modules放到common中,前后台均可调用此module</h4> You may customize this page by editing the following file:<br> <code><?= __FILE__ ?></code> </p> </div>
mingzhehao/sy-yii2-lte
common/modules/user/views/default/index.php
PHP
bsd-3-clause
614
import code import sys from awesomestream.jsonrpc import Client def main(): try: host = sys.argv[1] except IndexError: host = 'http://localhost:9997/' banner = """>>> from awesomestream.jsonrpc import Client >>> c = Client('%s')""" % (host,) c = Client(host) code.interact(banner, local={'Client': Client, 'c': c}) if __name__ == '__main__': main()
ericflo/awesomestream
awesomestream/repl.py
Python
bsd-3-clause
391
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/files/file_util.h" #include "base/strings/stringprintf.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/media/media_stream_devices_controller.h" #include "chrome/browser/media/webrtc_browsertest_base.h" #include "chrome/browser/media/webrtc_browsertest_common.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/website_settings/permission_bubble_manager.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/test_switches.h" #include "chrome/test/base/ui_test_utils.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/content_settings_types.h" #include "content/public/browser/notification_service.h" #include "content/public/common/content_switches.h" #include "content/public/common/media_stream_request.h" #include "content/public/common/origin_util.h" #include "content/public/test/browser_test_utils.h" #include "media/base/media_switches.h" #include "net/dns/mock_host_resolver.h" #include "net/test/spawned_test_server/spawned_test_server.h" // MediaStreamPermissionTest --------------------------------------------------- class MediaStreamPermissionTest : public WebRtcTestBase { public: MediaStreamPermissionTest() {} ~MediaStreamPermissionTest() override {} // InProcessBrowserTest: void SetUpCommandLine(base::CommandLine* command_line) override { // This test expects to run with fake devices but real UI. command_line->AppendSwitch(switches::kUseFakeDeviceForMediaStream); EXPECT_FALSE(command_line->HasSwitch(switches::kUseFakeUIForMediaStream)) << "Since this test tests the UI we want the real UI!"; } protected: content::WebContents* LoadTestPageInTab() { return LoadTestPageInBrowser(browser()); } content::WebContents* LoadTestPageInIncognitoTab() { return LoadTestPageInBrowser(CreateIncognitoBrowser()); } // Returns the URL of the main test page. GURL test_page_url() const { const char kMainWebrtcTestHtmlPage[] = "files/webrtc/webrtc_jsep01_test.html"; return test_server()->GetURL(kMainWebrtcTestHtmlPage); } private: content::WebContents* LoadTestPageInBrowser(Browser* browser) { EXPECT_TRUE(test_server()->Start()); // Uses the default server. GURL url = test_page_url(); EXPECT_TRUE(content::IsOriginSecure(url)); ui_test_utils::NavigateToURL(browser, url); return browser->tab_strip_model()->GetActiveWebContents(); } // Dummy callback for when we deny the current request directly. static void OnMediaStreamResponse(const content::MediaStreamDevices& devices, content::MediaStreamRequestResult result, scoped_ptr<content::MediaStreamUI> ui) {} DISALLOW_COPY_AND_ASSIGN(MediaStreamPermissionTest); }; // Actual tests --------------------------------------------------------------- IN_PROC_BROWSER_TEST_F(MediaStreamPermissionTest, TestAllowingUserMedia) { content::WebContents* tab_contents = LoadTestPageInTab(); EXPECT_TRUE(GetUserMediaAndAccept(tab_contents)); } IN_PROC_BROWSER_TEST_F(MediaStreamPermissionTest, TestDenyingUserMedia) { content::WebContents* tab_contents = LoadTestPageInTab(); GetUserMediaAndDeny(tab_contents); } IN_PROC_BROWSER_TEST_F(MediaStreamPermissionTest, TestDismissingRequest) { content::WebContents* tab_contents = LoadTestPageInTab(); GetUserMediaAndDismiss(tab_contents); } IN_PROC_BROWSER_TEST_F(MediaStreamPermissionTest, TestDenyingUserMediaIncognito) { content::WebContents* tab_contents = LoadTestPageInIncognitoTab(); GetUserMediaAndDeny(tab_contents); } IN_PROC_BROWSER_TEST_F(MediaStreamPermissionTest, TestSecureOriginDenyIsSticky) { content::WebContents* tab_contents = LoadTestPageInTab(); EXPECT_TRUE(content::IsOriginSecure(tab_contents->GetLastCommittedURL())); GetUserMediaAndDeny(tab_contents); GetUserMediaAndExpectAutoDenyWithoutPrompt(tab_contents); } IN_PROC_BROWSER_TEST_F(MediaStreamPermissionTest, TestSecureOriginAcceptIsSticky) { content::WebContents* tab_contents = LoadTestPageInTab(); EXPECT_TRUE(content::IsOriginSecure(tab_contents->GetLastCommittedURL())); EXPECT_TRUE(GetUserMediaAndAccept(tab_contents)); GetUserMediaAndExpectAutoAcceptWithoutPrompt(tab_contents); } IN_PROC_BROWSER_TEST_F(MediaStreamPermissionTest, TestDismissIsNotSticky) { content::WebContents* tab_contents = LoadTestPageInTab(); GetUserMediaAndDismiss(tab_contents); GetUserMediaAndDismiss(tab_contents); } IN_PROC_BROWSER_TEST_F(MediaStreamPermissionTest, TestDenyingThenClearingStickyException) { content::WebContents* tab_contents = LoadTestPageInTab(); GetUserMediaAndDeny(tab_contents); GetUserMediaAndExpectAutoDenyWithoutPrompt(tab_contents); HostContentSettingsMap* settings_map = HostContentSettingsMapFactory::GetForProfile(browser()->profile()); settings_map->ClearSettingsForOneType(CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC); settings_map->ClearSettingsForOneType( CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA); GetUserMediaAndDeny(tab_contents); } IN_PROC_BROWSER_TEST_F(MediaStreamPermissionTest, DenyingMicDoesNotCauseStickyDenyForCameras) { content::WebContents* tab_contents = LoadTestPageInTab(); GetUserMediaWithSpecificConstraintsAndDeny(tab_contents, kAudioOnlyCallConstraints); EXPECT_TRUE(GetUserMediaWithSpecificConstraintsAndAccept( tab_contents, kVideoOnlyCallConstraints)); } IN_PROC_BROWSER_TEST_F(MediaStreamPermissionTest, DenyingCameraDoesNotCauseStickyDenyForMics) { content::WebContents* tab_contents = LoadTestPageInTab(); GetUserMediaWithSpecificConstraintsAndDeny(tab_contents, kVideoOnlyCallConstraints); EXPECT_TRUE(GetUserMediaWithSpecificConstraintsAndAccept( tab_contents, kAudioOnlyCallConstraints)); }
Bysmyyr/chromium-crosswalk
chrome/browser/media/chrome_media_stream_infobar_browsertest.cc
C++
bsd-3-clause
6,574
package org.speedfirst.leetcode.array; import java.util.ArrayList; import java.util.Arrays; /** * Created by jiankuan on 11/4/14. */ public class FindKthElement { //param k : description of k //param numbers : array of numbers //return: description of return public int kthLargestElement(int k, ArrayList<Integer> numbers) { doQuickSelect(k - 1, numbers, 0, numbers.size() - 1); return numbers.get(k - 1); } // quick select solution public void doQuickSelect(int k, ArrayList<Integer> numbers, int s, int e) { if (s >= e) { return; } int pivot = numbers.get(e); // left number as pivot int left = s; for (int i = left; i < e; i++) { if (numbers.get(i) > pivot) { swap(numbers, i, left); left++; } } swap(numbers, left, e); if (left > k) { doQuickSelect(k, numbers, s, left - 1); } else { doQuickSelect(k, numbers, left + 1, e); } } private void swap(ArrayList<Integer> numbers, int i, int j) { int tmp = numbers.get(i); numbers.set(i, numbers.get(j)); numbers.set(j, tmp); } public static void main(String[] args) { FindKthElement f = new FindKthElement(); ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(9, 3, 2, 4, 8)); System.out.println(f.kthLargestElement(1, (ArrayList<Integer>) numbers.clone())); System.out.println(f.kthLargestElement(2, (ArrayList<Integer>) numbers.clone())); System.out.println(f.kthLargestElement(3, (ArrayList<Integer>) numbers.clone())); System.out.println(f.kthLargestElement(4, (ArrayList<Integer>) numbers.clone())); System.out.println(f.kthLargestElement(5, (ArrayList<Integer>) numbers.clone())); } }
speedfirst/leetcode
java/src/main/java/org/speedfirst/leetcode/array/FindKthElement.java
Java
bsd-3-clause
1,875
<?php /** * MultiFormStep controls the behaviour of a single form step in the MultiForm * process. All form steps are required to be subclasses of this class, as it * encapsulates the functionality required for the step to be aware of itself * in the process by knowing what it's next step is, and if applicable, it's previous * step. * * @package multiform */ class MultiFormStep extends DataObject { private static $db = array( 'Data' => 'Text' // stores serialized maps with all session information ); private static $has_one = array( 'Session' => 'MultiFormSession' ); /** * Centerpiece of the flow control for the form. * * If set to a string, you have a linear form flow * If set to an array, you should use {@link getNextStep()} * to enact flow control and branching to different form * steps, most likely based on previously set session data * (e.g. a checkbox field or a dropdown). * * @var array|string */ public static $next_steps; /** * Each {@link MultiForm} subclass needs at least * one step which is marked as the "final" one * and triggers the {@link MultiForm->finish()} * method that wraps up the whole submission. * * @var boolean */ public static $is_final_step = false; /** * This variable determines whether a user can use * the "back" action from this step. * * @TODO This does not check if the arbitrarily chosen step * using the step indicator is actually a previous step, so * unless you remove the link from the indicator template, or * type in StepID=23 to the address bar you can still go back * using the step indicator. * * @var boolean */ protected static $can_go_back = true; /** * Title of this step. * * Used for the step indicator templates. * * @var string */ protected $title; /** * Form class that this step is directly related to. * * @var MultiForm subclass */ protected $form; /** * List of additional CSS classes for this step * * @var array $extraClasses */ protected $extraClasses = array(); /** * Form fields to be rendered with this step. * (Form object is created in {@link MultiForm}. * * This function needs to be implemented on your * subclasses of MultiFormStep. * * @return FieldList */ public function getFields() { user_error('Please implement getFields on your MultiFormStep subclass', E_USER_ERROR); } /** * Additional form actions to be added to this step. * (Form object is created in {@link MultiForm}. * * Note: This is optional, and is to be implemented * on your subclasses of MultiFormStep. * * @return FieldList */ public function getExtraActions() { return (class_exists('FieldList')) ? new FieldList() : new FieldSet(); } /** * Get a validator specific to this form. * The form is automatically validated in {@link Form->httpSubmission()}. * * @return Validator */ public function getValidator() { return false; } /** * Accessor method for $this->title * * @return string Title of this step */ public function getTitle() { return $this->title ? $this->title : $this->class; } /** * Gets a direct link to this step (only works * if you're allowed to skip steps, or this step * has already been saved to the database * for the current {@link MultiFormSession}). * * @return string Relative URL to this step */ public function Link() { $form = $this->form; return Controller::join_links($form->getDisplayLink(), "?{$form->config()->get_var}={$this->Session()->Hash}"); } /** * Unserialize stored session data and return it. * This is used for loading data previously saved * in session back into the form. * * You need to overload this method onto your own * step if you require custom loading. An example * would be selective loading specific fields, leaving * others that are not required. * * @return array */ public function loadData() { return ($this->Data && is_string($this->Data)) ? unserialize($this->Data) : array(); } /** * Save the data for this step into session, serializing it first. * * To selectively save fields, instead of it all, this * method would need to be overloaded on your step class. * * @param array $data The processed data from save() on {@link MultiForm} */ public function saveData($data) { $this->Data = serialize($data); $this->write(); } /** * Save the data on this step into an object, * similiar to {@link Form->saveInto()} - by building * a stub form from {@link getFields()}. This is necessary * to trigger each {@link FormField->saveInto()} method * individually, rather than assuming that all data * serialized through {@link saveData()} can be saved * as a simple value outside of the original FormField context. * * @param DataObject $obj */ public function saveInto($obj) { $form = new Form( Controller::curr(), 'Form', $this->getFields(), ((class_exists('FieldList')) ? new FieldList() : new FieldSet()) ); $form->loadDataFrom($this->loadData()); $form->saveInto($obj); return $obj; } /** * Custom validation for a step. In most cases, it should be sufficient * to have built-in validation through the {@link Validator} class * on the {@link getValidator()} method. * * Use {@link Form->sessionMessage()} to feed back validation messages * to the user. Please don't redirect from this method, * this is taken care of in {@link next()}. * * @param array $data Request data * @param Form $form * @return boolean Validation success */ public function validateStep($data, $form) { return true; } /** * Returns the first value of $next_step * * @return string Classname of a {@link MultiFormStep} subclass */ public function getNextStep() { $nextSteps = static::$next_steps; // Check if next_steps have been implemented properly if not the final step if(!$this->isFinalStep()) { if(!isset($nextSteps)) user_error('MultiFormStep->getNextStep(): Please define at least one $next_steps on ' . $this->class, E_USER_ERROR); } if(is_string($nextSteps)) { return $nextSteps; } elseif(is_array($nextSteps) && count($nextSteps)) { // custom flow control goes here return $nextSteps[0]; } else { return false; } } /** * Returns the next step to the current step in the database. * * This will only return something if you've previously visited * the step ahead of the current step, and then gone back a step. * * @return MultiFormStep|boolean */ public function getNextStepFromDatabase() { if($this->SessionID && is_numeric($this->SessionID)) { $nextSteps = static::$next_steps; if(is_string($nextSteps)) { return DataObject::get_one($nextSteps, "\"SessionID\" = {$this->SessionID}"); } elseif(is_array($nextSteps)) { return DataObject::get_one($nextSteps[0], "\"SessionID\" = {$this->SessionID}"); } else { return false; } } } /** * Accessor method for self::$next_steps * * @return string|array */ public function getNextSteps() { return static::$next_steps; } /** * Returns the previous step, if there is one. * * To determine if there is a previous step, we check the database to see if there's * a previous step for this multi form session ID. * * @return string Classname of a {@link MultiFormStep} subclass */ public function getPreviousStep() { $steps = DataObject::get('MultiFormStep', "\"SessionID\" = {$this->SessionID}", '"LastEdited" DESC'); if($steps) { foreach($steps as $step) { $step->setForm($this->form); if($step->getNextStep()) { if($step->getNextStep() == $this->class) { return $step->class; } } } } } /** * Retrieves the previous step class record from the database. * * This will only return a record if you've previously been on the step. * * @return MultiFormStep subclass */ public function getPreviousStepFromDatabase() { if($prevStepClass = $this->getPreviousStep()) { return DataObject::get_one($prevStepClass, "\"SessionID\" = {$this->SessionID}"); } } /** * Get the text to the use on the button to the previous step. * @return string */ public function getPrevText() { return _t('MultiForm.BACK', 'Back'); } /** * Get the text to use on the button to the next step. * @return string */ public function getNextText() { return _t('MultiForm.NEXT', 'Next'); } /** * Get the text to use on the button to submit the form. * @return string */ public function getSubmitText() { return _t('MultiForm.SUBMIT', 'Submit'); } /** * Sets the form that this step is directly related to. * * @param MultiForm subclass $form */ public function setForm($form) { $this->form = $form; } /** * @return Form */ public function getForm() { return $this->form; } // ##################### Utility #################### /** * Determines whether the user is able to go back using the "action_back" * Determines whether the user is able to go back using the "action_back" * Determines whether the user is able to go back using the "action_back" * form action, based on the boolean value of $can_go_back. * * @return boolean */ public function canGoBack() { return static::$can_go_back; } /** * Determines whether this step is the final step in the multi-step process or not, * based on the variable $is_final_step - which must be defined on at least one step. * * @return boolean */ public function isFinalStep() { return static::$is_final_step; } /** * Determines whether the currently viewed step is the current step set in the session. * This assumes you are checking isCurrentStep() against a data record of a MultiFormStep * subclass, otherwise it doesn't work. An example of this is using a singleton instance - it won't * work because there's no data. * * @return boolean */ public function isCurrentStep() { return ($this->class == $this->Session()->CurrentStep()->class) ? true : false; } /** * Add a CSS-class to the step. If needed, multiple classes can be added by delimiting a string with spaces. * * @param string $class A string containing a classname or several class names delimited by a space. * @return MultiFormStep */ public function addExtraClass($class) { // split at white space $classes = preg_split('/\s+/', $class); foreach($classes as $class) { // add classes one by one $this->extraClasses[$class] = $class; } return $this; } /** * Remove a CSS-class from the step. Multiple classes names can be passed through as a space delimited string. * * @param string $class * @return MultiFormStep */ public function removeExtraClass($class) { // split at white space $classes = preg_split('/\s+/', $class); foreach ($classes as $class) { // unset one by one unset($this->extraClasses[$class]); } return $this; } /** * @return string */ public function getExtraClasses() { return join(' ', array_keys($this->extraClasses)); } }
spekulatius/silverstripe-multiform
code/model/MultiFormStep.php
PHP
bsd-3-clause
11,072
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import uuid import socket import time __appname__ = "pymessage" __author__ = "Marco Sirabella, Owen Davies" __copyright__ = "" __credits__ = "Marco Sirabella, Owen Davies" __license__ = "new BSD 3-Clause" __version__ = "0.0.3" __maintainers__ = "Marco Sirabella, Owen Davies" __email__ = "msirabel@gmail.com, dabmancer@dread.life" __status__ = "Prototype" __module__ = "" address = ('localhost', 5350) lguid = '0' def connect(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(address) sock.send((hex(uuid.getnode()) + '\n').encode() + bytes(False)) # ik this is such BAD CODE print("sent") sock.send(lguid.encode()) print('sent latest guid: {}'.format(lguid)) # contents = "latest guid +5: {}".format(lguid + '5') msg = True fullmsg = '' while msg: msg = sock.recv(16).decode() # low byte count for whatever reason #print('mes rec: {}'.format(msg)) fullmsg += msg print('received message: {}'.format(fullmsg)) sock.close() connect()
mjsir911/pymessage
client.py
Python
bsd-3-clause
1,124
package apachelog import ( "strings" ) // Format supported by the Apache mod_log_config module. // For more information, see: // https://httpd.apache.org/docs/2.4/en/mod/mod_log_config.html#formats type Format int // Supported formats. // // TODO(gilliek): move complex format, such as COOKIE, at the bottom of the list // in order to treat them separately. const ( format_beg Format = iota REMOTE_IP_ADDRESS // %a LOCAL_IP_ADDRESS // %A RESPONSE_SIZE // %B RESPONSE_SIZE_CLF // %b COOKIE // %{Foobar}C ELAPSED_TIME // %D ENV_VAR // %{FOOBAR}e HEADER // %{Foobar}i FILENAME // %f REMOTE_HOST // %h REQUEST_PROTO // %H REMOTE_LOGNAME // %l REQUEST_METHOD // %m PORT // %p PROCESS_ID // %P QUERY_STRING // %q REQUEST_FIRST_LINE // %r STATUS // %s TIME // %t REMOTE_USER // %u URL_PATH // %U CANONICAL_SERVER_NAME // %v SERVER_NAME // %V BYTES_RECEIVED // %I BYTES_SENT // %O ELAPSED_TIME_IN_SEC // %T format_end UNKNOWN // for errors ) var formats = [...]string{ REMOTE_IP_ADDRESS: "%a", LOCAL_IP_ADDRESS: "%A", RESPONSE_SIZE: "%B", RESPONSE_SIZE_CLF: "%b", COOKIE: "%{...}C", ELAPSED_TIME: "%D", ENV_VAR: "%{...}e", HEADER: "%{...}i", FILENAME: "%f", REMOTE_HOST: "%h", REQUEST_PROTO: "%H", REMOTE_LOGNAME: "%l", REQUEST_METHOD: "%m", PORT: "%p", PROCESS_ID: "%P", QUERY_STRING: "%q", REQUEST_FIRST_LINE: "%r", STATUS: "%s", TIME: "%t", REMOTE_USER: "%u", URL_PATH: "%U", CANONICAL_SERVER_NAME: "%v", SERVER_NAME: "%V", BYTES_RECEIVED: "%I", BYTES_SENT: "%O", ELAPSED_TIME_IN_SEC: "%T", UNKNOWN: "UNKNOWN", } func (f Format) String() string { if f > format_beg && f < format_end { return formats[f+1] } return formats[UNKNOWN] } var formatsMapping map[string]Format func init() { formatsMapping = make(map[string]Format) for i := format_beg + 1; i < format_end; i++ { formatsMapping[formats[i]] = i } } // LookupFormat retrieves the format corresponding to the given format string. func LookupFormat(format string) Format { if strings.HasPrefix(format, "%{") { if idx := strings.Index(format, "}"); idx != -1 { format = "%{..." + format[idx:] } } if f, found := formatsMapping[format]; found { return f } return UNKNOWN }
e-XpertSolutions/go-apachelog
apachelog/format.go
GO
bsd-3-clause
2,909
/* * Module name : lcd.c: write to LCD display * Author : TI-Avans, JW * Revision History : 20110228: - initial release; * Description : This module contains functions for writing to lcd-display * Test configuration: MCU : ATmega128 Dev.Board : BIGAVR6 Oscillator : External Clock 8.0000 MHz Ext. Modules : - SW: AVR-GCC * NOTES : - */ #include "lcd_2.h" #include <avr/io.h> // lcd_command: schrijf command byte (RS=0) // eerst hoge nibble, dan de lage // void lcd_command ( unsigned char command ) { PORTC = command & 0xF0; // hoge nibble PORTC = PORTC | 0x08; // start (EN=1) _delay_ms(1); // wait 1 ms PORTC = 0x00; // stop _delay_ms(5); // wait 5 ms PORTC = (command & 0x0F) << 4; // lage nibble, shift lage naar hoge bits PORTC = PORTC | 0x08; // start (EN =1) _delay_ms(1); // wait 1 ms PORTC = 0x00; // stop (EN=0 RS=0) _delay_ms(5); // wait 5 ms } // Schrijf data byte (RS=1) // eerst hoge nibble, dan de lage // void lcd_writeChar( unsigned char dat ) { PORTC = dat & 0xF0; // hoge nibble PORTC = PORTC | 0x0C; // data (RS=1), start (EN =1) _delay_ms(1); // wait 1 ms PORTC = 0x04; // stop _delay_ms(5); // wait 5 ms PORTC = (dat & 0x0F) << 4; // lage nibble PORTC = PORTC | 0x0C; // data (RS=1), start (EN =1) _delay_ms(1); // pulse 1 ms PORTC = 0x00; // stop (EN=0 RS=0) _delay_ms(5); // wait 5 ms } // Initialisatie ldr // void lcd_init( void ) { DDRC=0xFC; // PORT C is output to LCD display lcd_command( 0x01 ); // clear display lcd_command( 0x02 ); // return home lcd_command( 0x28 ); // mode: 4 bits interface data, 2 lines,5x8 dots lcd_command( 0x0C ); // display: on, cursor off, blinking off lcd_command( 0x06 ); // entry mode: cursor to right, no shift lcd_command( 0x80 ); // RAM adress: 0, first position, line 1 _delay_ms(20); } // // write first line void lcd_writeLine1 ( char text1[] ) { lcd_command(0x01); // clear display lcd_command(0x80); // first pos line 1, adres $00 for ( int i=0; i<strlen(text1); i++ ) { lcd_writeChar( text1[i] ); } } // write first line void lcd_wrLine1AtPos ( char text1[], unsigned char pos) { lcd_command(0x80+pos); // first pos line 1, adres pos for ( int i=0; i<strlen(text1); i++ ) { lcd_writeChar( text1[i] ); } } // // write second line void lcd_writeLine2 ( char text2[] ) { lcd_command(0xC0); // first pos line 2, adres $40 for ( int i=0; i<strlen(text2); i++ ) { lcd_writeChar( text2[i] ); } } // write first line void lcd_wrLine2AtPos ( char text2[], unsigned char pos) { lcd_command(0xC0+pos); // first pos line 2, adres $40+pos for ( int i=0; i<strlen(text2); i++ ) { lcd_writeChar( text2[i] ); } } // shift text over 'displacement' positions // to the right (displacement>0) or to the left (displacement<0) void lcd_shift( int displacement ) { int number=displacement<0?-displacement:displacement; for (int i=0; i<number; i++) { if (displacement <0) lcd_command(0x18); else lcd_command(0x1C); } }
man1utdfan/AVRProgramming
lcd_2.c
C
bsd-3-clause
3,250
from diesel import Loop, fork, Application, sleep def sleep_and_print(num): sleep(1) print num sleep(1) a.halt() def forker(): for x in xrange(5): fork(sleep_and_print, x) a = Application() a.add_loop(Loop(forker)) a.run()
dieseldev/diesel
examples/forker.py
Python
bsd-3-clause
255
# -*- coding: utf-8 -*- """ zine.forms ~~~~~~~~~~ The form classes the zine core uses. :copyright: (c) 2010 by the Zine Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from copy import copy from datetime import datetime from zine.i18n import _, lazy_gettext, list_languages from zine.application import get_application, get_request, emit_event from zine.config import DEFAULT_VARS from zine.database import db, posts from zine.models import User, Group, Comment, Post, Category, Tag, \ NotificationSubscription, STATUS_DRAFT, STATUS_PUBLISHED, \ STATUS_PROTECTED, STATUS_PRIVATE, \ COMMENT_UNMODERATED, COMMENT_MODERATED, \ COMMENT_BLOCKED_USER, COMMENT_BLOCKED_SPAM, COMMENT_DELETED from zine.parsers import render_preview from zine.privileges import bind_privileges from zine.notifications import send_notification_template, NEW_COMMENT, \ COMMENT_REQUIRES_MODERATION from zine.utils import forms, log, dump_json from zine.utils.http import redirect_to from zine.utils.validators import ValidationError, is_valid_email, \ is_valid_url, is_valid_slug, is_not_whitespace_only from zine.utils.redirects import register_redirect, change_url_prefix def config_field(cfgvar, label=None, **kwargs): """Helper function for fetching fields from the config.""" if isinstance(cfgvar, forms.Field): field = copy(cfgvar) else: field = copy(DEFAULT_VARS[cfgvar]) field._position_hint = forms._next_position_hint() if label is not None: field.label = label for name, value in kwargs.iteritems(): setattr(field, name, value) return field class LoginForm(forms.Form): """The form for the login page.""" user = forms.ModelField(User, 'username', required=True, messages=dict( not_found=lazy_gettext(u'User “%(value)s” does not exist.'), required=lazy_gettext(u'You have to enter a username.') ), on_not_found=lambda user: log.warning(_(u'Failed login attempt, user “%s” does not exist') % user, 'auth') ) password = forms.TextField(widget=forms.PasswordInput) permanent = forms.BooleanField() def context_validate(self, data): if not data['user'].check_password(data['password']): log.warning(_(u'Failed login attempt from “%s”, invalid password') % data['user'].username, 'auth') raise ValidationError(_('Incorrect password.')) class ChangePasswordForm(forms.Form): """The form used on the password-change dialog in the admin panel.""" old_password = forms.TextField(lazy_gettext(u'Old password'), required=True, widget=forms.PasswordInput) new_password = forms.TextField(lazy_gettext(u'New password'), required=True, widget=forms.PasswordInput) check_password = forms.TextField(lazy_gettext(u'Repeat password'), required=True, widget=forms.PasswordInput) def __init__(self, user, initial=None): forms.Form.__init__(self, initial) self.user = user def validate_old_password(self, value): if not self.user.check_password(value): raise ValidationError(_('The old password you\'ve ' 'entered is wrong.')) def context_validate(self, data): if data['new_password'] != data['check_password']: raise ValidationError(_('The two passwords don\'t match.')) class NewCommentForm(forms.Form): """New comment form for authors.""" # implementation detail: the maximum length of the column in the # database is longer than that. However we don't want users to # insert too long names there. The long column is reserved for # pingbacks and such. author = forms.TextField(lazy_gettext(u'Name*'), required=True, max_length=100, messages=dict( too_long=lazy_gettext(u'Your name is too long.'), required=lazy_gettext(u'You have to enter your name.') )) email = forms.TextField(lazy_gettext(u'Mail* (not published)'), required=True, validators=[is_valid_email()], messages=dict( required=lazy_gettext(u'You have to enter a valid e-mail address.') )) www = forms.TextField(lazy_gettext(u'Website'), validators=[is_valid_url( message=lazy_gettext(u'You have to enter a valid URL or omit the field.') )]) body = forms.TextField(lazy_gettext(u'Text'), min_length=2, max_length=6000, required=True, messages=dict( too_short=lazy_gettext(u'Your comment is too short.'), too_long=lazy_gettext(u'Your comment is too long.'), required=lazy_gettext(u'You have to enter a comment.') ), widget=forms.Textarea) parent = forms.HiddenModelField(Comment) def __init__(self, post, user, initial=None): forms.Form.__init__(self, initial) self.req = get_request() self.post = post self.user = user # if the user is logged in the form is a bit smaller if user.is_somebody: del self.fields['author'], self.fields['email'], self.fields['www'] def as_widget(self): widget = forms.Form.as_widget(self) widget.small_form = self.user.is_somebody return widget def validate_parent(self, value): if value.post != self.post: #_ this message is only displayed if the user tempered with #_ the form data raise ValidationError(_('Invalid object referenced.')) def context_validate(self, data): if not self.post.comments_enabled: raise ValidationError(_('Post is closed for commenting.')) if self.post.comments_closed: raise ValidationError(_('Commenting is no longer possible.')) def make_comment(self): """A handy helper to create a comment from the validated form.""" ip = self.req and self.req.remote_addr or '0.0.0.0' if self.user.is_somebody: author = self.user email = www = None else: author = self['author'] email = self['email'] www = self['www'] return Comment(self.post, author, self['body'], email, www, self['parent'], submitter_ip=ip) def create_if_valid(self, req): """The one-trick pony for commenting. Passed a req it tries to use the req data to submit a comment to the post. If the req is not a post req or the form is invalid the return value is None, otherwise a redirect response to the new comment. """ if req.method != 'POST' or not self.validate(req.form): return # if we don't have errors let's save it and emit an # `before-comment-saved` event so that plugins can do # block comments so that administrators have to approve it comment = self.make_comment() #! use this event to block comments before they are saved. This #! is useful for antispam and other ways of moderation. emit_event('before-comment-saved', req, comment) # Moderate Comment? Now that the spam check any everything # went through the processing we explicitly set it to # unmodereated if the blog configuration demands that if not comment.blocked and comment.requires_moderation: comment.status = COMMENT_UNMODERATED comment.blocked_msg = _(u'Comment waiting for approval') #! this is sent directly after the comment was saved. Useful if #! you want to send mail notifications or whatever. emit_event('after-comment-saved', req, comment) # Commit so that make_visible_for_request can access the comment id. db.commit() # send out a notification if the comment is not spam. Nobody is # interested in notifications on spam... if not comment.is_spam: if comment.blocked: notification_type = COMMENT_REQUIRES_MODERATION else: notification_type = NEW_COMMENT send_notification_template(notification_type, 'notifications/on_new_comment.zeml', user=req.user, comment=comment) # Still allow the user to see his comment if it's blocked if comment.blocked: comment.make_visible_for_request(req) return redirect_to(self.post) class PluginForm(forms.Form): """The form for plugin activation and deactivation.""" active_plugins = forms.MultiChoiceField(widget=forms.CheckboxGroup) disable_guard = forms.BooleanField(lazy_gettext(u'Disable plugin guard'), help_text=lazy_gettext(u'If the plugin guard is disabled errors ' u'on plugin setup are not caught.')) def __init__(self, initial=None): self.app = app = get_application() self.active_plugins.choices = sorted([(x.name, x.display_name) for x in app.plugins.values()], key=lambda x: x[1].lower()) if initial is None: initial = dict( active_plugins=[x.name for x in app.plugins.itervalues() if x.active] ) forms.Form.__init__(self, initial) def apply(self): """Apply the changes.""" t = self.app.cfg.edit() t['plugins'] = u', '.join(sorted(self.data['active_plugins'])) t.commit() class RemovePluginForm(forms.Form): """Dummy form for plugin removing.""" def __init__(self, plugin): forms.Form.__init__(self) self.plugin = plugin class PostForm(forms.Form): """This is the baseclass for all forms that deal with posts. There are two builtin subclasses for the builtin content types 'entry' and 'page'. """ title = forms.TextField(lazy_gettext(u'Title'), max_length=150, validators=[is_not_whitespace_only()], required=False) text = forms.TextField(lazy_gettext(u'Text'), max_length=65000, widget=forms.Textarea) status = forms.ChoiceField(lazy_gettext(u'Publication status'), choices=[ (STATUS_DRAFT, lazy_gettext(u'Draft')), (STATUS_PUBLISHED, lazy_gettext(u'Published')), (STATUS_PROTECTED, lazy_gettext(u'Protected')), (STATUS_PRIVATE, lazy_gettext(u'Private'))]) pub_date = forms.DateTimeField(lazy_gettext(u'Publication date'), help_text=lazy_gettext(u'Clear this field to update to current time')) slug = forms.TextField(lazy_gettext(u'Slug'), validators=[is_valid_slug()], help_text=lazy_gettext(u'Clear this field to autogenerate a new slug')) author = forms.ModelField(User, 'username', lazy_gettext('Author'), widget=forms.SelectBox) tags = forms.CommaSeparated(forms.TextField(), lazy_gettext(u'Tags')) categories = forms.Multiple(forms.ModelField(Category, 'id'), lazy_gettext(u'Categories'), widget=forms.CheckboxGroup) parser = forms.ChoiceField(lazy_gettext(u'Parser')) comments_enabled = forms.BooleanField(lazy_gettext(u'Enable comments')) pings_enabled = forms.BooleanField(lazy_gettext(u'Enable pingbacks')) ping_links = forms.BooleanField(lazy_gettext(u'Ping links')) #: the content type for this field. content_type = None def __init__(self, post=None, initial=None): self.app = get_application() self.post = post self.preview = False if post is not None: initial = forms.fill_dict(initial, title=post.title, text=post.text, status=post.status, pub_date=post.pub_date, slug=post.slug, author=post.author, tags=[x.name for x in post.tags], categories=[x.id for x in post.categories], parser=post.parser, comments_enabled=post.comments_enabled, pings_enabled=post.pings_enabled, ping_links=not post.parser_missing ) else: initial = forms.fill_dict(initial, status=STATUS_DRAFT) # if we have a request, we can use the current user as a default req = get_request() if req and req.user: initial['author'] = req.user initial.setdefault('parser', self.app.cfg['default_parser']) self.author.choices = [x.username for x in User.query.all()] self.parser.choices = self.app.list_parsers() self.parser_missing = post and post.parser_missing if self.parser_missing: self.parser.choices.append((post.parser, _('%s (missing)') % post.parser.title())) self.categories.choices = [(c.id, c.name) for c in Category.query.all()] forms.Form.__init__(self, initial) # if we have have an old post and the parser is not missing and # it was published when the form was created we collect the old # posts so that we don't have to ping them another time. self._old_links = set() if self.post is not None and not self.post.parser_missing and \ self.post.is_published: self._old_links.update(self.post.find_urls()) def validate(self, data): """We only validate if we're not in preview mode.""" self.preview = 'preview' in data return forms.Form.validate(self, data) and not self.preview def find_new_links(self): """Return a list of all new links.""" for link in self.post.find_urls(): if not link in self._old_links: yield link def validate_slug(self, value): """Make sure the slug is unique.""" query = Post.query.filter_by(slug=value) if self.post is not None: query = query.filter(Post.id != self.post.id) existing = query.first() if existing is not None: raise ValidationError(_('This slug is already in use.')) def validate_parser(self, value): """Make sure the missing parser is not selected.""" if self.parser_missing and value == self.post.parser: raise ValidationError(_('Selected parser is no longer ' 'available on the system.')) def render_preview(self): """Renders the preview for the post.""" return render_preview(self.data['text'], self.data['parser']) def as_widget(self): widget = forms.Form.as_widget(self) widget.new = self.post is None widget.post = self.post widget.preview = self.preview widget.render_preview = self.render_preview widget.parser_missing = self.parser_missing return widget def make_post(self): """A helper function that creates a post object from the data.""" data = self.data post = Post(data['title'], data['author'], data['text'], data['slug'], parser=data['parser'], content_type=self.content_type, pub_date=data['pub_date']) post.bind_categories(data['categories']) post.bind_tags(data['tags']) self._set_common_attributes(post) self.post = post return post def save_changes(self): """Save the changes back to the database. This also adds a redirect if the slug changes. """ if not self.data['pub_date']: # If user deleted publication timestamp, make a new one. self.data['pub_date'] = datetime.utcnow() old_slug = self.post.slug old_parser = self.post.parser forms.set_fields(self.post, self.data, 'title', 'author', 'parser') if (self.data['text'] != self.post.text or self.data['parser'] != old_parser): self.post.text = self.data['text'] add_redirect = self.post.is_published and old_slug != self.post.slug self.post.touch_times(self.data['pub_date']) self.post.bind_slug(self.data['slug']) self._set_common_attributes(self.post) if add_redirect: register_redirect(old_slug, self.post.slug) def _set_common_attributes(self, post): forms.set_fields(post, self.data, 'comments_enabled', 'pings_enabled', 'status') post.bind_categories(self.data['categories']) post.bind_tags(self.data['tags']) def taglist(self): """Return all available tags as a JSON-encoded list.""" tags = [t.name for t in Tag.query.all()] return dump_json(tags) class EntryForm(PostForm): content_type = 'entry' def __init__(self, post=None, initial=None): app = get_application() PostForm.__init__(self, post, forms.fill_dict(initial, comments_enabled=app.cfg['comments_enabled'], pings_enabled=app.cfg['pings_enabled'], ping_links=True )) class PageForm(PostForm): content_type = 'page' class PostDeleteForm(forms.Form): """Baseclass for deletion forms of posts.""" def __init__(self, post=None, initial=None): self.app = get_application() self.post = post forms.Form.__init__(self, initial) def as_widget(self): widget = forms.Form.as_widget(self) widget.post = self.post return widget def delete_post(self): """Deletes the post from the db.""" emit_event('before-post-deleted', self.post) db.delete(self.post) class _CommentBoundForm(forms.Form): """Internal baseclass for comment bound forms.""" def __init__(self, comment, initial=None): self.app = get_application() self.comment = comment forms.Form.__init__(self, initial) def as_widget(self): widget = forms.Form.as_widget(self) widget.comment = self.comment return widget class EditCommentForm(_CommentBoundForm): """Form for comment editing in admin.""" author = forms.TextField(lazy_gettext(u'Author'), required=True) email = forms.TextField(lazy_gettext(u'Email'), validators=[is_valid_email()]) www = forms.TextField(lazy_gettext(u'Website'), validators=[is_valid_url()]) text = forms.TextField(lazy_gettext(u'Text'), widget=forms.Textarea) pub_date = forms.DateTimeField(lazy_gettext(u'Date'), required=True) parser = forms.ChoiceField(lazy_gettext(u'Parser'), required=True) blocked = forms.BooleanField(lazy_gettext(u'Block Comment')) blocked_msg = forms.TextField(lazy_gettext(u'Reason')) def __init__(self, comment, initial=None): _CommentBoundForm.__init__(self, comment, forms.fill_dict(initial, author=comment.author, email=comment.email, www=comment.www, text=comment.text, pub_date=comment.pub_date, parser=comment.parser, blocked=comment.blocked, blocked_msg=comment.blocked_msg )) self.parser.choices = self.app.list_parsers() self.parser_missing = comment.parser_missing if self.parser_missing and comment.parser is not None: self.parser.choices.append((comment.parser, _('%s (missing)') % comment.parser.title())) def save_changes(self): """Save the changes back to the database.""" old_parser = self.comment.parser forms.set_fields(self.comment, self.data, 'pub_date', 'parser', 'blocked_msg') if (self.data['text'] != self.comment.text or self.data['parser'] != old_parser): self.comment.text = self.data['text'] # update status if self.data['blocked']: if not self.comment.blocked: self.comment.status = COMMENT_BLOCKED_USER else: self.comment.status = COMMENT_MODERATED # only apply these if the comment is not anonymous if self.comment.anonymous: forms.set_fields(self.comment, self.data, 'author', 'email', 'www') class DeleteCommentForm(_CommentBoundForm): """Helper form that is used to delete comments.""" def delete_comment(self): """Deletes the comment from the db.""" delete_comment(self.comment) class ApproveCommentForm(_CommentBoundForm): """Helper form for comment approvement.""" def approve_comment(self): """Approve the comment.""" #! plugins can use this to react to comment approvals. emit_event('before-comment-approved', self.comment) self.comment.status = COMMENT_MODERATED self.comment.blocked_msg = u'' class BlockCommentForm(_CommentBoundForm): """Form used to block comments.""" message = forms.TextField(lazy_gettext(u'Reason')) def __init__(self, comment, initial=None): self.req = get_request() _CommentBoundForm.__init__(self, comment, initial) def block_comment(self): msg = self.data['message'] if not msg and self.req: msg = _(u'blocked by %s') % self.req.user.display_name self.comment.status = COMMENT_BLOCKED_USER self.comment.bocked_msg = msg class MarkCommentForm(_CommentBoundForm): """Form used to block comments.""" def __init__(self, comment, initial=None): self.req = get_request() _CommentBoundForm.__init__(self, comment, initial) def mark_as_spam(self): emit_event('before-comment-mark-spam', self.comment) self.comment.status = COMMENT_BLOCKED_SPAM self.comment.blocked_msg = _("Comment reported as spam by %s" % get_request().user.display_name) def mark_as_ham(self): emit_event('before-comment-mark-ham', self.comment) emit_event('before-comment-approved', self.comment) self.comment.status = COMMENT_MODERATED self.comment.blocked_msg = u'' class _CategoryBoundForm(forms.Form): """Internal baseclass for category bound forms.""" def __init__(self, category, initial=None): self.app = get_application() self.category = category forms.Form.__init__(self, initial) def as_widget(self): widget = forms.Form.as_widget(self) widget.category = self.category widget.new = self.category is None return widget class EditCategoryForm(_CategoryBoundForm): """Form that is used to edit or create a category.""" slug = forms.TextField(lazy_gettext(u'Slug'), validators=[is_valid_slug()]) name = forms.TextField(lazy_gettext(u'Name'), max_length=50, required=True, validators=[is_not_whitespace_only()]) description = forms.TextField(lazy_gettext(u'Description'), max_length=5000, widget=forms.Textarea) def __init__(self, category=None, initial=None): if category is not None: initial = forms.fill_dict(initial, slug=category.slug, name=category.name, description=category.description ) _CategoryBoundForm.__init__(self, category, initial) def validate_slug(self, value): """Make sure the slug is unique.""" query = Category.query.filter_by(slug=value) if self.category is not None: query = query.filter(Category.id != self.category.id) existing = query.first() if existing is not None: raise ValidationError(_('This slug is already in use')) def make_category(self): """A helper function that creates a category object from the data.""" category = Category(self.data['name'], self.data['description'], self.data['slug'] or None) self.category = category return category def save_changes(self): """Save the changes back to the database. This also adds a redirect if the slug changes. """ old_slug = self.category.slug forms.set_fields(self.category, self.data, 'name', 'description') if self.data['slug']: self.category.slug = self.data['slug'] elif not self.category.slug: self.category.set_auto_slug() if old_slug != self.category.slug: register_redirect(old_slug, self.category.slug) class DeleteCategoryForm(_CategoryBoundForm): """Used for deleting categories.""" def delete_category(self): """Delete the category from the database.""" #! plugins can use this to react to category deletes. They can't stop #! the deleting of the category but they can delete information in #! their own tables so that the database is consistent afterwards. emit_event('before-category-deleted', self.category) db.delete(self.category) class CommentMassModerateForm(forms.Form): """This form is used for comment mass moderation.""" selected_comments = forms.MultiChoiceField(widget=forms.CheckboxGroup) per_page = forms.ChoiceField(choices=[20, 40, 60, 80, 100], label=lazy_gettext('Comments Per Page:')) def __init__(self, comments, initial=None): self.comments = comments self.selected_comments.choices = [c.id for c in self.comments] forms.Form.__init__(self, initial) def as_widget(self): widget = forms.Form.as_widget(self) widget.comments = self.comments return widget def iter_selection(self): selection = set(self.data['selected_comments']) for comment in self.comments: if comment.id in selection: yield comment def delete_selection(self): for comment in self.iter_selection(): delete_comment(comment) def approve_selection(self, comment=None): if comment: emit_event('before-comment-approved', comment) comment.status = COMMENT_MODERATED comment.blocked_msg = u'' else: for comment in self.iter_selection(): emit_event('before-comment-approved', comment) comment.status = COMMENT_MODERATED comment.blocked_msg = u'' def block_selection(self): for comment in self.iter_selection(): emit_event('before-comment-blocked', comment) comment.status = COMMENT_BLOCKED_USER comment.blocked_msg = _("Comment blocked by %s" % get_request().user.display_name) def mark_selection_as_spam(self): for comment in self.iter_selection(): emit_event('before-comment-mark-spam', comment) comment.status = COMMENT_BLOCKED_SPAM comment.blocked_msg = _("Comment marked as spam by %s" % get_request().user.display_name) def mark_selection_as_ham(self): for comment in self.iter_selection(): emit_event('before-comment-mark-ham', comment) self.approve_selection(comment) class _GroupBoundForm(forms.Form): """Internal baseclass for group bound forms.""" def __init__(self, group, initial=None): forms.Form.__init__(self, initial) self.app = get_application() self.group = group def as_widget(self): widget = forms.Form.as_widget(self) widget.group = self.group widget.new = self.group is None return widget class EditGroupForm(_GroupBoundForm): """Edit or create a group.""" groupname = forms.TextField(lazy_gettext(u'Groupname'), max_length=30, validators=[is_not_whitespace_only()], required=True) privileges = forms.MultiChoiceField(lazy_gettext(u'Privileges'), widget=forms.CheckboxGroup) def __init__(self, group=None, initial=None): if group is not None: initial = forms.fill_dict(initial, groupname=group.name, privileges=[x.name for x in group.privileges] ) _GroupBoundForm.__init__(self, group, initial) self.privileges.choices = self.app.list_privileges() def validate_groupname(self, value): query = Group.query.filter_by(name=value) if self.group is not None: query = query.filter(Group.id != self.group.id) if query.first() is not None: raise ValidationError(_('This groupname is already in use')) def _set_common_attributes(self, group): forms.set_fields(group, self.data) bind_privileges(group.privileges, self.data['privileges']) def make_group(self): """A helper function that creates a new group object.""" group = Group(self.data['groupname']) self._set_common_attributes(group) self.group = group return group def save_changes(self): """Apply the changes.""" self.group.name = self.data['groupname'] self._set_common_attributes(self.group) class DeleteGroupForm(_GroupBoundForm): """Used to delete a group from the admin panel.""" action = forms.ChoiceField(lazy_gettext(u'What should Zine do with users ' u'assigned to this group?'), choices=[ ('delete_membership', lazy_gettext(u'Do nothing, just detach the membership')), ('relocate', lazy_gettext(u'Move the users to another group')) ], widget=forms.RadioButtonGroup) relocate_to = forms.ModelField(Group, 'id', lazy_gettext(u'Relocate users to'), widget=forms.SelectBox) def __init__(self, group, initial=None): self.relocate_to.choices = [('', u'')] + [ (g.id, g.name) for g in Group.query.filter(Group.id != group.id) ] _GroupBoundForm.__init__(self, group, forms.fill_dict(initial, action='delete_membership')) def context_validate(self, data): if data['action'] == 'relocate' and not data['relocate_to']: raise ValidationError(_('You have to select a group that ' 'gets the users assigned.')) def delete_group(self): """Deletes a group.""" if self.data['action'] == 'relocate': new_group = Group.query.filter_by(self.data['reassign_to'].id).first() for user in self.group.users: if not new_group in user.groups: user.groups.append(new_group) db.commit() #! plugins can use this to react to user deletes. They can't stop #! the deleting of the group but they can delete information in #! their own tables so that the database is consistent afterwards. #! Additional to the group object the form data is submitted. emit_event('before-group-deleted', self.group, self.data) db.delete(self.group) class _UserBoundForm(forms.Form): """Internal baseclass for user bound forms.""" def __init__(self, user, initial=None): forms.Form.__init__(self, initial) self.app = get_application() self.user = user def as_widget(self): widget = forms.Form.as_widget(self) widget.user = self.user widget.new = self.user is None return widget class EditUserForm(_UserBoundForm): """Edit or create a user.""" username = forms.TextField(lazy_gettext(u'Username'), max_length=30, validators=[is_not_whitespace_only()], required=True) real_name = forms.TextField(lazy_gettext(u'Realname'), max_length=180) display_name = forms.ChoiceField(lazy_gettext(u'Display name')) description = forms.TextField(lazy_gettext(u'Description'), max_length=5000, widget=forms.Textarea) email = forms.TextField(lazy_gettext(u'Email'), required=True, validators=[is_valid_email()]) www = forms.TextField(lazy_gettext(u'Website'), validators=[is_valid_url()]) password = forms.TextField(lazy_gettext(u'Password'), widget=forms.PasswordInput) privileges = forms.MultiChoiceField(lazy_gettext(u'Privileges'), widget=forms.CheckboxGroup) groups = forms.MultiChoiceField(lazy_gettext(u'Groups'), widget=forms.CheckboxGroup) is_author = forms.BooleanField(lazy_gettext(u'List as author'), help_text=lazy_gettext(u'This user is listed as author')) def __init__(self, user=None, initial=None): if user is not None: initial = forms.fill_dict(initial, username=user.username, real_name=user.real_name, display_name=user._display_name, description=user.description, email=user.email, www=user.www, privileges=[x.name for x in user.own_privileges], groups=[g.name for g in user.groups], is_author=user.is_author ) _UserBoundForm.__init__(self, user, initial) self.display_name.choices = [ (u'$username', user and user.username or _('Username')), (u'$real_name', user and user.real_name or _('Realname')) ] self.privileges.choices = self.app.list_privileges() self.groups.choices = [g.name for g in Group.query.all()] self.password.required = user is None def validate_username(self, value): query = User.query.filter_by(username=value) if self.user is not None: query = query.filter(User.id != self.user.id) if query.first() is not None: raise ValidationError(_('This username is already in use')) def _set_common_attributes(self, user): forms.set_fields(user, self.data, 'www', 'real_name', 'description', 'display_name', 'is_author') bind_privileges(user.own_privileges, self.data['privileges'], user) bound_groups = set(g.name for g in user.groups) choosen_groups = set(self.data['groups']) group_mapping = dict((g.name, g) for g in Group.query.all()) # delete groups for group in (bound_groups - choosen_groups): user.groups.remove(group_mapping[group]) # and add new groups for group in (choosen_groups - bound_groups): user.groups.append(group_mapping[group]) def make_user(self): """A helper function that creates a new user object.""" user = User(self.data['username'], self.data['password'], self.data['email']) self._set_common_attributes(user) self.user = user return user def save_changes(self): """Apply the changes.""" self.user.username = self.data['username'] if self.data['password']: self.user.set_password(self.data['password']) self.user.email = self.data['email'] self._set_common_attributes(self.user) class DeleteUserForm(_UserBoundForm): """Used to delete a user from the admin panel.""" action = forms.ChoiceField(lazy_gettext(u'What should Zine do with posts ' u'written by this user?'), choices=[ ('delete', lazy_gettext(u'Delete them permanently')), ('reassign', lazy_gettext(u'Reassign posts')) ], widget=forms.RadioButtonGroup) reassign_to = forms.ModelField(User, 'id', lazy_gettext(u'Reassign posts to'), widget=forms.SelectBox) def __init__(self, user, initial=None): self.reassign_to.choices = [('', u'')] + [ (u.id, u.username) for u in User.query.filter(User.id != user.id) ] _UserBoundForm.__init__(self, user, forms.fill_dict(initial, action='reassign' )) def context_validate(self, data): if self.user.posts.count() is 0: data['action'] = None if data['action'] == 'reassign' and not data['reassign_to']: raise ValidationError(_('You have to select a user to reassign ' 'the posts to.')) def delete_user(self): """Deletes the user.""" if self.data['action'] == 'reassign': db.execute(posts.update(posts.c.author_id == self.user.id), dict( author_id=self.data['reassign_to'].id )) # find all the comments by this author and make them comments that # are no longer linked to the author. for comment in self.user.comments.all(): comment.unbind_user() #! plugins can use this to react to user deletes. They can't stop #! the deleting of the user but they can delete information in #! their own tables so that the database is consistent afterwards. #! Additional to the user object the form data is submitted. emit_event('before-user-deleted', self.user, self.data) db.delete(self.user) class EditProfileForm(_UserBoundForm): """Edit or create a user's profile.""" username = forms.TextField(lazy_gettext(u'Username'), max_length=30, validators=[is_not_whitespace_only()], required=True) real_name = forms.TextField(lazy_gettext(u'Realname'), max_length=180) display_name = forms.ChoiceField(lazy_gettext(u'Display name')) description = forms.TextField(lazy_gettext(u'Description'), max_length=5000, widget=forms.Textarea) email = forms.TextField(lazy_gettext(u'Email'), required=True, validators=[is_valid_email()]) www = forms.TextField(lazy_gettext(u'Website'), validators=[is_valid_url()]) password = forms.TextField(lazy_gettext(u'Password'), widget=forms.PasswordInput) password_confirm = forms.TextField(lazy_gettext(u'Confirm password'), widget=forms.PasswordInput, help_text=lazy_gettext(u'Confirm password')) def __init__(self, user=None, initial=None): if user is not None: initial = forms.fill_dict(initial, username=user.username, real_name=user.real_name, display_name=user._display_name, description=user.description, email=user.email, www=user.www ) _UserBoundForm.__init__(self, user, initial) self.display_name.choices = [ (u'$username', user and user.username or _('Username')), (u'$real_name', user and user.real_name or _('Realname')) ] def validate_email(self, value): query = User.query.filter_by(email=value) if self.user is not None: query = query.filter(User.id != self.user.id) if query.first() is not None: raise ValidationError(_('This email address is already in use')) def validate_password(self, value): if 'password_confirm' in self.data: password_confirm = self.data['password_confirm'] else: password_confirm = self.request.values.get('password_confirm', '') if ((not value == password_confirm) or (value and not password_confirm) or (password_confirm and not value)): raise ValidationError(_('Passwords do not match')) def save_changes(self): """Apply the changes.""" if self.data['password']: self.user.set_password(self.data['password']) self.user.real_name = self.data['real_name'] self.user.display_name = self.data['display_name'] self.user.description = self.data['description'] self.user.email = self.data['email'] self.user.www = self.data['www'] class DeleteAccountForm(_UserBoundForm): """Used for a user to delete a his own account.""" password = forms.TextField( lazy_gettext(u"Your password is required to delete your account:"), required=True, widget=forms.PasswordInput, messages = dict(required=lazy_gettext(u'Your password is required!')) ) def __init__(self, user, initial=None): _UserBoundForm.__init__(self, user, forms.fill_dict(initial, action='delete' )) def validate_password(self, value): if not self.user.check_password(value): raise ValidationError(_(u'Invalid password')) def delete_user(self): """Deletes the user's account.""" # find all the comments by this author and make them comments that # are no longer linked to the author. for comment in self.user.comments.all(): comment.unbind_user() #! plugins can use this to react to user deletes. They can't stop #! the deleting of the user but they can delete information in #! their own tables so that the database is consistent afterwards. #! Additional to the user object the form data is submitted. emit_event('before-user-deleted', self.user, self.data) db.delete(self.user) class _ConfigForm(forms.Form): """Internal baseclass for forms that operate on config values.""" def __init__(self, initial=None): self.app = get_application() if initial is None: initial = {} for name in self.fields: initial[name] = self.app.cfg[name] forms.Form.__init__(self, initial) def _apply(self, t, skip): for key, value in self.data.iteritems(): if key not in skip: t[key] = value def apply(self): t = self.app.cfg.edit() self._apply(t, set()) t.commit() class LogOptionsForm(_ConfigForm): """A form for the logfiles.""" log_file = config_field('log_file', lazy_gettext(u'Filename')) log_level = config_field('log_level', lazy_gettext(u'Log Level')) class BasicOptionsForm(_ConfigForm): """The form where the basic options are changed.""" blog_title = config_field('blog_title', lazy_gettext(u'Blog title')) blog_tagline = config_field('blog_tagline', lazy_gettext(u'Blog tagline')) blog_email = config_field('blog_email', lazy_gettext(u'Blog email')) language = config_field('language', lazy_gettext(u'Language')) timezone = config_field('timezone', lazy_gettext(u'Timezone')) session_cookie_name = config_field('session_cookie_name', lazy_gettext(u'Cookie Name')) comments_enabled = config_field('comments_enabled', label=lazy_gettext(u'Comments enabled'), help_text=lazy_gettext(u'enable comments per default')) moderate_comments = config_field('moderate_comments', lazy_gettext(u'Comment Moderation'), widget=forms.RadioButtonGroup) comments_open_for = config_field('comments_open_for', label=lazy_gettext(u'Comments Open Period')) pings_enabled = config_field('pings_enabled', lazy_gettext(u'Pingbacks enabled'), help_text=lazy_gettext(u'enable pingbacks per default')) use_flat_comments = config_field('use_flat_comments', lazy_gettext(u'Use flat comments'), help_text=lazy_gettext(u'All comments are posted top-level')) default_parser = config_field('default_parser', lazy_gettext(u'Default parser')) comment_parser = config_field('comment_parser', lazy_gettext(u'Comment parser')) posts_per_page = config_field('posts_per_page', lazy_gettext(u'Posts per page')) def __init__(self, initial=None): _ConfigForm.__init__(self, initial) self.language.choices = list_languages() self.default_parser.choices = self.comment_parser.choices = \ self.app.list_parsers() class URLOptionsForm(_ConfigForm): """The form for url changes. This form sends database queries, even though seems to only operate on the config. Make sure to commit. """ blog_url_prefix = config_field('blog_url_prefix', lazy_gettext(u'Blog URL prefix')) admin_url_prefix = config_field('admin_url_prefix', lazy_gettext(u'Admin URL prefix')) category_url_prefix = config_field('category_url_prefix', lazy_gettext(u'Category URL prefix')) tags_url_prefix = config_field('tags_url_prefix', lazy_gettext(u'Tag URL prefix')) profiles_url_prefix = config_field('profiles_url_prefix', lazy_gettext(u'Author Profiles URL prefix')) post_url_format = config_field('post_url_format', lazy_gettext(u'Post permalink URL format')) ascii_slugs = config_field('ascii_slugs', lazy_gettext(u'Limit slugs to ASCII')) fixed_url_date_digits = config_field('fixed_url_date_digits', lazy_gettext(u'Use zero-padded dates')) force_https = config_field('force_https', lazy_gettext(u'Force HTTPS')) def _apply(self, t, skip): for key, value in self.data.iteritems(): if key not in skip: old = t[key] if old != value: if key == 'blog_url_prefix': change_url_prefix(old, value) t[key] = value # update the blog_url based on the force_https flag. blog_url = (t['force_https'] and 'https' or 'http') + \ ':' + t['blog_url'].split(':', 1)[1] if blog_url != t['blog_url']: t['blog_url'] = blog_url class ThemeOptionsForm(_ConfigForm): """ The form for theme changes. This is mainly just a dummy, to get csrf protection working. """ class CacheOptionsForm(_ConfigForm): cache_system = config_field('cache_system', lazy_gettext(u'Cache system')) cache_timeout = config_field('cache_timeout', lazy_gettext(u'Default cache timeout')) enable_eager_caching = config_field('enable_eager_caching', lazy_gettext(u'Enable eager caching'), help_text=lazy_gettext(u'Enable')) memcached_servers = config_field('memcached_servers') filesystem_cache_path = config_field('filesystem_cache_path') def context_validate(self, data): if data['cache_system'] == 'memcached': if not data['memcached_servers']: raise ValidationError(_(u'You have to provide at least one ' u'server to use memcached.')) elif data['cache_system'] == 'filesystem': if not data['filesystem_cache_path']: raise ValidationError(_(u'You have to provide cache folder to ' u'use filesystem cache.')) class MaintenanceModeForm(forms.Form): """yet a dummy form, but could be extended later.""" class WordPressImportForm(forms.Form): """This form is used in the WordPress importer.""" download_url = forms.TextField(lazy_gettext(u'Dump Download URL'), validators=[is_valid_url()]) class FeedImportForm(forms.Form): """This form is used in the feed importer.""" download_url = forms.TextField(lazy_gettext(u'Feed Download URL'), validators=[is_valid_url()]) class DeleteImportForm(forms.Form): """This form is used to delete a imported file.""" class ExportForm(forms.Form): """This form is used to implement the export dialog.""" def delete_comment(comment): """ Deletes or marks for deletion the specified comment, depending on the comment's position in the comment thread. Comments are not pruned from the database until all their children are. """ if comment.children: # We don't have to check if the children are also marked deleted or not # because if they still exist, it means somewhere down the tree is a # comment that is not deleted. comment.status = COMMENT_DELETED comment.text = u'' comment.user = None comment._author = comment._email = comment._www = None else: parent = comment.parent #! plugins can use this to react to comment deletes. They can't #! stop the deleting of the comment but they can delete information #! in their own tables so that the database is consistent #! afterwards. emit_event('before-comment-deleted', comment) db.delete(comment) while parent is not None and parent.is_deleted: if not parent.children: newparent = parent.parent emit_event('before-comment-deleted', parent) db.delete(parent) parent = newparent else: parent = None # XXX: one could probably optimize this by tracking the amount # of deleted comments comment.post.sync_comment_count() def make_config_form(): """Returns the form for the configuration editor.""" app = get_application() fields = {} values = {} use_default_label = lazy_gettext(u'Use default value') for category in app.cfg.get_detail_list(): items = {} values[category['name']] = category_values = {} for item in category['items']: items[item['name']] = forms.Mapping( value=item['field'], use_default=forms.BooleanField(use_default_label) ) category_values[item['name']] = { 'value': item['value'], 'use_default': False } fields[category['name']] = forms.Mapping(**items) class _ConfigForm(forms.Form): values = forms.Mapping(**fields) cfg = app.cfg def apply(self): t = self.cfg.edit() for category, items in self.data['values'].iteritems(): for key, d in items.iteritems(): if category != 'zine': key = '%s/%s' % (category, key) if d['use_default']: t.revert_to_default(key) else: t[key] = d['value'] t.commit() return _ConfigForm({'values': values}) def make_notification_form(user): """Creates a notification form.""" app = get_application() fields = {} subscriptions = {} systems = [(s.key, s.name) for s in sorted(app.notification_manager.systems.values(), key=lambda x: x.name.lower())] for obj in app.notification_manager.types(user): fields[obj.name] = forms.MultiChoiceField(choices=systems, label=obj.description, widget=forms.CheckboxGroup) for ns in user.notification_subscriptions: subscriptions.setdefault(ns.notification_id, []) \ .append(ns.notification_system) class _NotificationForm(forms.Form): subscriptions = forms.Mapping(**fields) system_choices = systems def apply(self): user_subscriptions = {} for subscription in user.notification_subscriptions: user_subscriptions.setdefault(subscription.notification_id, set()).add(subscription.notification_system) for key, active in self['subscriptions'].iteritems(): currently_set = user_subscriptions.get(key, set()) active = set(active) # remove outdated for system in currently_set.difference(active): for subscription in user.notification_subscriptions \ .filter_by(notification_id=key, notification_system=system): db.session.delete(subscription) # add new for system in active.difference(currently_set): user.notification_subscriptions.append( NotificationSubscription(user=user, notification_id=key, notification_system=system)) return _NotificationForm({'subscriptions': subscriptions}) def make_import_form(blog): user_choices = [('__zine_create_user', _(u'Create new user'))] + [ (user.id, user.username) for user in User.query.order_by('username').all() ] _authors = dict((author.id, forms.ChoiceField(author.username, choices=user_choices)) for author in blog.authors) _posts = dict((post.id, forms.BooleanField(help_text=post.title)) for post in blog.posts) _comments = dict((post.id, forms.BooleanField()) for post in blog.posts) class _ImportForm(forms.Form): title = forms.BooleanField(lazy_gettext(u'Blog title'), help_text=blog.title) description = forms.BooleanField(lazy_gettext(u'Blog description'), help_text=blog.description) authors = forms.Mapping(_authors) posts = forms.Mapping(_posts) comments = forms.Mapping(_comments) load_config = forms.BooleanField(lazy_gettext(u'Load config values'), help_text=lazy_gettext( u'Load the configuration values ' u'from the import.')) def perform_import(self): from zine.importers import perform_import return perform_import(get_application(), blog, self.data, stream=True) _all_true = dict((x.id, True) for x in blog.posts) return _ImportForm({'posts': _all_true.copy(), 'comments': _all_true.copy()})
mitsuhiko/zine
zine/forms.py
Python
bsd-3-clause
55,129
/* * altivec_typeconversion.h * DevIL * * Created by Meloni Dario on 24/04/05. * */ #include "altivec_common.h" #ifdef ALTIVEC_GCC // data and newdata may be the same buffer // Used to convert RGB <-> BGR in various data types void abc2cba_byte(ILubyte* data, ILuint length, ILubyte* newdata); void abc2cba_short(ILushort* data, ILuint length, ILushort* newdata); void abc2cba_int(ILuint* data, ILuint length, ILuint* newdata); #define abc2cba_float(x, y, z) abc2cba_int(((ILuint*)(x)), y, ((ILuint*)(z))) void abc2cba_double(ILdouble* data, ILuint length, ILdouble* newdata); // Used to convert RGBA <-> BGRA in various data types void abcd2cbad_byte(ILubyte* data, ILuint length, ILubyte* newdata); void abcd2cbad_short(ILushort* data, ILuint length, ILushort* newdata); void abcd2cbad_int(ILuint* data, ILuint length, ILuint* newdata); #define abcd2cbad_float(x, y, z) abcd2cbad_int(((ILuint*)(x)), y, ((ILuint*)(z))) void abcd2cbad_double(ILdouble* data, ILuint length, ILdouble* newdata); #endif
dava/dava.engine
Programs/ColladaConverter/devil-1.7.8/src-IL/include/altivec_typeconversion.h
C
bsd-3-clause
1,015
#pragma once #include "Classes/Modules/PackageModule/Private/PackageWidget.h" #include <TArc/DataProcessing/TArcDataNode.h> class PackageNode; class QAction; class PackageData : public DAVA::TArcDataNode { public: private: friend class PackageModule; QAction* importPackageAction = nullptr; QAction* copyAction = nullptr; QAction* pasteAction = nullptr; QAction* cutAction = nullptr; QAction* deleteAction = nullptr; QAction* duplicateAction = nullptr; QAction* moveUpAction = nullptr; QAction* moveDownAction = nullptr; QAction* moveLeftAction = nullptr; QAction* moveRightAction = nullptr; QAction* jumpToPrototypeAction = nullptr; QAction* findPrototypeInstancesAction = nullptr; PackageWidget* packageWidget = nullptr; DAVA::Map<PackageNode*, PackageContext> packageWidgetContexts; DAVA_VIRTUAL_REFLECTION(PackageData, DAVA::TArcDataNode); };
dava/dava.engine
Programs/QuickEd/Classes/Modules/PackageModule/PackageData.h
C
bsd-3-clause
922
package scala.meta.internal.scalacp import java.util.{HashMap, HashSet} import scala.annotation.tailrec import scala.meta.internal.classpath.MissingSymbolException import scala.meta.internal.{semanticdb => s} import scala.meta.internal.semanticdb.Scala._ import scala.meta.internal.semanticdb.Scala.{Descriptor => d} import scala.meta.internal.semanticdb.Scala.{Names => n} import scala.meta.internal.semanticdb.SymbolInformation.{Kind => k} import scala.reflect.NameTransformer import scala.tools.scalap.scalax.rules.scalasig._ trait SymbolOps { _: Scalacp => lazy val symbolCache = new HashMap[Symbol, String] implicit class XtensionSymbolSSymbol(sym: Symbol) { def toSemantic: String = { def uncached(sym: Symbol): String = { if (sym.isSemanticdbGlobal) Symbols.Global(sym.owner, sym.descriptor) else freshSymbol() } val ssym = symbolCache.get(sym) if (ssym != null) { ssym } else { val ssym = uncached(sym) symbolCache.put(sym, ssym) ssym } } } implicit class XtensionSymbolSSpec(sym: Symbol) { def isSemanticdbGlobal: Boolean = !isSemanticdbLocal def isSemanticdbLocal: Boolean = { val owner = sym.parent.getOrElse(NoSymbol) def definitelyGlobal = sym.isPackage def definitelyLocal = sym == NoSymbol || (owner.isInstanceOf[MethodSymbol] && !sym.isParam) || ((owner.isAlias || (owner.isType && owner.isDeferred)) && !sym.isParam) || // NOTE: Scalap doesn't expose locals. // sym.isSelfParameter || // sym.isLocalDummy || sym.isRefinementClass || sym.isAnonymousClass || sym.isAnonymousFunction || (sym.isInstanceOf[TypeSymbol] && sym.isExistential) def ownerLocal = sym.parent.map(_.isSemanticdbLocal).getOrElse(false) !definitelyGlobal && (definitelyLocal || ownerLocal) } def owner: String = { if (sym.isRootPackage) Symbols.None else if (sym.isEmptyPackage) Symbols.RootPackage else if (sym.isToplevelPackage) Symbols.RootPackage else { sym.parent match { case Some(NoSymbol) => "" case Some(parent) => parent.ssym case None => sys.error(s"unsupported symbol $sym") } } } def symbolName: String = { if (sym.isRootPackage) n.RootPackage.value else if (sym.isEmptyPackage) n.EmptyPackage.value else if (sym.isConstructor) n.Constructor.value else { @tailrec def loop(value: String): String = { val i = value.lastIndexOf("$$") if (i > 0) loop(value.substring(i + 2)) else NameTransformer.decode(value).stripSuffix(" ") } loop(sym.name) } } def descriptor: Descriptor = { sym match { case sym: SymbolInfoSymbol => sym.kind match { case k.LOCAL | k.OBJECT | k.PACKAGE_OBJECT => d.Term(symbolName) case k.METHOD if sym.isValMethod => d.Term(symbolName) case k.METHOD | k.CONSTRUCTOR | k.MACRO => val overloads = { val peers = sym.parent.get.semanticdbDecls.syms peers.filter { case peer: MethodSymbol => peer.symbolName == sym.symbolName && !peer.isValMethod case _ => false } } val disambiguator = { if (overloads.lengthCompare(1) == 0) "()" else { val index = overloads.indexOf(sym) if (index <= 0) "()" else s"(+${index})" } } d.Method(symbolName, disambiguator) case k.TYPE | k.CLASS | k.TRAIT => d.Type(symbolName) case k.PACKAGE => d.Package(symbolName) case k.PARAMETER => d.Parameter(symbolName) case k.TYPE_PARAMETER => d.TypeParameter(symbolName) case skind => sys.error(s"unsupported kind $skind for symbol $sym") } case sym: ExternalSymbol => symbolIndex.lookup(sym) match { case PackageLookup => d.Package(symbolName) case JavaLookup => d.Type(symbolName) case ScalaLookup if sym.entry.entryType == 9 => d.Type(symbolName) case ScalaLookup if sym.entry.entryType == 10 => d.Term(symbolName) case ScalaLookup => sys.error(s"unsupported symbol $sym") case MissingLookup => throw MissingSymbolException(sym.path) } case NoSymbol => d.None } } def semanticdbDecls: SemanticdbDecls = { val decls = sym.children.filter(decl => decl.isUseful && !decl.isTypeParam) SemanticdbDecls(decls.toList) } } implicit class XtensionSymbolsSSpec(syms: Seq[Symbol]) { def semanticdbDecls: SemanticdbDecls = { SemanticdbDecls(syms.filter(_.isUseful)) } def sscope(linkMode: LinkMode): s.Scope = { linkMode match { case SymlinkChildren => s.Scope(symlinks = syms.map(_.ssym)) case HardlinkChildren => syms.map(registerHardlink) val hardlinks = syms.map { case sym: SymbolInfoSymbol => sym.toSymbolInformation(HardlinkChildren) case sym => sys.error(s"unsupported symbol $sym") } s.Scope(hardlinks = hardlinks) } } } case class SemanticdbDecls(syms: Seq[Symbol]) { def sscope(linkMode: LinkMode): s.Scope = { linkMode match { case SymlinkChildren => val sbuf = List.newBuilder[String] syms.foreach { sym => val ssym = sym.ssym sbuf += ssym if (sym.isUsefulField && sym.isMutable) { val setterSymbolName = s"${ssym.desc.name}_=" val setterSym = Symbols.Global(ssym.owner, d.Method(setterSymbolName, "()")) sbuf += setterSym } } s.Scope(sbuf.result) case HardlinkChildren => val sbuf = List.newBuilder[s.SymbolInformation] syms.foreach { sym => registerHardlink(sym) val sinfo = sym match { case sym: SymbolInfoSymbol => sym.toSymbolInformation(HardlinkChildren) case sym => sys.error(s"unsupported symbol $sym") } sbuf += sinfo if (sym.isUsefulField && sym.isMutable) { Synthetics.setterInfos(sinfo, HardlinkChildren).foreach(sbuf.+=) } } s.Scope(hardlinks = sbuf.result) } } } implicit class XtensionSymbol(sym: Symbol) { def ssym: String = sym.toSemantic def self: Type = sym match { case sym: ClassSymbol => sym.selfType .map { case RefinedType(_, List(_, self)) => self case _ => NoType } .getOrElse(NoType) case _ => NoType } def isRootPackage: Boolean = sym.path == "<root>" def isEmptyPackage: Boolean = sym.path == "<empty>" def isToplevelPackage: Boolean = sym.parent.isEmpty def isModuleClass: Boolean = sym.isInstanceOf[ClassSymbol] && sym.isModule def moduleClass: Symbol = sym match { case sym: SymbolInfoSymbol if sym.isModule => sym.infoType match { case TypeRefType(_, moduleClass, _) => moduleClass case _ => NoSymbol } case _ => NoSymbol } def isClass: Boolean = sym.isInstanceOf[ClassSymbol] && !sym.isModule def isObject: Boolean = sym.isInstanceOf[ObjectSymbol] def isType: Boolean = sym.isInstanceOf[TypeSymbol] def isAlias: Boolean = sym.isInstanceOf[AliasSymbol] def isMacro: Boolean = sym.isMethod && sym.hasFlag(0x00008000) def isConstructor: Boolean = sym.isMethod && (sym.name == "<init>" || sym.name == "$init$") def isPackageObject: Boolean = sym.name == "package" def isTypeParam = sym.isType && sym.isParam def isAnonymousClass = sym.name.contains("$anon") def isAnonymousFunction = sym.name.contains("$anonfun") def isSyntheticConstructor = sym match { case sym: SymbolInfoSymbol => val owner = sym.symbolInfo.owner sym.isConstructor && (owner.isModuleClass || owner.isTrait) case _ => false } def isLocalChild: Boolean = sym.name == "<local child>" def isExtensionMethod: Boolean = sym.name.contains("$extension") def isSyntheticValueClassCompanion: Boolean = { sym match { case sym: SymbolInfoSymbol => if (sym.isModuleClass) { sym.infoType match { case ClassInfoType(_, List(TypeRefType(_, anyRef, _))) => sym.isSynthetic && sym.semanticdbDecls.syms.isEmpty case _ => false } } else if (sym.isModule) { sym.moduleClass.isSyntheticValueClassCompanion } else { false } case _ => false } } def isValMethod: Boolean = { sym match { case sym: SymbolInfoSymbol => sym.kind.isMethod && { (sym.isAccessor && sym.isStable) || (isUsefulField && !sym.isMutable) } case _ => false } } def isScalacField: Boolean = { val isField = sym.isInstanceOf[MethodSymbol] && !sym.isMethod && !sym.isParam val isJavaDefined = sym.isJava isField && !isJavaDefined } def isUselessField: Boolean = { val peers = sym.parent.map(_.children.toList).getOrElse(Nil) val getter = peers.find(m => m.isAccessor && m.name == sym.name.stripSuffix(" ")) sym.isScalacField && getter.nonEmpty } def isUsefulField: Boolean = { sym.isScalacField && !sym.isUselessField } def isSyntheticCaseAccessor: Boolean = { sym.isCaseAccessor && sym.name.contains("$") } def isRefinementClass: Boolean = { sym.name == "<refinement>" } def isUseless: Boolean = { sym == NoSymbol || sym.isAnonymousClass || sym.isSyntheticConstructor || sym.isModuleClass || sym.isLocalChild || sym.isExtensionMethod || sym.isSyntheticValueClassCompanion || sym.isUselessField || sym.isSyntheticCaseAccessor || sym.isRefinementClass } def isUseful: Boolean = !sym.isUseless def isDefaultParameter: Boolean = { sym.hasFlag(0x02000000) && sym.isParam } } private var nextId = 0 private def freshSymbol(): String = { val result = Symbols.Local(nextId.toString) nextId += 1 result } lazy val hardlinks = new HashSet[String] private def registerHardlink(sym: Symbol): Unit = { hardlinks.add(sym.ssym) } }
scalameta/scalameta
semanticdb/metacp/src/main/scala/scala/meta/internal/scalacp/SymbolOps.scala
Scala
bsd-3-clause
10,838
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using OpenMetaverse; using log4net; using Mono.Addins; using Nini.Config; using System.Reflection; using OpenSim.Services.Base; using OpenSim.Services.Interfaces; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Services.Connectors { public class SimulationDataService : ServiceBase, ISimulationDataService { // private static readonly ILog m_log = // LogManager.GetLogger( // MethodBase.GetCurrentMethod().DeclaringType); protected ISimulationDataStore m_database; public SimulationDataService(IConfigSource config) : base(config) { string dllName = String.Empty; string connString = String.Empty; // Try reading the [DatabaseService] section, if it exists IConfig dbConfig = config.Configs["DatabaseService"]; if (dbConfig != null) { dllName = dbConfig.GetString("StorageProvider", String.Empty); connString = dbConfig.GetString("ConnectionString", String.Empty); } // Try reading the [SimulationDataStore] section IConfig simConfig = config.Configs["SimulationDataStore"]; if (simConfig != null) { dllName = simConfig.GetString("StorageProvider", dllName); connString = simConfig.GetString("ConnectionString", connString); } // We tried, but this doesn't exist. We can't proceed if (dllName == String.Empty) throw new Exception("No StorageProvider configured"); m_database = LoadPlugin<ISimulationDataStore>(dllName, new Object[] { connString }); if (m_database == null) throw new Exception("Could not find a storage interface in the given module"); } public void StoreObject(SceneObjectGroup obj, UUID regionUUID) { m_database.StoreObject(obj, regionUUID); } public void RemoveObject(UUID uuid, UUID regionUUID) { m_database.RemoveObject(uuid, regionUUID); } public void StorePrimInventory(UUID primID, ICollection<TaskInventoryItem> items) { m_database.StorePrimInventory(primID, items); } public List<SceneObjectGroup> LoadObjects(UUID regionUUID) { return m_database.LoadObjects(regionUUID); } public void StoreTerrain(double[,] terrain, UUID regionID) { m_database.StoreTerrain(terrain, regionID); } public double[,] LoadTerrain(UUID regionID) { return m_database.LoadTerrain(regionID); } public void StoreLandObject(ILandObject Parcel) { m_database.StoreLandObject(Parcel); } public void RemoveLandObject(UUID globalID) { m_database.RemoveLandObject(globalID); } public List<LandData> LoadLandObjects(UUID regionUUID) { return m_database.LoadLandObjects(regionUUID); } public void StoreRegionSettings(RegionSettings rs) { m_database.StoreRegionSettings(rs); } public RegionSettings LoadRegionSettings(UUID regionUUID) { return m_database.LoadRegionSettings(regionUUID); } public RegionLightShareData LoadRegionWindlightSettings(UUID regionUUID) { return m_database.LoadRegionWindlightSettings(regionUUID); } public void StoreRegionWindlightSettings(RegionLightShareData wl) { m_database.StoreRegionWindlightSettings(wl); } public void RemoveRegionWindlightSettings(UUID regionID) { m_database.RemoveRegionWindlightSettings(regionID); } } }
allquixotic/opensim-autobackup
OpenSim/Services/Connectors/Simulation/SimulationDataService.cs
C#
bsd-3-clause
5,620
from falcor import * def render_graph_BSDFViewer(): g = RenderGraph("BSDFViewerGraph") loadRenderPassLibrary("AccumulatePass.dll") loadRenderPassLibrary("BSDFViewer.dll") BSDFViewer = createPass("BSDFViewer") g.addPass(BSDFViewer, "BSDFViewer") AccumulatePass = createPass("AccumulatePass") g.addPass(AccumulatePass, "AccumulatePass") g.addEdge("BSDFViewer.output", "AccumulatePass.input") g.markOutput("AccumulatePass.output") return g BSDFViewer = render_graph_BSDFViewer() try: m.addGraph(BSDFViewer) except NameError: None
NVIDIAGameWorks/Falcor
Tests/image_tests/renderpasses/graphs/BSDFViewer.py
Python
bsd-3-clause
569
/* * Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the United States Government nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package gov.hhs.fha.nhinc.patientdiscovery._10.entity; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import gov.hhs.fha.nhinc.patientdiscovery._10.gateway.ws.EntityPatientDiscoverySecured; import javax.xml.ws.WebServiceContext; import org.hl7.v3.RespondingGatewayPRPAIN201305UV02RequestType; import org.hl7.v3.RespondingGatewayPRPAIN201306UV02ResponseType; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.jmock.lib.legacy.ClassImposteriser; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author Neil Webb */ @RunWith(JMock.class) public class EntityPatientDiscoverySecuredTest { Mockery context = new JUnit4Mockery() { { setImposteriser(ClassImposteriser.INSTANCE); } }; final EntityPatientDiscoveryImpl mockServiceImpl = context.mock(EntityPatientDiscoveryImpl.class); final WebServiceContext mockWebServiceContext = context.mock(WebServiceContext.class); final RespondingGatewayPRPAIN201305UV02RequestType mockRequest = context .mock(RespondingGatewayPRPAIN201305UV02RequestType.class); @Test public void testRespondingGatewayPRPAIN201305UV02Happy() { try { EntityPatientDiscoverySecured pdSecured = new EntityPatientDiscoverySecured() { @Override protected EntityPatientDiscoveryImpl getEntityPatientDiscoveryImpl() { return mockServiceImpl; } @Override protected WebServiceContext getWebServiceContext() { return mockWebServiceContext; } }; context.checking(new Expectations() { { oneOf(mockServiceImpl).respondingGatewayPRPAIN201305UV02( with(aNonNull(RespondingGatewayPRPAIN201305UV02RequestType.class)), with(aNonNull(WebServiceContext.class))); } }); RespondingGatewayPRPAIN201306UV02ResponseType response = pdSecured .respondingGatewayPRPAIN201305UV02(mockRequest); assertNotNull("RespondingGatewayPRPAIN201306UV02ResponseType was null", response); } catch (Throwable t) { System.out.println("Error running testRespondingGatewayPRPAIN201305UV02Happy: " + t.getMessage()); t.printStackTrace(); fail("Error running testRespondingGatewayPRPAIN201305UV02Happy: " + t.getMessage()); } } @Test public void testRespondingGatewayPRPAIN201305UV02NullServiceImpl() { try { EntityPatientDiscoverySecured pdSecured = new EntityPatientDiscoverySecured() { @Override protected EntityPatientDiscoveryImpl getEntityPatientDiscoveryImpl() { return null; } @Override protected WebServiceContext getWebServiceContext() { return mockWebServiceContext; } }; RespondingGatewayPRPAIN201306UV02ResponseType response = pdSecured .respondingGatewayPRPAIN201305UV02(mockRequest); assertNull("RespondingGatewayPRPAIN201306UV02ResponseType was not null", response); } catch (Throwable t) { System.out.println("Error running testRespondingGatewayPRPAIN201305UV02NullServiceImpl: " + t.getMessage()); t.printStackTrace(); fail("Error running testRespondingGatewayPRPAIN201305UV02NullServiceImpl: " + t.getMessage()); } } }
alameluchidambaram/CONNECT
Product/Production/Gateway/PatientDiscovery_10/src/test/java/gov/hhs/fha/nhinc/patientdiscovery/_10/entity/EntityPatientDiscoverySecuredTest.java
Java
bsd-3-clause
5,464
from django.conf.urls.defaults import * from django_de.apps.authors.models import Author urlpatterns = patterns('django.views.generic.list_detail', (r'^$', 'object_list', dict( queryset = Author.objects.order_by('name', 'slug'), template_object_name = 'author', allow_empty=True, ), ) )
django-de/django-de-v2
django_de/apps/authors/urls.py
Python
bsd-3-clause
348
/* * This file is part of the Soletta Project * * Copyright (C) 2015 Intel Corporation. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <stdbool.h> #include <stdint.h> #include <sys/types.h> #include <sol-macros.h> #include <sol-buffer.h> #ifdef __cplusplus extern "C" { #endif /** * @file * @brief These routines are used for I2C access under Solleta. */ /** * @ingroup IO * * @{ */ struct sol_i2c; struct sol_i2c_pending; enum sol_i2c_speed { SOL_I2C_SPEED_10KBIT = 0, SOL_I2C_SPEED_100KBIT, SOL_I2C_SPEED_400KBIT, SOL_I2C_SPEED_1MBIT, SOL_I2C_SPEED_3MBIT_400KBIT }; /** * Open an I2C bus. * * @param bus The I2C bus number to open * @param speed The speed to open I2C bus @a bus at * @return A new I2C bus handle * * @note This call won't attempt to make any pin muxing operations * underneath. Use sol_i2c_open() for that, also this will not cache this I2C * or try get an previous cached I2C handle. * */ struct sol_i2c *sol_i2c_open_raw(uint8_t bus, enum sol_i2c_speed speed) SOL_ATTR_WARN_UNUSED_RESULT; /** * Open an I2C bus. * * @param bus The I2C bus number to open * @param speed The speed to open I2C bus @a bus at * @return A new I2C bus handle * * @note This call will attempt to make pin muxing operations * underneath, for the given platform that the code is running in. Use * sol_i2c_open_raw() if you want to skip any pin mux operation. * @note The same I2C bus is shared between every user, so only the first one * opening the bus will be able to set the bus speed, if some I2C slave device * need to work in lower speed you need to change it on every other user of * the bus. * */ struct sol_i2c *sol_i2c_open(uint8_t bus, enum sol_i2c_speed speed) SOL_ATTR_WARN_UNUSED_RESULT; /** * Close an I2C bus. * * @param i2c bus The I2C bus handle to close * */ void sol_i2c_close(struct sol_i2c *i2c); /** * Close an I2C bus. * * @param i2c bus The I2C bus handle to close * * @note This call will not remove this I2C handle from cache. * Use sol_i2c_close() for that. */ void sol_i2c_close_raw(struct sol_i2c *i2c); /** * Set a (slave) device address on a I2C bus to deliver commands * to. * * All other I2C functions, after this call, will act on the given * @a slave_address device address. Since other I2C calls might happen * in between your own ones, though, it's highly advisable that you * issue this call before using any of the I2C read/write functions. * * @param i2c bus The I2C bus handle * @param slave_address The slave device address to deliver commands to * * @return @c true on success, @c false otherwise. * */ bool sol_i2c_set_slave_address(struct sol_i2c *i2c, uint8_t slave_address); /** * Get the (slave) device address set on an I2C bus (to deliver I2C * commands) * * @param i2c bus The I2C bus handle * @return The slave device address set on @a bus. @c 0x0 means @a bus * was not set to any device yet */ uint8_t sol_i2c_get_slave_address(struct sol_i2c *i2c); /** * Perform a I2C write quick operation * * This sends a single bit to a device (command designed to turn on * and off simple devices) * * @param i2c The I2C bus handle * @param rw The value to write * @param write_quick_cb The callback to be issued when the operation * finishes. The status parameter should be equal to one in case of * success * @param cb_data Data to be passed to @a write_quick_cb * * @return pending handle if operation was started otherwise a NULL pointer */ struct sol_i2c_pending *sol_i2c_write_quick(struct sol_i2c *i2c, bool rw, void (*write_quick_cb)(void *cb_data, struct sol_i2c *i2c, ssize_t status), const void *cb_data); /** * Perform successive asynchronous I2C byte read operations, with no specified * register * * This makes @a count read byte I2C operations on the device @a bus * is set to operate on, at no specific register. Some devices are so * simple that this interface is enough. For others, it is a shorthand * if you want to read the same register as in the previous I2C * command. * * @param i2c bus The I2C bus handle * @param data The output buffer for the read operation * @param count The bytes count for the read operation * @param read_cb The callback to be called when operation finish, the status * parameter should be equal to count in case of success * @param cb_data The first parameter of callback * * @note Caller should guarantee that data will not be freed until * callback is called. * Also there is no transfer queue, calling this function when there is * another I2C operation running will return false. * * @return pending handle if operation was started otherwise a NULL pointer */ struct sol_i2c_pending *sol_i2c_read(struct sol_i2c *i2c, uint8_t *data, size_t count, void (*read_cb)(void *cb_data, struct sol_i2c *i2c, uint8_t *data, ssize_t status), const void *cb_data); /** * Perform successive asynchronous I2C byte write operations, with no specified * register * * This makes @a count write byte I2C operations on the device @a * bus is set to operate on, at no specific register. Some devices are * so simple that this interface is enough. For others, it is a * shorthand if you want to write the same register as in the previous * I2C command. * * @param i2c bus The I2C bus handle * @param data The output buffer for the write operation * @param count The bytes count for the write operation * @param write_cb The callback to be called when operation finish, the status * parameter should be equal to count in case of success * @param cb_data The first parameter of callback * * @note Caller should guarantee that data will not be freed until * callback is called. * Also there is no transfer queue, calling this function when there is * another I2C operation running will return false. * * @return pending handle if operation was started otherwise a NULL pointer */ struct sol_i2c_pending *sol_i2c_write(struct sol_i2c *i2c, uint8_t *data, size_t count, void (*write_cb)(void *cb_data, struct sol_i2c *i2c, uint8_t *data, ssize_t status), const void *cb_data); /** * Perform a asynchronous I2C read operation on a given device register * * @param i2c bus The I2C bus handle * @param reg The I2C register for the read operation * @param data The output buffer for the read operation * @param count The bytes count for the read operation * @param read_reg_cb The callback to be called when operation finish, * the status parameter should be equal to count in case of success * @param cb_data The first parameter of callback * * @note Caller should guarantee that data will not be freed until * callback is called. * Also there is no transfer queue, calling this function when there is * another I2C operation running will return false. * * @return pending handle if operation was started otherwise a NULL pointer */ struct sol_i2c_pending *sol_i2c_read_register(struct sol_i2c *i2c, uint8_t reg, uint8_t *data, size_t count, void (*read_reg_cb)(void *cb_data, struct sol_i2c *i2c, uint8_t reg, uint8_t *data, ssize_t status), const void *cb_data); /** * Perform a asynchronous I2C write operation on a given device register * * @param i2c bus The I2C bus handle * @param reg The I2C register for the write operation * @param data The output buffer for the write operation * @param count The bytes count for the write operation * @param write_reg_cb The callback to be called when operation finish, * the status parameter should be equal to count in case of success * @param cb_data The first parameter of callback * * @note Caller should guarantee that data will not be freed until * callback is called. * Also there is no transfer queue, calling this function when there is * another I2C operation running will return false. * * @return pending handle if operation was started otherwise a NULL pointer */ struct sol_i2c_pending *sol_i2c_write_register(struct sol_i2c *i2c, uint8_t reg, const uint8_t *data, size_t count, void (*write_reg_cb)(void *cb_data, struct sol_i2c *i2c, uint8_t reg, uint8_t *data, ssize_t status), const void *cb_data); /** * Asynchronous read of an arbitrary number of bytes from a register in * repeated bursts of a given length (that start always on the provided * register address) * * This is so because a lot of devices will, after a read operation, * update its register values with new data to be read on subsequent * operations, until the total data length the user requested is read. * If the device has the auto-increment feature, * sol_i2c_read_register() might be a better call than this function. * * This will issue multiple I2C read/write transactions with the * first (write) message specifying the register to operate on and the * second (read) message specifying the length (always @a len per * read) and the destination of the read operation. * * @param i2c bus The I2C bus handle * @param reg The register to start reading from * @param values Where to store the read bytes * @param count The size of a single read block * @param times How many reads of size @a len to perform (on success, * @a len * @a times bytes will be read) * @param read_reg_multiple_cb The callback to be called when operation finish, * the status parameter should be equal to count in case of success * @param cb_data The first parameter of callback * * @note Caller should guarantee that data will not be freed until * callback is called. * Also there is no transfer queue, calling this function when there is * another I2C operation running will return false. * * @return pending handle if operation was started otherwise a NULL pointer */ struct sol_i2c_pending *sol_i2c_read_register_multiple(struct sol_i2c *i2c, uint8_t reg, uint8_t *values, size_t count, uint8_t times, void (*read_reg_multiple_cb)(void *cb_data, struct sol_i2c *i2c, uint8_t reg, uint8_t *data, ssize_t status), const void *cb_data); /** * Return true if I2C bus is busy, processing another operation. * This function should be called before call any other I2C function. * * @param i2c The I2C bus handle * * @return true is busy or false if idle */ bool sol_i2c_busy(struct sol_i2c *i2c); /** * Get the I2C bus id * * @param i2c The I2C bus handle * * @return the bus id */ uint8_t sol_i2c_bus_get(const struct sol_i2c *i2c); /** * Cancel a pending operation. * * @param i2c the I2C bus handle * @param pending the operation handle */ void sol_i2c_pending_cancel(struct sol_i2c *i2c, struct sol_i2c_pending *pending); #ifdef SOL_PLATFORM_LINUX /** * Create a new i2c device. * * Iterates through @a relative_dir on '/sys/devices/' looking * for 'i2c-X' dir and add @a dev_name @dev_number to its 'new_device' file. * * @param relative_dir bus on '/sys/devices' where to add new i2c device. * @param dev_name name of device. Usually is the one its driver expects. * @param dev_number number of device on bus. * @param result_path resulting path of new device. It's a convenience to * retrieve new device path. Note that the device dir may take some time * to appear on sysfs - it may be necessary to wait some time before trying to * access it. * * @return a positive value if everything was ok. A negative one if some error * happened. Watch out for -EEXIST return: it means that device could not be * created because it already exists. */ int sol_i2c_create_device(const char *address, const char *dev_name, unsigned int dev_number, struct sol_buffer *result_path); #endif /** * @} */ #ifdef __cplusplus } #endif
anselmolsm/soletta
src/lib/io/include/sol-i2c.h
C
bsd-3-clause
13,119
using Lix.Commons.Repositories; using Lix.Commons.Tests.Examples; using Lix.Commons.Tests.Repositories; using MbUnit.Framework; using NHibernate; namespace Lix.NHibernate.Utilities.Tests.Repositories { [TestFixture] public class when_listing_entities_in_an_nhibernate_repository : when_listing_entities_in_a_repository<NHibernateUnitOfWork, NHibernateRepository<Fish>> { public ISessionFactory SessionFactory { get; private set; } private ISession Session { get; set; } [FixtureSetUp] public void ClassSetup() { this.SessionFactory = SessionFactoryFactory.CreateSessionFactory(); } public override void SetUp() { this.Session = this.SessionFactory.OpenSession(); using (var tx = this.Session.BeginTransaction()) { SessionFactoryFactory.BuildSchema(this.Session); tx.Commit(); } base.SetUp(); } public override void TearDown() { this.UnitOfWork.Commit(); this.Session.Close(); this.Session.Dispose(); this.Session = null; base.TearDown(); } protected override void SaveToUnitOfWork(NHibernateUnitOfWork unitOfWork, Fish entity) { unitOfWork.Session.Save(entity); } protected override NHibernateRepository<Fish> CreateRepository() { return new NHibernateRepository<Fish>(this.UnitOfWork); } protected override NHibernateUnitOfWork CreateUnitOfWork() { return new NHibernateUnitOfWork(this.Session); } } }
lukesmith/lix
src/Lix.NHibernate.Utilities.Tests/Repositories/when_listing_entities_in_an_nhibernate_repository.cs
C#
bsd-3-clause
1,778
<?php namespace CL\PsrCache; /** * @author Ivan Kerin <ikerin@gmail.com> * @copyright 2014, Clippings Ltd. * @license http://spdx.org/licenses/BSD-3-Clause */ class NullItem implements CacheItemInterface { private $key; private $value; public function __construct($key) { $this->key = $key; } /** * Returns the key for the current cache item. * * The key is loaded by the Implementing Library, but should be available to * the higher level callers when needed. * * @return string * The key string for this cache item. */ public function getKey() { return $this->key; } /** * Retrieves the value of the item from the cache associated with this objects key. * * The value returned must be identical to the value original stored by set(). * * if isHit() returns false, this method MUST return null. Note that null * is a legitimate cached value, so the isHit() method SHOULD be used to * differentiate between "null value was found" and "no value was found." * * @return mixed * The value corresponding to this cache item's key, or null if not found. */ public function get() { return $this->value; } /** * Sets the value represented by this cache item. * * The $value argument may be any item that can be serialized by PHP, * although the method of serialization is left up to the Implementing * Library. * * Implementing Libraries MAY provide a default TTL if one is not specified. * If no TTL is specified and no default TTL has been set, the TTL MUST * be set to the maximum possible duration of the underlying storage * mechanism, or permanent if possible. * * @param mixed $value * The serializable value to be stored. * @param int|\DateTime $ttl * - If an integer is passed, it is interpreted as the number of seconds * after which the item MUST be considered expired. * - If a DateTime object is passed, it is interpreted as the point in * time after which the item MUST be considered expired. * - If no value is passed, a default value MAY be used. If none is set, * the value should be stored permanently or for as long as the * implementation allows. * @return static * The invoked object. */ public function set($value, $ttl = null) { $this->value = $value; return $this; } /** * Saves a value into the cache. * * @return boolean * Returns true if the item was successfully saved, or false if there was * an error. */ public function save() { return true; } /** * Confirms if the cache item lookup resulted in a cache hit. * * Note: This method MUST NOT have a race condition between calling isHit() * and calling get(). * * @return boolean * True if the request resulted in a cache hit. False otherwise. */ public function isHit() { return false; } /** * Removes the current key from the cache. * * @return boolean * Returns true if the item was deleted or if it did not exist in the * first place, or false if there was an error. */ public function delete() { return true; } /** * Confirms if the cache item exists in the cache. * * Note: This method MAY avoid retrieving the cached value for performance * reasons, which could result in a race condition between exists() and get(). * To avoid that potential race condition use isHit() instead. * * @return boolean * True if item exists in the cache, false otherwise. */ public function exists() { return false; } }
clippings/psr-cache
src/NullItem.php
PHP
bsd-3-clause
3,903
#ifndef SEGMATCH_FEATURES_HPP_ #define SEGMATCH_FEATURES_HPP_ #include <string> #include <vector> #include <Eigen/Core> #include <glog/logging.h> namespace segmatch { typedef double FeatureValueType; struct FeatureValue { FeatureValue() {} FeatureValue(std::string feature_name, FeatureValueType feature_value) : name(feature_name), value(feature_value) {} std::string name = ""; FeatureValueType value = 0.0; }; /// \brief A feature can be composed of any number of values, each with its own name. class Feature { public: Feature() {} ~Feature() {} explicit Feature(const std::string& name) : name_(name) {} size_t size() const { return feature_values_.size(); } bool empty() { return feature_values_.empty(); } const FeatureValue& at(const size_t& index) const { return feature_values_.at(index); } void clear() { feature_values_.clear(); } void push_back(const FeatureValue& value) { LOG_IF(WARNING, findValueByName(value.name, NULL)) << "Adding several FeatureValues of same name to Feature is not recommended."; feature_values_.push_back(value); } bool findValueByName(const std::string& name, FeatureValue* value) const; std::string getName() const {return name_;} private: std::vector<FeatureValue> feature_values_; std::string name_; }; // class Feature /// \brief A collection of features. class Features { public: Features() {} Features& operator+= (const Features& rhs) { this->features_.insert(this->features_.end(), rhs.features_.begin(), rhs.features_.end()); return *this; } void push_back(const Feature& feature) { features_.push_back(feature); } size_t size() const { return features_.size(); } const Feature& at(const size_t& index) const { return features_.at(index); } void clear() { features_.clear(); } void clearByName(const std::string& name); bool empty() { return features_.empty(); } void replaceByName(const Feature& new_feature); size_t sizeWhenFlattened() const; std::vector<FeatureValueType> asVectorOfValues() const; Eigen::MatrixXd asEigenMatrix() const; Features rotationInvariantFeaturesOnly() const; std::vector<std::string> asVectorOfNames() const; private: std::vector<Feature> features_; }; // class Features } // namespace segmatch #endif // SEGMATCH_FEATURES_HPP_
ethz-asl/segmatch
segmatch/include/segmatch/features.hpp
C++
bsd-3-clause
2,318
#include "CResult.hpp" #include "mysql.hpp" #include "CQuery.hpp" bool CQuery::Execute(MYSQL *connection) { CLog::Get()->Log(LogLevel::DEBUG, "CQuery::Execute(this={}, connection={})", static_cast<const void *>(this), static_cast<const void *>(connection)); int error = 0; default_clock::time_point exec_timepoint = default_clock::now(); error = mysql_real_query(connection, m_Query.c_str(), m_Query.length()); default_clock::duration exec_time = default_clock::now() - exec_timepoint; if (error != 0) { const char *error_str = mysql_error(connection); string msg = fmt::format("error #{} while executing query \"{}\": {}", mysql_errno(connection), m_Query, error_str ? error_str : "(nullptr)"); if (!m_DbgInfo.empty()) CLog::Get()->Log(LogLevel::ERROR, m_DbgInfo, msg.c_str()); else CLog::Get()->Log(LogLevel::ERROR, msg.c_str()); return false; } auto query_exec_time_milli = std::chrono::duration_cast<std::chrono::milliseconds>(exec_time).count(), query_exec_time_micro = std::chrono::duration_cast<std::chrono::microseconds>(exec_time).count(); CLog::Get()->Log(LogLevel::INFO, "query \"{}\" successfully executed within {}.{} milliseconds", m_Query, query_exec_time_milli, query_exec_time_micro - (query_exec_time_milli * 1000)); m_Result = CResultSet::Create(connection, exec_time, m_Query); return m_Result != nullptr; }
pBlueG/SA-MP-MySQL
src/CQuery.cpp
C++
bsd-3-clause
1,393
package org.tolweb.treegrowserver.dao; import java.util.Date; import java.util.List; import org.tolweb.treegrow.main.Contributor; import org.tolweb.treegrowserver.PublicationBatch; public interface PublicationBatchDAO { public void saveBatch(PublicationBatch batch); public PublicationBatch getBatchWithId(Long id); public PublicationBatch getBatchForSubmittedNode(Long nodeId); public boolean getContributorCanPublishBatch(Contributor contr, PublicationBatch batch); public List<PublicationBatch> getOpenPublicationBatches(); public Date getLastPublishedDateForPage(Long pageId); public Date getLastPublishedDateForNode(Long nodeId); }
tolweb/tolweb-app
TreeGrowServer/src/org/tolweb/treegrowserver/dao/PublicationBatchDAO.java
Java
bsd-3-clause
668
all: build build: rebar3 compile erlc clients/erlang_client/client.erl run_server: erl -pa _build/default/lib/chat/ebin -eval "application:start(chat)" -noshell start_sasl run_client: erl -pa clients/erlang_client -s client connect -noshell
Limmen/chatserver
Makefile
Makefile
bsd-3-clause
252
<!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.6.0_26) on Sun Jan 22 14:18:59 CET 2012 --> <TITLE> Uses of Class soot.jimple.spark.pag.GlobalVarNode (Soot API) </TITLE> <META NAME="date" CONTENT="2012-01-22"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class soot.jimple.spark.pag.GlobalVarNode (Soot API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= 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=2 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"> <A HREF="../../../../../soot/jimple/spark/pag/GlobalVarNode.html" title="class in soot.jimple.spark.pag"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&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?soot/jimple/spark/pag//class-useGlobalVarNode.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="GlobalVarNode.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 Class<br>soot.jimple.spark.pag.GlobalVarNode</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../soot/jimple/spark/pag/GlobalVarNode.html" title="class in soot.jimple.spark.pag">GlobalVarNode</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#soot.jimple.spark.pag"><B>soot.jimple.spark.pag</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="soot.jimple.spark.pag"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../soot/jimple/spark/pag/GlobalVarNode.html" title="class in soot.jimple.spark.pag">GlobalVarNode</A> in <A HREF="../../../../../soot/jimple/spark/pag/package-summary.html">soot.jimple.spark.pag</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../soot/jimple/spark/pag/package-summary.html">soot.jimple.spark.pag</A> that return <A HREF="../../../../../soot/jimple/spark/pag/GlobalVarNode.html" title="class in soot.jimple.spark.pag">GlobalVarNode</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../soot/jimple/spark/pag/GlobalVarNode.html" title="class in soot.jimple.spark.pag">GlobalVarNode</A></CODE></FONT></TD> <TD><CODE><B>PAG.</B><B><A HREF="../../../../../soot/jimple/spark/pag/PAG.html#findGlobalVarNode(java.lang.Object)">findGlobalVarNode</A></B>(<A HREF="http://java.sun.com/j2se/1.6.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A>&nbsp;value)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Finds the GlobalVarNode for the variable value, or returns null.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../soot/jimple/spark/pag/GlobalVarNode.html" title="class in soot.jimple.spark.pag">GlobalVarNode</A></CODE></FONT></TD> <TD><CODE><B>PAG.</B><B><A HREF="../../../../../soot/jimple/spark/pag/PAG.html#findGlobalVarNode(java.lang.Object)">findGlobalVarNode</A></B>(<A HREF="http://java.sun.com/j2se/1.6.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A>&nbsp;value)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Finds the GlobalVarNode for the variable value, or returns null.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../soot/jimple/spark/pag/GlobalVarNode.html" title="class in soot.jimple.spark.pag">GlobalVarNode</A></CODE></FONT></TD> <TD><CODE><B>PAG.</B><B><A HREF="../../../../../soot/jimple/spark/pag/PAG.html#makeGlobalVarNode(java.lang.Object, soot.Type)">makeGlobalVarNode</A></B>(<A HREF="http://java.sun.com/j2se/1.6.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A>&nbsp;value, <A HREF="../../../../../soot/Type.html" title="class in soot">Type</A>&nbsp;type)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Finds or creates the GlobalVarNode for the variable value, of type type.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../soot/jimple/spark/pag/GlobalVarNode.html" title="class in soot.jimple.spark.pag">GlobalVarNode</A></CODE></FONT></TD> <TD><CODE><B>PAG.</B><B><A HREF="../../../../../soot/jimple/spark/pag/PAG.html#makeGlobalVarNode(java.lang.Object, soot.Type)">makeGlobalVarNode</A></B>(<A HREF="http://java.sun.com/j2se/1.6.0/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</A>&nbsp;value, <A HREF="../../../../../soot/Type.html" title="class in soot">Type</A>&nbsp;type)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Finds or creates the GlobalVarNode for the variable value, of type type.</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=2 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"> <A HREF="../../../../../soot/jimple/spark/pag/GlobalVarNode.html" title="class in soot.jimple.spark.pag"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&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?soot/jimple/spark/pag//class-useGlobalVarNode.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="GlobalVarNode.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> </BODY> </HTML>
Phortran/SicurezzaInformatica
ApkSSL_Tester/libs/soot/doc/soot/jimple/spark/pag/class-use/GlobalVarNode.html
HTML
bsd-3-clause
10,290
/*================================================================================ Copyright (c) 2009 VMware, Inc. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of VMware, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================*/ package com.vmware.vim25; /** @author Steve Jin (sjin@vmware.com) */ public class ClusterProfileConfigInfo extends ProfileConfigInfo { public ComplianceProfile complyProfile; public ComplianceProfile getComplyProfile() { return this.complyProfile; } public void setComplyProfile(ComplianceProfile complyProfile) { this.complyProfile=complyProfile; } }
mikem2005/vijava
src/com/vmware/vim25/ClusterProfileConfigInfo.java
Java
bsd-3-clause
2,021
#!/bin/sh # source the common platform independent functionality and option parsing script_location=$(cd "$(dirname "$0")"; pwd) . ${script_location}/common_test.sh retval=0 # running unit test suite run_unittests --gtest_shuffle \ --gtest_death_test_use_fork || retval=1 cd ${SOURCE_DIRECTORY}/test echo "running CernVM-FS client test cases..." CVMFS_TEST_CLASS_NAME=ClientIntegrationTests \ ./run.sh $CLIENT_TEST_LOGFILE -o ${CLIENT_TEST_LOGFILE}${XUNIT_OUTPUT_SUFFIX} \ -x src/004-davinci \ src/005-asetup \ src/006-buildkernel \ src/007-testjobs \ src/024-reload-during-asetup \ -- \ src/0* \ || retval=1 echo -n "make sure apache is running... " sudo systemctl start httpd > /dev/null && echo "done" || echo "fail" echo "running CernVM-FS server test cases..." CVMFS_TEST_CLASS_NAME=ServerIntegrationTests \ ./run.sh $SERVER_TEST_LOGFILE -o ${SERVER_TEST_LOGFILE}${XUNIT_OUTPUT_SUFFIX} \ -x src/518-hardlinkstresstest \ src/524-corruptmanifestfailover \ src/600-securecvmfs \ -- \ src/5* \ src/6* \ src/7* \ || retval=1 # To do: remove me once previous package is available echo "NOT running CernVM-FS migration test cases (disabled)..." #CVMFS_TEST_CLASS_NAME=MigrationTests \ #./run.sh $MIGRATIONTEST_LOGFILE -o ${MIGRATIONTEST_LOGFILE}${XUNIT_OUTPUT_SUFFIX} \ # migration_tests/* \ # || retval=1 exit $retval
trshaffer/cvmfs
test/cloud_testing/platforms/fedora24_x86_64_test.sh
Shell
bsd-3-clause
2,482
body { padding-top: 60px; padding-bottom: 40px; font-family: sans-serif; } .zf-green { color: #68b604; } .btn-success { background-color: #57a900; background-image: -moz-linear-gradient(top, #70d900, #57a900); background-image: -ms-linear-gradient(top, #70d900, #57a900); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#70d900), to(#57a900)); background-image: -webkit-linear-gradient(top, #70d900, #57a900); background-image: -o-linear-gradient(top, #70d900, #57a900); background-image: linear-gradient(top, #70d900, #57a900); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#70d900', endColorstr='#57a900', GradientType=0); } .btn-success:hover, .btn-success:active, .btn-success.active, .btn-success.disabled, .btn-success[disabled] { background-color: #57a900; } .btn-success:active, .btn-success.active { background-color: #57a900; } div.container a.brand { background: url("../img/zf2-logo.png") no-repeat scroll 0 10px transparent; margin-left: 0; padding: 8px 20px 12px 40px; }
septembersixth/glory-blog
public/css/admin/style.css
CSS
bsd-3-clause
1,070
/* -*- Mode: C; c-basic-offset:4 ; -*- */ /* * Copyright (C) 1997 University of Chicago. * See COPYRIGHT notice in top-level directory. */ #include "adio.h" #include "adio_extern.h" #ifdef ROMIO_INSIDE_MPICH2 #include "mpiimpl.h" #endif void ADIO_End(int *error_code) { ADIOI_Flatlist_node *curr, *next; ADIOI_Datarep *datarep, *datarep_next; /* FPRINTF(stderr, "reached end\n"); */ /* if a default errhandler was set on MPI_FILE_NULL then we need to ensure * that our reference to that errhandler is released */ PMPI_File_set_errhandler(MPI_FILE_NULL, MPI_ERRORS_RETURN); /* delete the flattened datatype list */ curr = ADIOI_Flatlist; while (curr) { if (curr->blocklens) ADIOI_Free(curr->blocklens); if (curr->indices) ADIOI_Free(curr->indices); next = curr->next; ADIOI_Free(curr); curr = next; } ADIOI_Flatlist = NULL; /* free file and info tables used for Fortran interface */ if (ADIOI_Ftable) ADIOI_Free(ADIOI_Ftable); #ifndef HAVE_MPI_INFO if (MPIR_Infotable) ADIOI_Free(MPIR_Infotable); #endif /* free the memory allocated for a new data representation, if any */ datarep = ADIOI_Datarep_head; while (datarep) { datarep_next = datarep->next; #ifdef HAVE_MPIU_FUNCS MPIU_Free(datarep->name); #else ADIOI_Free(datarep->name); #endif ADIOI_Free(datarep); datarep = datarep_next; } if( ADIOI_syshints != MPI_INFO_NULL) MPI_Info_free(&ADIOI_syshints); MPI_Op_free(&ADIO_same_amode); *error_code = MPI_SUCCESS; } /* This is the delete callback function associated with ADIO_Init_keyval when MPI_COMM_SELF is freed */ int ADIOI_End_call(MPI_Comm comm, int keyval, void *attribute_val, void *extra_state) { int error_code; ADIOI_UNREFERENCED_ARG(comm); ADIOI_UNREFERENCED_ARG(attribute_val); ADIOI_UNREFERENCED_ARG(extra_state); MPI_Keyval_free(&keyval); /* The end call will be called after all possible uses of this keyval, even * if a file was opened with MPI_COMM_SELF. Note, this assumes LIFO * MPI_COMM_SELF attribute destruction behavior mandated by MPI-2.2. */ if (ADIOI_cb_config_list_keyval != MPI_KEYVAL_INVALID) MPI_Keyval_free(&ADIOI_cb_config_list_keyval); ADIO_End(&error_code); return error_code; }
gnu3ra/SCC15HPCRepast
INSTALLATION/mpich2-1.4.1p1/src/mpi/romio/adio/common/ad_end.c
C
bsd-3-clause
2,332
module Paths_variants ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName, getSysconfDir ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) import Prelude catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version [0,1,0,0] [] bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath bindir = "/Users/jo/.cabal/bin" libdir = "/Users/jo/.cabal/lib/x86_64-osx-ghc-7.10.2/varia_5wCMPNeYlGhAk0qTYbHvsm" datadir = "/Users/jo/.cabal/share/x86_64-osx-ghc-7.10.2/variants-0.1.0.0" libexecdir = "/Users/jo/.cabal/libexec" sysconfdir = "/Users/jo/.cabal/etc" getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath getBinDir = catchIO (getEnv "variants_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "variants_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "variants_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "variants_libexecdir") (\_ -> return libexecdir) getSysconfDir = catchIO (getEnv "variants_sysconfdir") (\_ -> return sysconfdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
josephDunne/variants
dist/build/autogen/Paths_variants.hs
Haskell
bsd-3-clause
1,313
import * as Redux from "redux" import { composeWithDevTools } from "redux-devtools-extension/developmentOnly" import thunk from "redux-thunk" import reducersRegistry from "./reducers" const configureStore = (initialState) => { const middlewares = [ thunk ] const enhancer = composeWithDevTools( applyMiddleware(...middlewares) ) const reducer = combineReducers(reducersRegistry) const store = Redux.createStore( reducer, initialState, enhancer ) if (module.hot) { module.hot.accept("./reducers", () => { const nextReducer = combineReducers(reducersRegistry) store.replaceReducer(nextReducer) }) } return store } export default store
yogurt1/yogurt1.github.io
src/store/index.js
JavaScript
bsd-3-clause
761
--- layout: default permalink: /development/ published: false --- <div class="development"> {% include menu.html %} <div class="plot"> <p> <strong>Airlift</strong> is constantly being improved. We are always looking for help in the following areas. If you would like to contribute in any way, whether you are an intern, someone working with Google Summer of Code, or are just looking for a cool project to join, please <a href="http://www.lucidtechnics.com/about/">contact us</a>. We could use the help! </p> </div> </div> <div class="ideas"> <div class="idea"> <h1>Dictation Improvements</h1> <div class="description"> <p> Dictation is our English based domain specific language we use to describe a business' application resources. Airlift uses these Dictation based resource descriptions to produce Google App Engine specific code. The code we generate includes, but is not limited to, datastore persistence logic, resource validation and conversion, and application audit and security. </div> <div class="description"> <p> Dictation is not perfect. We will like to improve Dictation's usability. One such way is to provide an editor that automatically detects syntax errors as well as improve Dictation's readability via keyword highlighting. This editor should be cloud based, but also usable offline. It should be easy enough to use that a non-technical person code create a valid Dictation file with ease. </p> <div class="links"> <ul style="list-style: none"> <li>Project Lead <a href="http://github.com/davezen1">David Hodge</a></li> <li>Source Code <a href="https://github.com/LucidTechnics/dictation">Dictation</a></li> </ul> </div> </div> </div> <div class="idea"> <h1>Google App Engine Service Api Enhancements</h1> <div class="description"> <p> Airlift's goal is twofold ... 1> make it easier to use Google's App Engine, and 2> provide JavaScript developer's a vehicle for creating server side code deployed on App Engine. Part of this goal can be achieved by simplifying the Google's API for App Engine services. </div> <div class="description"> <p> We have had success simplifying the use of datastore, task queues, and memcache. We would like to do the same for the other App Engine APIs like search for instance, as well as provide APIs that integrate other Google services such as Cloud, Drive, Prediction, and other APIs. </p> <div class="links"> <ul style="list-style: none"> <li> Project Lead <a href="http://github.com/bediako">Bediako George</a></li> <li>Source Code <a href="https://github.com/LucidTechnics/Airlift">Airlift</a></li> <li>APIs <a href="https://cloud.google.com/products/">Google Cloud Services</a></li> </ul> </div> </div> </div> <div class="idea"> <h1>Airflow - automated workflow</h1> <div class="description"> <p> Airflow is a workflow generation framework built on Dictation and Airlift. It is designed to look at an application's Dictation file and create an underlying workflow framework that relies on Airlift generated code designed to automate manual workflow tasks. </div> <div class="description"> <p> Using Airlift's inherently restful design along with the descriptive access information provided by a Dictation, it is possible to generate logic that provides automated resource monitoring and change notifications to system actors via email and other mechanisms. We call this process Airflow and are looking for help creating this open source bolt-on for Airlift. </p> <div class="links"> <ul style="list-style: none"> <li>Project Lead <a href="http://github.com/bediako">Bediako George</a></li> <li>Source Code <a href="https://github.com/LucidTechnics/Airlift">Airlift</a></li> </ul> </div> </div> </div> </div>
Airlift-Framework/airlift-framework.github.com
development.html
HTML
bsd-3-clause
4,076
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_FORM_MANAGER_H_ #define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_FORM_MANAGER_H_ #include <stdint.h> #include <string> #include <vector> #include "build/build_config.h" #include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/memory/weak_ptr.h" #include "components/autofill/core/browser/field_types.h" #include "components/autofill/core/common/password_form.h" #include "components/password_manager/core/browser/password_manager_driver.h" #include "components/password_manager/core/browser/password_store.h" #include "components/password_manager/core/browser/password_store_consumer.h" namespace password_manager { class PasswordManager; class PasswordManagerClient; // Per-password-form-{on-page, dialog} class responsible for interactions // between a given form, the per-tab PasswordManager, and the PasswordStore. class PasswordFormManager : public PasswordStoreConsumer { public: // |password_manager| owns this object // |form_on_page| is the form that may be submitted and could need login data. // |ssl_valid| represents the security of the page containing observed_form, // used to filter login results from database. PasswordFormManager(PasswordManager* password_manager, PasswordManagerClient* client, const base::WeakPtr<PasswordManagerDriver>& driver, const autofill::PasswordForm& observed_form, bool ssl_valid); ~PasswordFormManager() override; // Flags describing the result of comparing two forms as performed by // DoesMatch. Individual flags are only relevant for HTML forms, but // RESULT_COMPLETE_MATCH will also be returned to indicate non-HTML forms // completely matching. // The ordering of these flags is important. Larger matches are more // preferred than lower matches. That is, since RESULT_HTML_ATTRIBUTES_MATCH // is greater than RESULT_ACTION_MATCH, a match of only attributes and not // actions will be preferred to one of actions and not attributes. enum MatchResultFlags { RESULT_NO_MATCH = 0, RESULT_ACTION_MATCH = 1 << 0, RESULT_HTML_ATTRIBUTES_MATCH = 1 << 1, RESULT_ORIGINS_MATCH = 1 << 2, RESULT_COMPLETE_MATCH = RESULT_ACTION_MATCH | RESULT_HTML_ATTRIBUTES_MATCH | RESULT_ORIGINS_MATCH }; // Use MatchResultMask to contain combinations of MatchResultFlags values. // It's a signed int rather than unsigned to avoid signed/unsigned mismatch // caused by the enum values implicitly converting to signed int. typedef int MatchResultMask; enum OtherPossibleUsernamesAction { ALLOW_OTHER_POSSIBLE_USERNAMES, IGNORE_OTHER_POSSIBLE_USERNAMES }; // Chooses between the current and new password value which one to save. This // is whichever is non-empty, with the preference being given to the new one. static base::string16 PasswordToSave(const autofill::PasswordForm& form); // Compares basic data of |observed_form_| with |form| and returns how much // they match. The return value is a MatchResultMask bitmask. MatchResultMask DoesManage(const autofill::PasswordForm& form) const; // Retrieves potential matching logins from the database. // |prompt_policy| indicates whether it's permissible to prompt the user to // authorize access to locked passwords. This argument is only used on // platforms that support prompting the user for access (such as Mac OS). void FetchMatchingLoginsFromPasswordStore( PasswordStore::AuthorizationPromptPolicy prompt_policy); // Simple state-check to verify whether this object as received a callback // from the PasswordStore and completed its matching phase. Note that the // callback in question occurs on the same (and only) main thread from which // instances of this class are ever used, but it is required since it is // conceivable that a user (or ui test) could attempt to submit a login // prompt before the callback has occured, which would InvokeLater a call to // PasswordManager::ProvisionallySave, which would interact with this object // before the db has had time to answer with matching password entries. // This is intended to be a one-time check; if the return value is false the // expectation is caller will give up. This clearly won't work if you put it // in a loop and wait for matching to complete; you're (supposed to be) on // the same thread! bool HasCompletedMatching() const; // Update |this| with the |form| that was actually submitted. Used to // determine what type the submitted form is for // IsIgnorableChangePasswordForm() and UMA stats. void SetSubmittedForm(const autofill::PasswordForm& form); // Determines if the user opted to 'never remember' passwords for this form. bool IsBlacklisted() const; // Used by PasswordManager to determine whether or not to display // a SavePasswordBar when given the green light to save the PasswordForm // managed by this. bool IsNewLogin() const; // Returns true if the current pending credentials were found using // origin matching of the public suffix, instead of the signon realm of the // form. bool IsPendingCredentialsPublicSuffixMatch() const; // Checks if the form is a valid password form. Forms which lack password // field are not considered valid. bool HasValidPasswordForm() const; // Through |driver|, supply the associated frame with appropriate information // (fill data, whether to allow password generation, etc.). If this is called // before |this| has data from the PasswordStore, the execution will be // delayed until the data arrives. void ProcessFrame(const base::WeakPtr<PasswordManagerDriver>& driver); void OnGetPasswordStoreResults( ScopedVector<autofill::PasswordForm> results) override; // A user opted to 'never remember' passwords for this form. // Blacklist it so that from now on when it is seen we ignore it. // TODO(vasilii): remove the 'virtual' specifier. virtual void PermanentlyBlacklist(); // If the user has submitted observed_form_, provisionally hold on to // the submitted credentials until we are told by PasswordManager whether // or not the login was successful. |action| describes how we deal with // possible usernames. If |action| is ALLOW_OTHER_POSSIBLE_USERNAMES we will // treat a possible usernames match as a sign that our original heuristics // were wrong and that the user selected the correct username from the // Autofill UI. void ProvisionallySave(const autofill::PasswordForm& credentials, OtherPossibleUsernamesAction action); // Handles save-as-new or update of the form managed by this manager. // Note the basic data of updated_credentials must match that of // observed_form_ (e.g DoesManage(pending_credentials_) == true). // TODO: Make this private once we switch to the new UI. void Save(); // Update the password store entry for |credentials_to_update|, using the // password from |pending_credentials_|. It modifies |pending_credentials_|. // |credentials_to_update| should be one of |best_matches_| or // |pending_credentials_|. void Update(const autofill::PasswordForm& credentials_to_update); // Call these if/when we know the form submission worked or failed. // These routines are used to update internal statistics ("ActionsTaken"). void LogSubmitPassed(); void LogSubmitFailed(); // When attempting to provisionally save |form|, call this to check if it is // actually a change-password form which should be ignored, i.e., whether: // * the username was not explicitly marked with "autocomplete=username", and // * both the current and new password fields are non-empty, and // * the username and password do not match any credentials already stored. // In these cases the username field is detection is unreliable (there might // even be none), and the user should not be bothered with saving a // potentially malformed credential. Once we handle change password forms // correctly, this method should be replaced accordingly. // // Must be called after SetSubmittedForm(). bool is_ignorable_change_password_form() const { DCHECK(form_type_ != kFormTypeUnspecified); return is_ignorable_change_password_form_; } // These functions are used to determine if this form has had it's password // auto generated by the browser. bool has_generated_password() const { return has_generated_password_; } void set_has_generated_password(bool generated_password) { has_generated_password_ = generated_password; } bool password_overridden() const { return password_overridden_; } // Called if the user could generate a password for this form. void MarkGenerationAvailable() { generation_available_ = true; } // Returns the pending credentials. const autofill::PasswordForm& pending_credentials() const { return pending_credentials_; } // Returns the best matches. const autofill::PasswordFormMap& best_matches() const { return best_matches_; } const autofill::PasswordForm* preferred_match() const { return preferred_match_; } const ScopedVector<autofill::PasswordForm>& blacklisted_matches() const { return blacklisted_matches_; } #if defined(UNIT_TEST) void SimulateFetchMatchingLoginsFromPasswordStore() { // Just need to update the internal states. state_ = MATCHING_PHASE; } #endif const autofill::PasswordForm& observed_form() const { return observed_form_; } bool is_possible_change_password_form_without_username() const { return is_possible_change_password_form_without_username_; } // Use this to wipe copies of |pending_credentials_| from the password store // (and |best_matches_| as well. It will only wipe if: // 1. The stored password differs from the one in |pending_credentials_|. // 2. And the store already returned results for the observed form. // This is designed for use with sync credentials, so it will use GAIA utils // to catch equivalent usernames (e.g., if |pending_credentials_| have // username 'test', and the store also contains outdated entries for // 'test@gmail.com' and 'test@googlemail.com', those will be wiped). void WipeStoreCopyIfOutdated(); private: friend class PasswordFormManagerTest; // ManagerAction - What does the manager do with this form? Either it // fills it, or it doesn't. If it doesn't fill it, that's either // because it has no match, or it is blacklisted, or it is disabled // via the AUTOCOMPLETE=off attribute. Note that if we don't have // an exact match, we still provide candidates that the user may // end up choosing. enum ManagerAction { kManagerActionNone = 0, kManagerActionAutofilled, kManagerActionBlacklisted, kManagerActionMax }; // UserAction - What does the user do with this form? If he or she // does nothing (either by accepting what the password manager did, or // by simply (not typing anything at all), you get None. If there were // multiple choices and the user selects one other than the default, // you get Choose, if user selects an entry from matching against the Public // Suffix List you get ChoosePslMatch, if the user types in a new value // for just the password you get OverridePassword, and if the user types in a // new value for the username and password you get // OverrideUsernameAndPassword. enum UserAction { kUserActionNone = 0, kUserActionChoose, kUserActionChoosePslMatch, kUserActionOverridePassword, kUserActionOverrideUsernameAndPassword, kUserActionMax }; // Result - What happens to the form? enum SubmitResult { kSubmitResultNotSubmitted = 0, kSubmitResultFailed, kSubmitResultPassed, kSubmitResultMax }; // What the form is used for. kFormTypeUnspecified is only set before // the SetSubmittedForm() is called, and should never be actually uploaded. enum FormType { kFormTypeLogin, kFormTypeLoginNoUsername, kFormTypeChangePasswordEnabled, kFormTypeChangePasswordDisabled, kFormTypeChangePasswordNoUsername, kFormTypeSignup, kFormTypeSignupNoUsername, kFormTypeLoginAndSignup, kFormTypeUnspecified, kFormTypeMax }; // The maximum number of combinations of the three preceding enums. // This is used when recording the actions taken by the form in UMA. static const int kMaxNumActionsTaken = kManagerActionMax * kUserActionMax * kSubmitResultMax; // Determines if we need to autofill given the results of the query. // Takes ownership of the elements in |result|. void OnRequestDone(ScopedVector<autofill::PasswordForm> result); // Helper for Save in the case that best_matches.size() == 0, meaning // we have no prior record of this form/username/password and the user // has opted to 'Save Password'. The previously preferred login from // |best_matches_| will be reset. void SaveAsNewLogin(); // Helper for OnGetPasswordStoreResults to score an individual result // against the observed_form_. uint32_t ScoreResult(const autofill::PasswordForm& candidate) const; // For the blacklisted |form| returns true iff it blacklists |observed_form_|. bool IsBlacklistMatch(const autofill::PasswordForm& form) const; // Helper for Save in the case that best_matches.size() > 0, meaning // we have at least one match for this form/username/password. This // Updates the form managed by this object, as well as any matching forms // that now need to have preferred bit changed, since updated_credentials // is now implicitly 'preferred'. void UpdateLogin(); // Check to see if |pending| corresponds to an account creation form. If we // think that it does, we label it as such and upload this state to the // Autofill server to vote for the correct username field, and also so that // we will trigger password generation in the future. This function will // update generation_upload_status of |pending| if an upload is performed. void SendAutofillVotes(const autofill::PasswordForm& observed, autofill::PasswordForm* pending); // Update all login matches to reflect new preferred state - preferred flag // will be reset on all matched logins that different than the current // |pending_credentials_|. void UpdatePreferredLoginState(PasswordStore* password_store); // Returns true if |username| is one of the other possible usernames for a // password form in |best_matches_| and sets |pending_credentials_| to the // match which had this username. bool UpdatePendingCredentialsIfOtherPossibleUsername( const base::string16& username); // Returns true if |form| is a username update of a credential already in // |best_matches_|. Sets |pending_credentials_| to the appropriate // PasswordForm if it returns true. bool UpdatePendingCredentialsIfUsernameChanged( const autofill::PasswordForm& form); // Update state to reflect that |credential| was used. This is broken out from // UpdateLogin() so that PSL matches can also be properly updated. void UpdateMetadataForUsage(const autofill::PasswordForm& credential); // Converts the "ActionsTaken" fields into an int so they can be logged to // UMA. int GetActionsTaken() const; // Remove possible_usernames that may contains sensitive information and // duplicates. void SanitizePossibleUsernames(autofill::PasswordForm* form); // Helper function to delegate uploading to the AutofillManager. Returns true // on success. // |login_form_signature| may be empty. It is non-empty when the user fills // and submits a login form using a generated password. In this case, // |login_form_signature| should be set to the submitted form's signature. // Note that in this case, |form.FormSignature()| gives the signature for the // registration form on which the password was generated, rather than the // submitted form's signature. bool UploadPasswordForm(const autofill::FormData& form_data, const base::string16& username_field, const autofill::ServerFieldType& password_type, const std::string& login_form_signature); // Create pending credentials from provisionally saved form and forms received // from password store. void CreatePendingCredentials(); // If |pending_credentials_.username_value| is not empty, iterates over all // forms from |best_matches_| and deletes from the password store all which // are not PSL-matched, have an empty username, and a password equal to // |pending_credentials_.password_value|. void DeleteEmptyUsernameCredentials(); // If |best_matches| contains only one entry then return this entry. Otherwise // for empty |password| return nullptr and for non-empty |password| returns // the unique entry in |best_matches_| with the same password, if it exists, // and nullptr otherwise. autofill::PasswordForm* FindBestMatchForUpdatePassword( const base::string16& password) const; // Set of nonblacklisted PasswordForms from the DB that best match the form // being managed by this. Use a map instead of vector, because we most // frequently require lookups by username value in IsNewLogin. autofill::PasswordFormMap best_matches_; // Set of blacklisted forms from the PasswordStore that best match the current // form. ScopedVector<autofill::PasswordForm> blacklisted_matches_; // The PasswordForm from the page or dialog managed by |this|. const autofill::PasswordForm observed_form_; // Stores provisionally saved form until |pending_credentials_| is created. scoped_ptr<const autofill::PasswordForm> provisionally_saved_form_; // Stores if for creating |pending_credentials_| other possible usernames // option should apply. OtherPossibleUsernamesAction other_possible_username_action_; // The origin url path of observed_form_ tokenized, for convenience when // scoring. const std::vector<std::string> form_path_segments_; // Stores updated credentials when the form was submitted but success is // still unknown. autofill::PasswordForm pending_credentials_; // Whether pending_credentials_ stores a new login or is an update // to an existing one. bool is_new_login_; // Whether this form has an auto generated password. bool has_generated_password_; // Whether the saved password was overridden. bool password_overridden_; // Whether the user can choose to generate a password for this form. bool generation_available_; // Set if the user has selected one of the other possible usernames in // |pending_credentials_|. base::string16 selected_username_; // PasswordManager owning this. const PasswordManager* const password_manager_; // Convenience pointer to entry in best_matches_ that is marked // as preferred. This is only allowed to be null if there are no best matches // at all, since there will always be one preferred login when there are // multiple matches (when first saved, a login is marked preferred). const autofill::PasswordForm* preferred_match_; // If the submitted form is for a change password form and the username // doesn't match saved credentials. bool is_ignorable_change_password_form_; // True if we consider this form to be a change password form without username // field. We use only client heuristics, so it could include signup forms. // The value of this variable is calculated based not only on information from // |observed_form_| but also on the credentials that the user submitted. bool is_possible_change_password_form_without_username_; typedef enum { PRE_MATCHING_PHASE, // Have not yet invoked a GetLogins query to find // matching login information from password store. MATCHING_PHASE, // We've made a GetLogins request, but // haven't received or finished processing result. POST_MATCHING_PHASE // We've queried the DB and processed matching // login results. } PasswordFormManagerState; // State of matching process, used to verify that we don't call methods // assuming we've already processed the request for matching logins, // when we actually haven't. PasswordFormManagerState state_; // The client which implements embedder-specific PasswordManager operations. PasswordManagerClient* client_; // When |this| is created, it is because a form has been found in a frame, // represented by a driver. For that frame, and for all others with an // equivalent form, the associated drivers are needed to perform // frame-specific operations (filling etc.). While |this| waits for the // matching credentials from the PasswordStore, the drivers for frames needing // fill information are buffered in |drivers_|, and served once the results // arrive, if the drivers are still valid. std::vector<base::WeakPtr<PasswordManagerDriver>> drivers_; // These three fields record the "ActionsTaken" by the browser and // the user with this form, and the result. They are combined and // recorded in UMA when the manager is destroyed. ManagerAction manager_action_; UserAction user_action_; SubmitResult submit_result_; // Form type of the form that |this| is managing. Set after SetSubmittedForm() // as our classification of the form can change depending on what data the // user has entered. FormType form_type_; DISALLOW_COPY_AND_ASSIGN(PasswordFormManager); }; } // namespace password_manager #endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_PASSWORD_FORM_MANAGER_H_
Chilledheart/chromium
components/password_manager/core/browser/password_form_manager.h
C
bsd-3-clause
21,936
<!-- %BD_HTML%/SearchResult.htm --> <HTML> <HEAD> <meta http-equiv="Content-Type" content="text/html; charset=windows-1255"> <TITLE>úåöàú àéðèøðè - Takanot File</TITLE> </HEAD> <style> <!-- TR.A_Table {font-color:#3e6ea6; background-color: #f7f9fb; font-size:11;font-family: Arial,} TR.B_Table {font-color:#3e6ea6; background-color: #ecf1f6; font-size:11;font-family: Arial,} TR.C {font-color:#1e4a7a; background-color: #A9CAEF;font-weight:bold; font-size:11;font-family: Arial,} TR.clear { font-color:#1e4a7a; background-color: #FFFFFF;} H5 { font-family:Arial, Helvetica, sans-serif; font-size: 14px;} H3 { font-family:Arial, Helvetica, sans-serif; font-size: 16px;} TD.A_Row { font-family: Arial, Helvetica, sans-serif; font-weight:bold; font-style: normal; color: #093300; font-size: 10px} .defaultFont { color:#1f4a7b;font-family: Arial, Helvetica, sans-serif; font-size: 12px} --> </style> <BODY dir=rtl class="defaultFont"> <CENTER> <IMG src="/budget/Images/title1.jpg" align=bottom alt="ú÷öéá äîãéðä"> <TABLE align="center" border=0 cellspacing=0 cellpadding=0> <TR align="center"> <TD><H3>úåöàú çéôåù ìùðú 2010</H3></TD> </TR> <TR align="center"> <!--<TD><H3>ðúåðé áéöåò ðëåðéí ìñåó çåãù 01/2011</H3></TD>--> <TD><H3>ðúåðé áéöåò ëôé ùðøùîå áñôøé äðäìú äçùáåðåú ùì äîùøãéí - 01/2011<br></H3></TD> </TR> </TR align="center"> <TD><H3>àéï àçéãåú áéï äñòéôéí ìâáé îåòã òãëåï äðúåðéí</H3></TD> </TR> </TABLE> <H5>äñëåîéí äéðí ùì çå÷ äú÷öéá äî÷åøé åáàìôé ù÷ìéí <BR> </H5> </CENTER> <table width="100%" border="0" cellspacing="1" cellpadding="1" bgcolor="#8fbcee"> <TR class="C" align="center"> <TD valign=top width=50>ñòéó</TD> <TD valign=top align="right" width=120>ùí ñòéó</TD> <TD valign=top width=65>äåöàä ðèå</TD> <TD valign=top width=65>äåöàä îåúðéú áäëðñä</TD> <TD valign=top width=65>ñä"ë äåöàä</TD> <TD valign=top width=65>äøùàä ìäúçééá</TD> <TD valign=top width=65>ùéà ë"à</TD> <TD valign=top width=40>ñä"ë ðåöì</TD> <TD valign=top width=40>àçåæ ðåöì</TD> </TR> </TABLE> <table width="100%" border="0" cellspacing="1" cellpadding="1" bgcolor="#8fbcee"> <TR class="B_Table" align="center"> <TD valign=top width=50>&nbsp;95</TD> <TD valign=top align="right" width=120>&nbsp;ðîì çãøä</TD> <TD valign=top width=65>&nbsp; 32,000</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 32,000</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 5.0</TD> <TD valign=top width=40>&nbsp; 22,325</TD> <TD valign=top width=40>&nbsp; 69.77</TD> </TR> <TR class="A_Table" align="center"> <TD valign=top width=50>&nbsp;9502</TD> <TD valign=top align="right" width=120>&nbsp;äåöàåú ðîì çãøä</TD> <TD valign=top width=65>&nbsp; 32,000</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 32,000</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 5.0</TD> <TD valign=top width=40>&nbsp; 22,316</TD> <TD valign=top width=40>&nbsp; 69.74</TD> </TR> <TR class="B_Table" align="center"> <TD valign=top width=50>&nbsp;950201</TD> <TD valign=top align="right" width=120>&nbsp;äåöàåú ðîì çãøä</TD> <TD valign=top width=65>&nbsp; 32,000</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 32,000</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 5.0</TD> <TD valign=top width=40>&nbsp; 22,316</TD> <TD valign=top width=40>&nbsp; 69.74</TD> </TR> <TR class="A_Table" align="center"> <TD valign=top width=50>&nbsp;9569</TD> <TD valign=top align="right" width=120>&nbsp;çùáåï îòáø</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 9</TD> <TD valign=top width=40>&nbsp; 0.00</TD> </TR> <TR class="B_Table" align="center"> <TD valign=top width=50>&nbsp;956999</TD> <TD valign=top align="right" width=120>&nbsp;çùáåï îòáø</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 9</TD> <TD valign=top width=40>&nbsp; 0.00</TD> </TR> <TR class="A_Table" align="center"> <TD valign=top width=50>&nbsp;9570</TD> <TD valign=top align="right" width=120>&nbsp;äëðñåú ðîì çãøä</TD> <TD valign=top width=65>&nbsp; 32,000</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 32,000</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 0</TD> <TD valign=top width=40>&nbsp; 0.00</TD> </TR> <TR class="B_Table" align="center"> <TD valign=top width=50>&nbsp;9572</TD> <TD valign=top align="right" width=120>&nbsp;äëðñåú ðîì çãøä</TD> <TD valign=top width=65>&nbsp; 32,000</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 32,000</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 22,343</TD> <TD valign=top width=40>&nbsp; 69.82</TD> </TR> <TR class="A_Table" align="center"> <TD valign=top width=50>&nbsp;957205</TD> <TD valign=top align="right" width=120>&nbsp;äëðñåú ðîì çãøä</TD> <TD valign=top width=65>&nbsp; 32,000</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 32,000</TD> <TD valign=top width=65>&nbsp; 0</TD> <TD valign=top width=65>&nbsp; 0.0</TD> <TD valign=top width=40>&nbsp; 22,343</TD> <TD valign=top width=40>&nbsp; 69.82</TD> </TR> </TABLE> </CENTER> <BR> <CENTER> <table border="0" cellspacing="1" cellpadding="3" bgcolor="#8fbcee" dir="rtl"> <TR class="C" align="center"> <TD class="A_Row" valign=top width=80>ñéëåí ãå"ç</TD> <TD class="A_Row" valign=top width=60>äåöàä ðèå</TD> <TD class="A_Row" valign=top width=60>äåöàä îåúðéú áäëðñä</TD> <TD class="A_Row" valign=top width=60>ñä"ë äåöàä</TD> <TD class="A_Row" valign=top width=60>äøùàä ìäúçééá</TD> <TD class="A_Row" valign=top width=60>ùéà ë"à</TD> <TD class="A_Row" valign=top width=50>ñä"ë ðåöì</TD> <TD class="A_Row" valign=top width=50>àçåæ ðåöì</TD> </TR> <TR class="clear" align="center"> <TD class="A_Row" valign=top width=80>&nbsp;ú÷öéá î÷åøé</TD> <TD class="A_Row" valign=top width=60>&nbsp; 64,000</TD> <TD class="A_Row" valign=top width=60>&nbsp; 0</TD> <TD class="A_Row" valign=top width=60>&nbsp; 64,000</TD> <TD class="A_Row" valign=top width=60>&nbsp; 0</TD> <TD class="A_Row" valign=top width=60>&nbsp; 5</TD> <TD class="A_Row" valign=top width=50>&nbsp;</TD> <TD class="A_Row" valign=top width=50>&nbsp;</TD> </TR> <!--<TR class="clear" align="center"> <TD class="A_Row" valign=top width=80>&nbsp;ú÷öéá òì ùéðåééå</TD> <TD class="A_Row" valign=top width=60>&nbsp; 64,000</TD> <TD class="A_Row" valign=top width=60>&nbsp; 0</TD> <TD class="A_Row" valign=top width=60>&nbsp; 64,000</TD> <TD class="A_Row" valign=top width=60>&nbsp; 0</TD> <TD class="A_Row" valign=top width=60>&nbsp; 5</TD> <TD class="A_Row" valign=top width=50>&nbsp; 44,668</TD> <TD class="A_Row" valign=top width=50>&nbsp; 69.79</TD> </TR>--> </TABLE> <CENTER> <TABLE WIDTH="100" > <TR> <TD align="center" nowrap> <IMG SRC="/budget/Images/semel.gif" HEIGHT=37 WIDTH=30 border = "0"><BR> <FONT SIZE=-2> <A HREF="http://www.mof.gov.il/rights.htm"> ëì äæëåéåú &copy; .ùîåøåú,2005,îãéðú éùøàì<BR></A> ðùîç ì÷áì àú äòøåúéëí åäöòåúéëí ìëúåáú: </FONT> <FONT SIZE=-2 dir=ltr> <A HREF="mailto:Webmaster@mof.gov.il">Webmaster@mof.gov.il</A><BR> </FONT> </TD> </TR> </TABLE> </CENTER> </CENTER> </BODY> </HTML>
daonb/obudget
data/queries/results/result-2010-95.html
HTML
bsd-3-clause
9,462
from django.contrib.auth.models import User from django.core.management.base import BaseCommand from djangoautoconf.local_key_manager import get_default_admin_username, \ get_default_admin_password from djangoautoconf.management.commands.web_manage_tools.user_creator import create_admin def create_default_admin(): super_username = get_default_admin_username() super_password = get_default_admin_password() if not User.objects.filter(username=super_username).exists(): create_admin(super_username, super_password, "r@j.cn") print("default admin created") else: print("default admin already created") class Command(BaseCommand): args = '' help = 'Create command cache for environment where os.listdir is not working' def handle(self, *args, **options): create_default_admin()
weijia/djangoautoconf
djangoautoconf/management/commands/create_default_super_user.py
Python
bsd-3-clause
844
--- id: 5900f4f91000cf542c51000c challengeType: 5 title: 'Problem 397: Triangle on parabola' forumTopicId: 302062 --- ## Description <section id='description'> On the parabola y = x2/k, three points A(a, a2/k), B(b, b2/k) and C(c, c2/k) are chosen. Let F(K, X) be the number of the integer quadruplets (k, a, b, c) such that at least one angle of the triangle ABC is 45-degree, with 1 ≤ k ≤ K and -X ≤ a < b < c ≤ X. For example, F(1, 10) = 41 and F(10, 100) = 12492. Find F(106, 109). </section> ## Instructions <section id='instructions'> </section> ## Tests <section id='tests'> ```yml tests: - text: <code>euler397()</code> should return 141630459461893730. testString: assert.strictEqual(euler397(), 141630459461893730); ``` </section> ## Challenge Seed <section id='challengeSeed'> <div id='js-seed'> ```js function euler397() { // Good luck! return true; } euler397(); ``` </div> </section> ## Solution <section id='solution'> ```js // solution required ``` </section>
BhaveshSGupta/FreeCodeCamp
curriculum/challenges/english/08-coding-interview-prep/project-euler/problem-397-triangle-on-parabola.english.md
Markdown
bsd-3-clause
1,016
<html xmlns:concordion="http://www.concordion.org/2007/concordion"> <link href="../../../../../concordion.css" rel="stylesheet" type="text/css" /> <body> <h1>Null Result</h1> <p> If the evaluation result is <code>null</code> then the string "(null)" is used for performing the comparison. </p> <div class="example"> <h3>Example</h3> <pre concordion:set="#snippet"> &lt;span concordion:assertEquals="myMethod()"&gt;<b><em>(some expectation)</em></b>&lt;/span&gt; </pre> <table concordion:execute="#outcome = outcomeOfPerformingAssertEquals(#snippet, #expectedString, #result)"> <tr> <th concordion:set="#result">myMethod()<br />Returns</th> <th concordion:set="#expectedString">The Expectation</th> <th concordion:assertEquals="#outcome">Outcome</th> </tr> <tr> <td>null</td> <td>(null)</td> <td>SUCCESS</td> </tr> <tr> <td>null</td> <td>xyz</td> <td>FAILURE</td> </tr> <tr> <td>null</td> <td>null</td> <td>FAILURE</td> </tr> </table> </div> </body> </html>
pobrelkey/xcordion
xcordion/spec/spec/concordion/command/assertEquals/nonString/NullResult.html
HTML
bsd-3-clause
1,380
""" Parsing resource files. See base.py for the ParsedResource base class. """ import os.path from pontoon.sync.formats import ( compare_locales, ftl, json_extensions, lang, po, silme, xliff, ) # To add support for a new resource format, add an entry to this dict # where the key is the extension you're parsing and the value is a # callable returning an instance of a ParsedResource subclass. SUPPORTED_FORMAT_PARSERS = { ".dtd": silme.parse_dtd, ".ftl": ftl.parse, ".inc": silme.parse_inc, ".ini": silme.parse_ini, ".json": json_extensions.parse, ".lang": lang.parse, ".po": po.parse, ".pot": po.parse, ".properties": silme.parse_properties, ".xlf": xliff.parse, ".xliff": xliff.parse, ".xml": compare_locales.parse, } def are_compatible_formats(extension_a, extension_b): """ Return True if given file extensions belong to the same file format. We test that by comparing parsers used by each file extenion. Note that some formats (e.g. Gettext, XLIFF) use multiple file extensions. """ try: return ( SUPPORTED_FORMAT_PARSERS[extension_a] == SUPPORTED_FORMAT_PARSERS[extension_b] ) # File extension not supported except KeyError: return False def parse(path, source_path=None, locale=None): """ Parse the resource file at the given path and return a ParsedResource with its translations. :param path: Path to the resource file to parse. :param source_path: Path to the corresponding resource file in the source directory for the resource we're parsing. Asymmetric formats need this for saving. Defaults to None. :param locale: Object which describes information about currently processed locale. Some of the formats require information about things like e.g. plural form. """ root, extension = os.path.splitext(path) if extension in SUPPORTED_FORMAT_PARSERS: return SUPPORTED_FORMAT_PARSERS[extension]( path, source_path=source_path, locale=locale ) else: raise ValueError("Translation format {0} is not supported.".format(extension))
jotes/pontoon
pontoon/sync/formats/__init__.py
Python
bsd-3-clause
2,225
/* * Copyright (c) 2002-2022, City of Paris * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright notice * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice * and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * License 1.0 */ package fr.paris.lutece.portal.business.style; import java.io.Serializable; /** * This class represents business objects Mode */ public class Theme implements Serializable { public static final String RESOURCE_TYPE = "THEME"; private static final long serialVersionUID = -1423380460541137444L; private String _strCodeTheme; private String _strThemeDescription; private String _strPathImages; private String _strPathCss; private String _strPathJs; private String _strThemeAuthor; private String _strThemeAuthorUrl; private String _strThemeVersion; private String _strThemeLicence; /** * Returns the _strCodeTheme * * @return the _strCodeTheme */ public String getCodeTheme( ) { return _strCodeTheme; } /** * Sets the _strCodeTheme * * @param strCodeTheme * the _strCodeTheme to set */ public void setCodeTheme( String strCodeTheme ) { _strCodeTheme = strCodeTheme; } /** * Returns the _strThemeDescription * * @return the _strThemeDescription */ public String getThemeDescription( ) { return _strThemeDescription; } /** * Sets the _strThemeDescription * * @param strThemeDescription * the _strThemeDescription to set */ public void setThemeDescription( String strThemeDescription ) { _strThemeDescription = strThemeDescription; } /** * Returns the _strPathImages * * @return the _strPathImages */ public String getPathImages( ) { return _strPathImages; } /** * Sets the _strPathImages * * @param strPathImages * the _strPathImages to set */ public void setPathImages( String strPathImages ) { _strPathImages = strPathImages; } /** * Returns the _strPathCss * * @return the _strPathCss */ public String getPathCss( ) { return _strPathCss; } /** * Sets the _strPathCss * * @param strPathCss * the _strPathCss to set */ public void setPathCss( String strPathCss ) { _strPathCss = strPathCss; } /** * Returns the _strPathJs * * @return the _strPathJs */ public String getPathJs( ) { return _strPathJs; } /** * Sets the _strPathJs * * @param strPathJs * the _strPathJs to set */ public void setPathJs( String strPathJs ) { _strPathJs = strPathJs; } /** * Returns the _strThemeAuthor * * @return the _strThemeAuthor */ public String getThemeAuthor( ) { return _strThemeAuthor; } /** * Sets the _strThemeAuthor * * @param strThemeAuthor * the _strThemeAuthor to set */ public void setThemeAuthor( String strThemeAuthor ) { _strThemeAuthor = strThemeAuthor; } /** * Returns the _strThemeAuthorUrl * * @return the _strThemeAuthorUrl */ public String getThemeAuthorUrl( ) { return _strThemeAuthorUrl; } /** * Sets the _strThemeAuthorUrl * * @param strThemeAuthorUrl * the _strThemeAuthorUrl to set */ public void setThemeAuthorUrl( String strThemeAuthorUrl ) { _strThemeAuthorUrl = strThemeAuthorUrl; } /** * Returns the _strThemeVersion * * @return the _strThemeVersion */ public String getThemeVersion( ) { return _strThemeVersion; } /** * Sets the _strThemeVersion * * @param strThemeVersion * the _strThemeVersion to set */ public void setThemeVersion( String strThemeVersion ) { _strThemeVersion = strThemeVersion; } /** * Returns the _strThemeLicence * * @return the _strThemeLicence */ public String getThemeLicence( ) { return _strThemeLicence; } /** * Sets the _strThemeLicence * * @param strThemeLicence * the _strThemeLicence to set */ public void setThemeLicence( String strThemeLicence ) { _strThemeLicence = strThemeLicence; } }
lutece-platform/lutece-core
src/java/fr/paris/lutece/portal/business/style/Theme.java
Java
bsd-3-clause
5,914
<?php namespace backend\modules\group_services\controllers; use Yii; use backend\modules\group_services\models\Group_services; use backend\modules\group_services\models\Group_servicesSearch; use yii\filters\AccessControl; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; /** * Group_servicesController implements the CRUD actions for Group_services model. */ class Group_servicesController extends Controller { public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], ], ], 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'allow' => true, 'roles' => ['admin'], ], ], ], ]; } /** * Lists all Group_services models. * @return mixed */ public function actionIndex() { $searchModel = new Group_servicesSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, ]); } /** * Displays a single Group_services model. * @param integer $id * @return mixed */ public function actionView($id) { return $this->render('view', [ 'model' => $this->findModel($id), ]); } /** * Creates a new Group_services model. * If creation is successful, the browser will be redirected to the 'view' page. * @return mixed */ public function actionCreate() { $model = new Group_services(); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('create', [ 'model' => $model, ]); } } /** * Updates an existing Group_services model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->save()) { return $this->redirect(['view', 'id' => $model->id]); } else { return $this->render('update', [ 'model' => $model, ]); } } /** * Deletes an existing Group_services model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param integer $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } /** * Finds the Group_services model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Group_services the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Group_services::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } }
morozovigor/carbax
backend/modules/group_services/controllers/Group_servicesController.php
PHP
bsd-3-clause
3,587
"use strict"; (function() { // Private fields var storedAppInfo = null; // For Production var appInfo = { "clientId": "7bee6942-63fb-4fbd-88d6-00394941de08", "clientSecret": "SECRETGOESHERE", "redirectUri": chrome.identity.getRedirectURL(""), "scopes": "files.readwrite.all offline_access", "authServiceUri": "https://login.microsoftonline.com/common/oauth2/v2.0/authorize", "tokenServiceUri": "https://login.microsoftonline.com/common/oauth2/v2.0/token" }; var CHUNK_SIZE = 1024 * 1024 * 4; // 4MB // Constructor var OneDriveClient = function(onedriveFS) { this.onedrive_fs_ = onedriveFS; this.access_token_ = null; this.writeRequestMap = {}; initializeJQueryAjaxBinaryHandler.call(this); OneDriveClient.prototype.provideAppInfo(appInfo); }; // Public functions OneDriveClient.prototype.authorize = function(successCallback, errorCallback) { this.access_token_ = OneDriveClient.prototype.getTokenFromCookie(); if (this.access_token_) { successCallback(); } else { var appInfo = OneDriveClient.prototype.getAppInfo(); var AUTH_URL = appInfo.authServiceUri + "?client_id=" + appInfo.clientId + "&response_type=code" + "&redirect_uri=" + encodeURIComponent(appInfo.redirectUri); if (appInfo.scopes) { AUTH_URL += "&scope=" + encodeURIComponent(appInfo.scopes); } if (appInfo.resourceUri) { AUTH_URL += "&resource=" + encodeURIComponent(appInfo.resourceUri); } console.log(AUTH_URL); chrome.identity.launchWebAuthFlow({ "url": AUTH_URL, "interactive": true }, function(redirectUrl) { if (chrome.runtime.lastError) { errorCallback(chrome.runtime.lastError.message); return; } if (redirectUrl) { var codeInfo = OneDriveClient.prototype.getCodeFromUrl(redirectUrl); this.code_ = codeInfo.code; // Get Token via POST $.ajax({ type: "POST", url: appInfo.tokenServiceUri, headers: { "Content-Type": "application/x-www-form-urlencoded" }, responseType: "arraybuffer", data: "client_id=" + appInfo.clientId + "&redirect_uri=" + appInfo.redirectUri + "&client_secret=" + appInfo.clientSecret + "&code=" + this.code_ + "&grant_type=authorization_code", dataType: "text" }).done(function(jsonData) { console.log("OK-jsonData"); console.log(jsonData); var tokenInfo = OneDriveClient.prototype.getTokenInfoFromJSON(jsonData); console.log("tokenInfo"); console.log(tokenInfo); // Process Token - WEAREHERE this.access_token_ = tokenInfo.access_token; this.refresh_token_ = tokenInfo.refresh_token; this.token_expiry_ = parseInt(tokenInfo.expires_in); if (this.access_token_) { OneDriveClient.prototype.setCookie(this.access_token_, this.refresh_token_, this.token_expiry_); this.driveData = OneDriveClient.prototype.getDriveData(); successCallback(); } else { console.log("This error is here. 1"); errorCallback("failed to get an access token "); } }.bind(this)).fail(function(error) { handleError.call(this, error, successCallback, errorCallback); }.bind(this)); } else { errorCallback("Authorization failed"); } }.bind(this)); } }; OneDriveClient.prototype.getDriveData = function(successCallback, errorCallback) { var url = "https://graph.microsoft.com/v1.0/me/drive"; console.log("url set"); $.ajax({ type: "GET", url: url, headers: { "Authorization": "Bearer " + this.access_token_ }, dataType: "json" }).done(function(result) { console.log("preres"); console.log(result); console.log("postres"); var driveData = { id: result.id, name: normalizeName.call(this, result.name), type: result.driveType, quota: result.quota }; console.log("drive data:"); console.log(driveData); console.log("drive data end:"); //return driveData; successCallback(result, false); }.bind(this)).fail(function(error) { handleError.call(this, error, successCallback, errorCallback); }.bind(this)); }; OneDriveClient.prototype.getToken = function(successCallback, errorCallback) { var appInfo = OneDriveClient.prototype.getAppInfo(); var AUTH_URL = appInfo.authServiceUri + "?client_id=" + appInfo.clientId + "&response_type=code" + "&redirect_uri=" + encodeURIComponent(appInfo.redirectUri); if (appInfo.scopes) { AUTH_URL += "&scope=" + encodeURIComponent(appInfo.scopes); } if (appInfo.resourceUri) { AUTH_URL += "&resource=" + encodeURIComponent(appInfo.resourceUri); } console.log(AUTH_URL); chrome.identity.launchWebAuthFlow({ "url": AUTH_URL, "interactive": true }, function(redirectUrl) { if (chrome.runtime.lastError) { errorCallback(chrome.runtime.lastError.message); return; } if (redirectUrl) { var tokenInfo = OneDriveClient.prototype.getTokenInfoFromJSON(redirectUrl); this.access_token_ = tokenInfo.access_token; this.refresh_token_ = tokenInfo.refresh_token; this.token_expiry_ = parseInt(tokenInfo.expires_in); if (this.access_token_) { OneDriveClient.prototype.setCookie(this.access_token_, this.refresh_token_, this.token_expiry_); successCallback(); } else { errorCallback("failed to get an access token "); } } else { errorCallback("Authorization failed"); } }.bind(this)); }; OneDriveClient.prototype.refreshToken = function(successCallback, errorCallback) { var appInfo = OneDriveClient.prototype.getAppInfo(); console.log("appInfo"); console.log(appInfo); this.refresh_token_ = OneDriveClient.prototype.getRefreshTokenFromCookie(); // Get Refresh Token via POST $.ajax({ type: "POST", url: appInfo.tokenServiceUri, headers: { "Content-Type": "application/x-www-form-urlencoded" }, responseType: "arraybuffer", data: "client_id=" + appInfo.clientId + "&redirect_uri=" + appInfo.redirectUri + "&client_secret=" + appInfo.clientSecret + "&refresh_token=" + this.refresh_token_ + "&grant_type=refresh_token", dataType: "text" }).done(function(jsonData) { console.log("OK-jsonData"); console.log(jsonData); var tokenInfo = OneDriveClient.prototype.getTokenInfoFromJSON(jsonData); console.log("tokenInfo"); console.log(tokenInfo); // Process Token - WEAREHERE this.access_token_ = tokenInfo.access_token; this.refresh_token_ = tokenInfo.refresh_token; this.token_expiry_ = parseInt(tokenInfo.expires_in); successCallback(); }.bind(this)).fail(function(error) { this.onedrive_fs_.doUnmount(function() { errorCallback("failed to get a refresh token "); chrome.notifications.create("", { type: "basic", title: "FileSystem for OneDrive", message: "Failed to refresh the access token. File system unmounted.", iconUrl: "/icons/48.png" }, function(notificationId) { }.bind(this)); }.bind(this)); }.bind(this)); if (this.access_token_) { OneDriveClient.prototype.setCookie(this.access_token_, this.refresh_token_, this.token_expiry_); successCallback(); } else { this.onedrive_fs_.doUnmount(function() { errorCallback("failed to get an access token "); chrome.notifications.create("", { type: "basic", title: "FileSystem for OneDrive", message: "Failed to get a new access token. File system unmounted.", iconUrl: "/icons/48.png" }, function(notificationId) { }.bind(this)); }.bind(this)); errorCallback("failed to get an access token "); } }; OneDriveClient.prototype.getTokenInfoFromJSON = function(jsonData) { if (jsonData) { console.log(jsonData); /* '{' + tokenResponse.replace(/([^=]+)=([^&]+)&?/g, '"$1":"$2",').slice(0,-1) + '}',*/ var tokenInfo = JSON.parse(jsonData); console.log("tokenInfo"); console.log(tokenInfo); return tokenInfo; } else { console.log("failed to receive tokenInfo"); } }; OneDriveClient.prototype.getCodeFromUrl = function(redirectUrl) { if (redirectUrl) { var codeResponse = redirectUrl.substring(redirectUrl.indexOf("?") + 1); console.log(codeResponse); var codeInfo = JSON.parse( '{' + codeResponse.replace(/([^=]+)=([^&]+)&?/g, '"$1":"$2",').slice(0,-1) + '}', function(key, value) { return key === "" ? value : decodeURIComponent(value); }); console.log("codeInfo"); console.log(codeInfo); return codeInfo; } else { console.log("failed to receive codeInfo"); } }; OneDriveClient.prototype.getTokenFromCookie = function() { var cookies = document.cookie; var name = "odauth="; var start = cookies.indexOf(name); if (start >= 0) { start += name.length; var end = cookies.indexOf(';', start); if (end < 0) { end = cookies.length; } else { var postCookie = cookies.substring(end); } var value = cookies.substring(start, end); return value; } return ""; }; OneDriveClient.prototype.getRefreshTokenFromCookie = function() { var cookies = document.cookie; var name = "refreshToken="; var start = cookies.indexOf(name); if (start >= 0) { start += name.length; var end = cookies.indexOf(';', start); if (end < 0) { end = cookies.length; } else { var postCookie = cookies.substring(end); } var value = cookies.substring(start, end); return value; } return ""; }; OneDriveClient.prototype.setCookie = function() { var expiration = new Date(); expiration.setTime(expiration.getTime() + this.token_expiry_ * 1000); var cookie = "odauth=" + this.access_token_ +"; refreshToken=" + this.refresh_token_ +"; path=/; expires=" + expiration.toUTCString(); if (document.location.protocol.toLowerCase() === "https") { cookie = cookie + ";secure"; } document.cookie = cookie; }; OneDriveClient.prototype.getAppInfo = function() { if (storedAppInfo) { return storedAppInfo; } var scriptTag = document.getElementById("odauth"); if (!scriptTag) { console.log("the script tag for odauth.js should have its id set to 'odauth'"); } var clientId = scriptTag.getAttribute("clientId"); if (!clientId) { console.log("the odauth script tag needs a clientId attribute set to your application id"); } var scopes = scriptTag.getAttribute("scopes"); // scopes aren't always required, so we don't warn here. var redirectUri = scriptTag.getAttribute("redirectUri"); if (!redirectUri) { console.log("the odauth script tag needs a redirectUri attribute set to your redirect landing url"); } var resourceUri = scriptTag.getAttribute("resourceUri"); var authServiceUri = scriptTag.getAttribute("authServiceUri"); if (!authServiceUri) { console.log("the odauth script tag needs an authServiceUri attribtue set to the oauth authentication service url"); } var appInfo = { "clientId": clientId, "scopes": scopes, "redirectUri": redirectUri, "resourceUri": resourceUri, "authServiceUri": authServiceUri }; storedAppInfo = appInfo; return appInfo; }; OneDriveClient.prototype.provideAppInfo = function(obj) { storedAppInfo = obj; }; OneDriveClient.prototype.getAccessToken = function() { return this.access_token_; }; OneDriveClient.prototype.setAccessToken = function(accessToken) { this.access_token_ = accessToken; }; OneDriveClient.prototype.unauthorize = function(successCallback, errorCallback) { if (this.access_token_) { chrome.identity.removeCachedAuthToken({ token: this.access_token_ }, function() { this.access_token_ = null; successCallback(); }.bind(this)); } else { errorCallback("Not authorized"); } }; OneDriveClient.prototype.getMetadata = function(path, successCallback, errorCallback) { var url = "https://graph.microsoft.com/v1.0/me/drive/root"; if (path !== "/") { url += ":" + path; } $.ajax({ type: "GET", url: url, headers: { "Authorization": "Bearer " + this.access_token_ }, dataType: "json" }).done(function(result) { console.log(result); var entryMetadata = { isDirectory: isDirectoryEntry.call(this, result), name: normalizeName.call(this, result.name), size: result.size, modificationTime: new Date(result.lastModifiedDateTime) }; if (!isDirectoryEntry.call(this, result)) { entryMetadata.mimeType = result.mime_type; } successCallback(entryMetadata); }.bind(this)).fail(function(error) { handleError.call(this, error, successCallback, errorCallback); }.bind(this)); }; OneDriveClient.prototype.readDirectory = function(path, successCallback, errorCallback) { var url = "https://graph.microsoft.com/v1.0/me/drive/root"; if (path !== "/") { url += ":" + path + ":"; } $.ajax({ type: "GET", url: url + "/children", headers: { "Authorization": "Bearer " + this.access_token_ }, dataType: "json" }).done(function(result) { console.log(result); var contents = result.value; createEntryMetadatas.call(this, contents, 0, [], successCallback, errorCallback); }.bind(this)); }; OneDriveClient.prototype.openFile = function(filePath, requestId, mode, successCallback, errorCallback) { this.writeRequestMap[requestId] = { mode: mode }; successCallback(); }; OneDriveClient.prototype.closeFile = function(filePath, openRequestId, successCallback, errorCallback) { var writeRequest = this.writeRequestMap[openRequestId]; if (writeRequest && writeRequest.mode === "WRITE") { var localFileName = writeRequest.localFileName; var errorHandler = function(error) { console.log("writeFile failed"); console.log(error); errorCallback("FAILED"); }.bind(this); window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.requestFileSystem(window.TEMPORARY, 100 * 1024 * 1024, function(fs) { fs.root.getFile(localFileName, {}, function(fileEntry) { fileEntry.file(function(file) { var totalSize = file.size; var reader = new FileReader(); reader.addEventListener("loadend", function() { sendSimpleUpload.call(this, { filePath: filePath, data: reader.result }, function() { fileEntry.remove(function() { successCallback(); }.bind(this), errorHandler); }.bind(this), errorCallback); }.bind(this)); reader.readAsArrayBuffer(file); }.bind(this)); }.bind(this), errorHandler); }.bind(this), errorHandler); } else { successCallback(); } }; OneDriveClient.prototype.readFile = function(filePath, offset, length, successCallback, errorCallback) { $.ajax({ type: "GET", url: "https://graph.microsoft.com/v1.0/me/drive/root:" + filePath + ":/content", headers: { "Authorization": "Bearer " + this.access_token_, "Range": "bytes=" + offset + "-" + (offset + length - 1) }, dataType: "binary", responseType: "arraybuffer" }).done(function(result) { console.log(result); successCallback(result, false); }.bind(this)).fail(function(error) { handleError.call(this, error, successCallback, errorCallback); }.bind(this)); }; OneDriveClient.prototype.createDirectory = function(directoryPath, successCallback, errorCallback) { var lastSlashPos = directoryPath.lastIndexOf("/"); var parent = directoryPath.substring(0, lastSlashPos); var name = directoryPath.substring(lastSlashPos + 1); var url = "https://graph.microsoft.com/v1.0/me/drive/root"; if (parent !== "") { url += ":" + parent + ":"; } $.ajax({ type: "POST", url: url + "/children", headers: { "Authorization": "Bearer " + this.access_token_, "Content-Type": "application/json" }, data: JSON.stringify({ name: name, folder: {} }), dataType: "json" }).done(function(result) { successCallback(); }.bind(this)).fail(function(error) { handleError.call(this, error, successCallback, errorCallback); }.bind(this)); }; OneDriveClient.prototype.deleteEntry = function(entryPath, successCallback, errorCallback) { $.ajax({ type: "DELETE", url: "https://graph.microsoft.com/v1.0/me/drive/root:" + entryPath, headers: { "Authorization": "Bearer " + this.access_token_ }, dataType: "json" }).done(function(result) { successCallback(); }.bind(this)).fail(function(error) { handleError.call(this, error, successCallback, errorCallback); }.bind(this)); }; OneDriveClient.prototype.moveEntry = function(sourcePath, targetPath, successCallback, errorCallback) { var sourceLastSlashPos = sourcePath.lastIndexOf("/"); var sourceDir = sourcePath.substring(0, sourceLastSlashPos); var sourceName = sourcePath.substring(sourceLastSlashPos + 1); var targetLastSlashPos = targetPath.lastIndexOf("/"); var targetDir = targetPath.substring(0, targetLastSlashPos); var targetName = targetPath.substring(targetLastSlashPos + 1); var data = {}; if (sourceName !== targetName) { data.name = targetName; } if (sourceDir !== targetDir) { data.parentReference = { path: "/drive/root:" + targetDir }; } $.ajax({ type: "PATCH", url: "https://graph.microsoft.com/v1.0/me/drive/root:" + sourcePath, headers: { "Authorization": "Bearer " + this.access_token_, "Content-Type": "application/json" }, data: JSON.stringify(data), dataType: "json" }).done(function(result) { successCallback(); }.bind(this)).fail(function(error) { handleError.call(this, error, successCallback, errorCallback); }.bind(this)); }; OneDriveClient.prototype.copyEntry = function(sourcePath, targetPath, successCallback, errorCallback) { var sourceLastSlashPos = sourcePath.lastIndexOf("/"); var sourceDir = sourcePath.substring(0, sourceLastSlashPos); var targetLastSlashPos = targetPath.lastIndexOf("/"); var targetDir = targetPath.substring(0, targetLastSlashPos); var data = {}; if (sourceDir !== targetDir) { data.parentReference = { path: "/drive/root:" + targetDir }; } $.ajax({ type: "POST", url: "https://graph.microsoft.com/v1.0/me/drive/root:" + sourcePath + ":/action.copy", headers: { "Authorization": "Bearer " + this.access_token_, "Content-Type": "application/json", "Prefer": "respond-async" }, data: JSON.stringify(data), dataType: "json" }).done(function(result) { successCallback(); }.bind(this)).fail(function(error) { if (error.status === 202) { successCallback(); } else { handleError.call(this, error, successCallback, errorCallback); } }.bind(this)); }; OneDriveClient.prototype.createFile = function(filePath, successCallback, errorCallback) { $.ajax({ type: "PUT", url: "https://graph.microsoft.com/v1.0/me/drive/root:" + filePath + ":/content", headers: { "Authorization": "Bearer " + this.access_token_, "Content-Type": "application/octet-stream" }, processData: false, data: new ArrayBuffer(), dataType: "json" }).done(function(result) { successCallback(); }.bind(this)).fail(function(error) { handleError.call(this, error, successCallback, errorCallback); }.bind(this)); }; OneDriveClient.prototype.writeFile = function(filePath, data, offset, openRequestId, successCallback, errorCallback) { var writeRequest = this.writeRequestMap[openRequestId]; writeRequest.filePath = filePath; var localFileName = String(openRequestId); writeRequest.localFileName = localFileName; var errorHandler = function(error) { console.log("writeFile failed"); console.log(error); errorCallback("FAILED"); }.bind(this); window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.requestFileSystem(window.TEMPORARY, 100 * 1024 * 1024, function(fs) { fs.root.getFile(localFileName, {create: true, exclusive: false}, function(fileEntry) { fileEntry.createWriter(function(fileWriter) { fileWriter.onwriteend = function(e) { successCallback(); }.bind(this); fileWriter.onerror = errorHandler; fileWriter.seek(offset); var blob = new Blob([data]); fileWriter.write(blob); }.bind(this), errorHandler); }.bind(this), errorHandler); }.bind(this), errorHandler); }; OneDriveClient.prototype.truncate = function(filePath, length, successCallback, errorCallback) { $.ajax({ type: "GET", url: "https://graph.microsoft.com/v1.0/me/drive/root:" + filePath + ":/content", headers: { "Authorization": "Bearer " + this.access_token_ }, dataType: "binary", responseType: "arraybuffer" }).done(function(data) { if (length < data.byteLength) { // Truncate var req = { filePath: filePath, data: data.slice(0, length) }; // createUploadSession.call(this, req, successCallback, errorCallback); sendSimpleUpload.call(this, req, successCallback, errorCallback); } else { // Pad with null bytes. var diff = length - data.byteLength; var blob = new Blob([data, new Array(diff + 1).join('\0')]); var reader = new FileReader(); reader.addEventListener("loadend", function() { var req = { filePath: filePath, data: reader.result }; // createUploadSession.call(this, req, successCallback, errorCallback); sendSimpleUpload.call(this, req, successCallback, errorCallback); }.bind(this)); reader.readAsArrayBuffer(blob); } }.bind(this)).fail(function(error) { handleError.call(this, error, successCallback, errorCallback); }.bind(this)); }; // Private functions var handleError = function(error, successCallback, errorCallback) { console.log(error); var status = Number(error.status); if (status === 404) { errorCallback("NOT_FOUND"); } else if (status === 401) { // Access token has already expired or unauthorized. Unmount. this.onedrive_fs_.doUnmount(function() { errorCallback("INVALID_OPERATION"); chrome.notifications.create("", { type: "basic", title: "File System for OneDrive", message: "The access token has expired. File system unmounted.", iconUrl: "/icons/48.png" }, function(notificationId) { }.bind(this)); }.bind(this)); } else { errorCallback("FAILED"); } }; var sendSimpleUpload = function(options, successCallback, errorCallback) { $.ajax({ type: "PUT", url: "https://graph.microsoft.com/v1.0/me/drive/root:" + options.filePath + ":/content", dataType: "json", headers: { "Authorization": "Bearer " + this.access_token_, "Content-Type": "application/octet-stream" }, processData: false, data: options.data }).done(function(result) { console.log(result); successCallback(); }.bind(this)).fail(function(error) { handleError.call(this, error, successCallback, errorCallback); }.bind(this)); }; /* var createUploadSession = function(options, successCallback, errorCallback) { $.ajax({ type: "POST", url: "https://graph.microsoft.com/v1.0/me/drive/root:" + options.filePath + ":/upload.createSession", headers: { "Authorization": "Bearer " + this.access_token_, "Content-Type": "application/json" }, data: JSON.stringify({ "@name.conflictBehavior": "replace" }), dataType: "json" }).done(function(data) { console.log(data); options.uploadUrl = data.uploadUrl; sendContents.call(this, options, successCallback, errorCallback); }.bind(this)).fail(function(error) { handleError.call(this, error, successCallback, errorCallback); }.bind(this)); }; var sendContents = function(options, successCallback, errorCallback) { if (!options.hasMore) { successCallback(); } else { var len = options.data.byteLength; var remains = len - options.sentBytes; var sendLength = Math.min(CHUNK_SIZE, remains); var more = (options.sentBytes + sendLength) < len; var sendBuffer = options.data.slice(options.sentBytes, sendLength); $.ajax({ type: "PUT", url: options.uploadUrl, dataType: "json", headers: { "Authorization": "Bearer " + this.access_token_, "Content-Range": "bytes " + options.offset + "-" + (options.offset + sendLength - 1) + "/" + len //"Content-Type": "application/octet-stream" }, processData: false, data: sendBuffer }).done(function(result) { console.log(result); var writeRequest = this.writeRequestMap[options.openRequestId]; if (writeRequest) { writeRequest.uploadId = result.upload_id; } var req = { filePath: options.filePath, data: options.data, offset: options.offset + sendLength, sentBytes: options.sendBytes + sendLength, uploadId: result.upload_id, hasMore: more, openRequestId: options.openRequestId, uploadUrl: options.uploadUrl }; sendContents.call(this, req, successCallback, errorCallback); }.bind(this)).fail(function(error) { handleError.call(this, error, successCallback, errorCallback); }.bind(this)); } }; */ var createEntryMetadatas = function(contents, index, entryMetadatas, successCallback, errorCallback) { if (contents.length === index) { successCallback(entryMetadatas); } else { var content = contents[index]; var entryMetadata = { isDirectory: isDirectoryEntry.call(this, content), name: content.name, size: content.size, modificationTime: new Date(content.lastModifiedDateTime) }; if (!isDirectoryEntry.call(this, content)) { if (content.file) { entryMetadata.mimeType = content.file.mimeType; } else { entryMetadata.mimeType = content.package.type; } } console.log(entryMetadata); entryMetadatas.push(entryMetadata); createEntryMetadatas.call(this, contents, ++index, entryMetadatas, successCallback, errorCallback); } }; var isDirectoryEntry = function(entry) { var folder = entry.folder; if (folder) { return true; } else { return false; } }; var normalizeName = function(name) { if (name === "root") { return ""; } else { return name; } }; var initializeJQueryAjaxBinaryHandler = function() { $.ajaxTransport("+binary", function(options, originalOptions, jqXHR){ if (window.FormData && ((options.dataType && (options.dataType === 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob))))) { return { send: function(_, callback){ var xhr = new XMLHttpRequest(), url = options.url, type = options.type, dataType = options.responseType || "blob", data = options.data || null; xhr.addEventListener('load', function(){ var data = {}; data[options.dataType] = xhr.response; callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders()); }); xhr.open(type, url, true); for (var key in options.headers) { xhr.setRequestHeader(key, options.headers[key]); } xhr.responseType = dataType; xhr.send(data); }, abort: function(){ jqXHR.abort(); } }; } }); }; // Export window.OneDriveClient = OneDriveClient; })();
yoichiro/chromeos-filesystem-onedrive
app/scripts/onedrive_client.js
JavaScript
bsd-3-clause
34,714
// Copyright (c) 2011-2013, Cornell University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of WTF nor the names of its contributors may be // used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "common/macros.h" #include "client/message_hyperdex_search.h" using wtf::message_hyperdex_search; message_hyperdex_search :: message_hyperdex_search(client* cl, const char* space, const char* name, const char* regex) : message(cl, OPCODE_HYPERDEX_SEARCH) , m_space(space) , m_name(name) , m_regex(regex) , m_status(HYPERDEX_CLIENT_GARBAGE) , m_attrs(NULL) , m_attrs_size(0) { TRACE; } message_hyperdex_search :: ~message_hyperdex_search() throw() { TRACE; } int64_t message_hyperdex_search :: send() { TRACE; struct hyperdex_client_attribute_check check; check.attr = m_name.c_str(); check.value = m_regex.c_str(); check.value_sz = m_regex.size(); check.datatype = HYPERDATATYPE_STRING; check.predicate = HYPERPREDICATE_REGEX; hyperdex::Client* hc = &m_cl->m_hyperdex_client; //XXX: begin transaction here m_reqid = hc->search("wtf", &check, 1, &m_status, &m_attrs, &m_attrs_size); return m_reqid; }
seanogden/wtf
client/message_hyperdex_search.cc
C++
bsd-3-clause
2,881
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _QMITKTOFRECORDERWIDGET_H_INCLUDED #define _QMITKTOFRECORDERWIDGET_H_INCLUDED #include <MitkToFUIExports.h> #include <ui_QmitkToFRecorderWidgetControls.h> //QT headers #include <QWidget> #include <QString> #include <QDialog> #include <QFileDialog> //itk headers #include "itkCommand.h" //mitk headers #include <mitkToFImageGrabber.h> #include <mitkToFImageRecorder.h> class QmitkStdMultiWidget; struct QFileDialogArgs; class QFileIconProvider; class QFileDialogPrivate; /** * @brief Widget allowing to play / record ToF data * * @ingroup ToFUI */ class MitkToFUI_EXPORT QmitkToFRecorderWidget :public QWidget { //this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkToFRecorderWidget(QWidget* p = 0, Qt::WindowFlags f1 = 0); virtual ~QmitkToFRecorderWidget(); /* @brief This method is part of the widget an needs not to be called seperately. */ virtual void CreateQtPartControl(QWidget *parent); /* @brief This method is part of the widget an needs not to be called seperately. (Creation of the connections of main and control widget.)*/ virtual void CreateConnections(); /*! \brief Set the parameters used for this widget \param ToFImageGrabber image grabber providing images from a ToF device \param tofImageRecorder image recorder allowing to record ToF images */ void SetParameter(mitk::ToFImageGrabber* ToFImageGrabber, mitk::ToFImageRecorder* toFImageRecorder); /*! \brief resets the GUI elements to the initial state. Play button: enabled, Stop button: disabled, Recording box: disabled */ void ResetGUIToInitial(); signals: /*! \brief signal emitted when "Play" button is pressed */ void ToFCameraStarted(); /*! \brief signal emitted when "Stop" button is pressed */ void ToFCameraStopped(); /*! \brief signal emitted when recording is started */ void RecordingStarted(); /*! \brief signal emitted AbortEvent() in ToFImageRecorder is observed */ void RecordingStopped(); public slots: /*! \brief slot invoking to start the camera. Calls StartCamera() and emits ToFCameraStarted signal */ void OnPlay(); /*! \brief slot invoking to stop the camera and the recorder. Calls StopCamera() and StopRecorder and emits ToFCameraStarted signal. Resets GUI to initial state. */ void OnStop(); /*! \brief slot invoking to start the recording After letting the user chose a file location for the record, m_ImageRecorder->StartRecording() is inoved. */ void OnStartRecorder(); /*! \brief slot resetting the GUI elements of the recording box */ void OnRecordingStopped(); /*! \brief slot activating/deactivating "number of frames" spin box dependent on recording mode (PerFrame / Infinite) */ void OnChangeRecordModeComboBox(int index); protected: /*! \brief starts the camera by calling ToFImageGrabber::StartCamera() */ void StartCamera(); /*! \brief stops the camera by calling ToFImageGrabber::StopCamera() */ void StopCamera(); /*! \brief stops the recording by calling ToFImageRecorder::StopRecording() */ void StopRecorder(); /*! \brief emits RecordingStopped signal. */ void StopRecordingCallback(); /*! \brief adapted version of QFileDialog::getSaveFileName() The user is now asked to choose which images he wants to save (Distance and/or Intensity and/or Amplitude image) and which type the saved image should have (3D, 2D+t). */ static QString getSaveFileName(mitk::ToFImageWriter::ToFImageType& tofImageType, bool& distanceImageSelected, bool& amplitudeImageSelected, bool& intensityImageSelected, bool& rgbImageSelected, bool& rawDataSelected, QWidget *parent = 0, const QString &caption = QString(), const QString &dir = QString(), const QString &filter = QString(), QString *selectedFilter = 0, QFileDialog::Options options = 0 ); /*! \brief method creating a filename from the given information \param dir directory to save the file \param baseFilename base file name entered by the user \param modulationFreq modulation frequency of the camera \param integrationTime integration time of the camera \param numOfFrames number of frames recorded \param extension file extension \param imageType type of image (DistanceImage, IntensityImage, AmplitudeImage) \return dir+"/"+baseFilename+"_MF"+modulationFreq+"_IT"+integrationTime+"_"+numOfFrames+"Images"+imageType+extension */ std::string prepareFilename(std::string dir, std::string baseFilename, std::string modulationFreq, std::string integrationTime, std::string numOfFrames, std::string extension, std::string imageType); Ui::QmitkToFRecorderWidgetControls* m_Controls; ///< member holding the UI elements of this widget mitk::ToFImageGrabber::Pointer m_ToFImageGrabber; ///< member holding the ToFImageGrabber for acquiring ToF images mitk::ToFImageRecorder::Pointer m_ToFImageRecorder; ///< member holding the recorder for ToF images mitk::ToFImageRecorder::RecordMode m_RecordMode; ///< member holding the RecordMode of the recorder (PerFrame / Infinite) typedef itk::SimpleMemberCommand<QmitkToFRecorderWidget> CommandType; CommandType::Pointer m_StopRecordingCommand; ///< itkCommand for abort of recording private: }; #endif // _QMITKTOFRECORDERWIDGET_H_INCLUDED
danielknorr/MITK
Modules/ToFUI/Qmitk/QmitkToFRecorderWidget.h
C
bsd-3-clause
6,685
qc::db_trans ============ part of [Database API](../db.md) Usage ----- `db_trans code ?on_error_code?` Description ----------- Execute code within a database transaction. Rollback on database or tcl error. Examples -------- ```tcl db_trans { db_dml {update account set balance=balance-10 where account_id=1} db_dml {update account set balance=balance+10 where account_id=2} } db_trans { # Select for update db_1row {select order_state from sales_order where order_number=123 for update} if { ![string equal $order_state OPEN ] } { # Throw error and ROLLBACK error "Can't invoice sales order $order_number because it is not OPEN" } # Perform action that requires order to be OPEN invoice_sales_order 123 } db_trans { blow-up } { # cleanup here } ``` ---------------------------------- *[Qcode Software Limited] [qcode]* [qcode]: http://www.qcode.co.uk "Qcode Software"
qcode-software/qcode-tcl
doc/procs/db_trans.md
Markdown
bsd-3-clause
929
<?php // DO NOT EDIT! Generated by Protobuf-PHP protoc plugin 1.0 // Source: vtgate.proto // Date: 2016-01-22 01:34:42 namespace Vitess\Proto\Vtgate { class Session extends \DrSlump\Protobuf\Message { /** @var boolean */ public $in_transaction = null; /** @var \Vitess\Proto\Vtgate\Session\ShardSession[] */ public $shard_sessions = array(); /** @var \Closure[] */ protected static $__extensions = array(); public static function descriptor() { $descriptor = new \DrSlump\Protobuf\Descriptor(__CLASS__, 'vtgate.Session'); // OPTIONAL BOOL in_transaction = 1 $f = new \DrSlump\Protobuf\Field(); $f->number = 1; $f->name = "in_transaction"; $f->type = \DrSlump\Protobuf::TYPE_BOOL; $f->rule = \DrSlump\Protobuf::RULE_OPTIONAL; $descriptor->addField($f); // REPEATED MESSAGE shard_sessions = 2 $f = new \DrSlump\Protobuf\Field(); $f->number = 2; $f->name = "shard_sessions"; $f->type = \DrSlump\Protobuf::TYPE_MESSAGE; $f->rule = \DrSlump\Protobuf::RULE_REPEATED; $f->reference = '\Vitess\Proto\Vtgate\Session\ShardSession'; $descriptor->addField($f); foreach (self::$__extensions as $cb) { $descriptor->addField($cb(), true); } return $descriptor; } /** * Check if <in_transaction> has a value * * @return boolean */ public function hasInTransaction(){ return $this->_has(1); } /** * Clear <in_transaction> value * * @return \Vitess\Proto\Vtgate\Session */ public function clearInTransaction(){ return $this->_clear(1); } /** * Get <in_transaction> value * * @return boolean */ public function getInTransaction(){ return $this->_get(1); } /** * Set <in_transaction> value * * @param boolean $value * @return \Vitess\Proto\Vtgate\Session */ public function setInTransaction( $value){ return $this->_set(1, $value); } /** * Check if <shard_sessions> has a value * * @return boolean */ public function hasShardSessions(){ return $this->_has(2); } /** * Clear <shard_sessions> value * * @return \Vitess\Proto\Vtgate\Session */ public function clearShardSessions(){ return $this->_clear(2); } /** * Get <shard_sessions> value * * @param int $idx * @return \Vitess\Proto\Vtgate\Session\ShardSession */ public function getShardSessions($idx = NULL){ return $this->_get(2, $idx); } /** * Set <shard_sessions> value * * @param \Vitess\Proto\Vtgate\Session\ShardSession $value * @return \Vitess\Proto\Vtgate\Session */ public function setShardSessions(\Vitess\Proto\Vtgate\Session\ShardSession $value, $idx = NULL){ return $this->_set(2, $value, $idx); } /** * Get all elements of <shard_sessions> * * @return \Vitess\Proto\Vtgate\Session\ShardSession[] */ public function getShardSessionsList(){ return $this->_get(2); } /** * Add a new element to <shard_sessions> * * @param \Vitess\Proto\Vtgate\Session\ShardSession $value * @return \Vitess\Proto\Vtgate\Session */ public function addShardSessions(\Vitess\Proto\Vtgate\Session\ShardSession $value){ return $this->_add(2, $value); } } }
guokeno0/vitess
php/src/Vitess/Proto/Vtgate/Session.php
PHP
bsd-3-clause
3,544
# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make <target>' where <target> is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/textprocessor.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/textprocessor.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/textprocessor" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/textprocessor" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt."
jibaku/django-textprocessor
docs/Makefile
Makefile
bsd-3-clause
5,592
/* * Copyright (c) 2016 Villu Ruusmann */ package org.jpmml.model.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.dmg.pmml.Version; /** * Marks a feature that was changed from optional to required in the specified PMML schema version. * * @see Optional */ @Retention ( value = RetentionPolicy.RUNTIME ) @Target ( value = {ElementType.TYPE, ElementType.FIELD} ) public @interface Required { Version value(); }
jpmml/jpmml-model
pmml-model/src/main/java/org/jpmml/model/annotations/Required.java
Java
bsd-3-clause
558
import astar import os import sys import csv import math from difflib import SequenceMatcher import unittest class Station: def __init__(self, id, name, position): self.id = id self.name = name self.position = position self.links = [] def build_data(): """builds the 'map' by reading the data files""" stations = {} rootdir = os.path.dirname(__file__) r = csv.reader(open(os.path.join(rootdir, 'underground_stations.csv'))) next(r) # jump the first line for record in r: id = int(record[0]) lat = float(record[1]) lon = float(record[2]) name = record[3] stations[id] = Station(id, name, (lat, lon)) r = csv.reader(open(os.path.join(rootdir, 'underground_routes.csv'))) next(r) # jump the first line for id1, id2, lineNumber in r: id1 = int(id1) id2 = int(id2) stations[id1].links.append(stations[id2]) stations[id2].links.append(stations[id1]) return stations STATIONS = build_data() def get_station_by_name(name): """lookup by name, the name does not have to be exact.""" name = name.lower() ratios = [(SequenceMatcher(None, name, v.name.lower()).ratio(), v) for v in STATIONS.values()] best = max(ratios, key=lambda a: a[0]) if best[0] > 0.7: return best[1] else: return None def get_path(s1, s2): """ runs astar on the map""" def distance(n1, n2): """computes the distance between two stations""" latA, longA = n1.position latB, longB = n2.position # convert degres to radians!! latA, latB, longA, longB = map( lambda d: d * math.pi / 180, (latA, latB, longA, longB)) x = (longB - longA) * math.cos((latA + latB) / 2) y = latB - latA return math.hypot(x, y) return astar.find_path(s1, s2, neighbors_fnct=lambda s: s.links, heuristic_cost_estimate_fnct=distance, distance_between_fnct=distance) class LondonTests(unittest.TestCase): def test_solve_underground(self): for n1,n2 in [('Chesham', 'Wimbledon'), ('Uxbridge','Upminster'), ('Heathrow Terminal 4','Epping')]: s1 = get_station_by_name(n1) s2 = get_station_by_name(n2) path = get_path(s1, s2) self.assertTrue(not path is None) if __name__ == '__main__': if len(sys.argv) != 3: print( 'Usage : {script} <station1> <station2>'.format(script=sys.argv[0])) sys.exit(1) station1 = get_station_by_name(sys.argv[1]) print('Station 1 : ' + station1.name) station2 = get_station_by_name(sys.argv[2]) print('Station 2 : ' + station2.name) print('-' * 80) path = get_path(station1, station2) if path: for s in path: print(s.name) else: raise Exception('path not found!')
jrialland/python-astar
tests/london/test_london_underground.py
Python
bsd-3-clause
2,878
{% extends "base.html" %} {% load i18n %} {% block title %}{{block.super}} - Password Reset Confirm{% endblock %} {% block content %} {% if validlink %} <form method="post" action=".">{% csrf_token %} {{ form.as_p }} <input type="submit" value="{% trans 'Submit' %}" /> </form> {% else %} <p>{% trans "Password reset failed" %}</p> {% endif %} {% endblock %}
tedtieken/django-simple-registration
templates/simple_registration/password_reset_confirm.html
HTML
bsd-3-clause
372
#ifndef NVTRISTRIP_H #define NVTRISTRIP_H #ifndef NULL #define NULL 0 #endif namespace NvTriStrip { //////////////////////////////////////////////////////////////////////////////////////// // Public interface for stripifier //////////////////////////////////////////////////////////////////////////////////////// //GeForce1 and 2 cache size #define CACHESIZE_GEFORCE1_2 16 //GeForce3 cache size #define CACHESIZE_GEFORCE3 24 enum PrimType { PT_LIST, PT_STRIP, PT_FAN }; struct PrimitiveGroup { PrimType type; unsigned int numIndices; unsigned short* indices; //////////////////////////////////////////////////////////////////////////////////////// PrimitiveGroup() : type(PT_STRIP), numIndices(0), indices(NULL) {} ~PrimitiveGroup() { if(indices) delete [] indices; indices = NULL; } }; //////////////////////////////////////////////////////////////////////////////////////// // EnableRestart() // // For GPUs that support primitive restart, this sets a value as the restart index // // Restart is meaningless if strips are not being stitched together, so enabling restart // makes NvTriStrip forcing stitching. So, you'll get back one strip. // // Default value: disabled // void EnableRestart(const unsigned int restartVal); //////////////////////////////////////////////////////////////////////////////////////// // DisableRestart() // // For GPUs that support primitive restart, this disables using primitive restart // void DisableRestart(); //////////////////////////////////////////////////////////////////////////////////////// // SetCacheSize() // // Sets the cache size which the stripfier uses to optimize the data. // Controls the length of the generated individual strips. // This is the "actual" cache size, so 24 for GeForce3 and 16 for GeForce1/2 // You may want to play around with this number to tweak performance. // // Default value: 16 // void SetCacheSize(const unsigned int cacheSize); //////////////////////////////////////////////////////////////////////////////////////// // SetStitchStrips() // // bool to indicate whether to stitch together strips into one huge strip or not. // If set to true, you'll get back one huge strip stitched together using degenerate // triangles. // If set to false, you'll get back a large number of separate strips. // // Default value: true // void SetStitchStrips(const bool bStitchStrips); //////////////////////////////////////////////////////////////////////////////////////// // SetMinStripSize() // // Sets the minimum acceptable size for a strip, in triangles. // All strips generated which are shorter than this will be thrown into one big, separate list. // // Default value: 0 // void SetMinStripSize(const unsigned int minSize); //////////////////////////////////////////////////////////////////////////////////////// // SetListsOnly() // // If set to true, will return an optimized list, with no strips at all. // // Default value: false // void SetListsOnly(const bool bListsOnly); //////////////////////////////////////////////////////////////////////////////////////// // GenerateStrips() // // in_indices: input index list, the indices you would use to render // in_numIndices: number of entries in in_indices // primGroups: array of optimized/stripified PrimitiveGroups // numGroups: number of groups returned // // Be sure to call delete[] on the returned primGroups to avoid leaking mem // bool GenerateStrips(const unsigned short* in_indices, const unsigned int in_numIndices, PrimitiveGroup** primGroups, unsigned short* numGroups, bool validateEnabled = false); //////////////////////////////////////////////////////////////////////////////////////// // RemapIndices() // // Function to remap your indices to improve spatial locality in your vertex buffer. // // in_primGroups: array of PrimitiveGroups you want remapped // numGroups: number of entries in in_primGroups // numVerts: number of vertices in your vertex buffer, also can be thought of as the range // of acceptable values for indices in your primitive groups. // remappedGroups: array of remapped PrimitiveGroups // // Note that, according to the remapping handed back to you, you must reorder your // vertex buffer. // // Credit goes to the MS Xbox crew for the idea for this interface. // void RemapIndices(const PrimitiveGroup* in_primGroups, const unsigned short numGroups, const unsigned short numVerts, PrimitiveGroup** remappedGroups); } //End namespace #endif
BlazesRus/niflib
NvTriStrip/NvTriStrip.h
C
bsd-3-clause
4,567
# !usr/bin/env python # -*- coding: utf-8 -*- # # Licensed under a 3-clause BSD license. # # @Author: Brian Cherinka # @Date: 2018-10-11 17:51:43 # @Last modified by: Brian Cherinka # @Last Modified time: 2018-11-29 17:23:15 from __future__ import print_function, division, absolute_import import numpy as np import astropy import astropy.units as u import marvin.tools from marvin.tools.quantities.spectrum import Spectrum from marvin.utils.general.general import get_drpall_table from marvin.utils.plot.scatter import plot as scatplot from marvin import log from .base import VACMixIn, VACTarget def choose_best_spectrum(par1, par2, conf_thresh=0.1): '''choose optimal HI spectrum based on the following criteria: (1) If both detected and unconfused, choose highest SNR (2) If both detected and both confused, choose lower confusion prob. (3) If both detected and one confused, choose non-confused (4) If one non-confused detection and one non-detection, go with detection (5) If one confused detetion and one non-detection, go with non-detection (6) If niether detected, choose lowest rms par1 and par2 are dictionaries with the following parameters: program - gbt or alfalfa snr - integrated SNR rms - rms noise level conf_prob - confusion probability conf_thresh = maximum confusion probability below which we classify the object as essentially unconfused. Default to 0.1 following (Stark+21) ''' programs = [par1['program'],par2['program']] sel_high_snr = np.argmax([par1['snr'],par2['snr']]) sel_low_rms = np.argmin([par1['rms'],par2['rms']]) sel_low_conf = np.argmin([par1['conf_prob'],par2['conf_prob']]) #both detected if (par1['snr'] > 0) & (par2['snr'] > 0): if (par1['conf_prob'] <= conf_thresh) & (par2['conf_prob'] <= conf_thresh): pick = sel_high_snr elif (par1['conf_prob'] <= conf_thresh) & (par2['conf_prob'] > conf_thresh): pick = 0 elif (par1['conf_prob'] > conf_thresh) & (par2['conf_prob'] <= conf_thresh): pick = 1 elif (par1['conf_prob'] > conf_thresh) & (par2['conf_prob'] > conf_thresh): pick = sel_low_conf #both nondetected elif (par1['snr'] <= 0) & (par2['snr'] <= 0): pick = sel_low_rms #one detected elif (par1['snr'] > 0) & (par2['snr'] <= 0): if par1['conf_prob'] < conf_thresh: pick=0 else: pick=1 elif (par1['snr'] <= 0) & (par2['snr'] > 0): if par2['conf_prob'] < conf_thresh: pick=1 else: pick=0 return programs[pick] class HIVAC(VACMixIn): """Provides access to the MaNGA-HI VAC. VAC name: HI URL: https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=hi-manga-data-release-1 Description: Returns HI summary data and spectra Authors: David Stark and Karen Masters """ # Required parameters name = 'HI' description = 'Returns HI summary data and spectra' version = {'MPL-7': 'v1_0_1', 'DR15': 'v1_0_1', 'DR16': 'v1_0_2', 'DR17': 'v2_0_1', 'MPL-11': 'v2_0_1'} display_name = 'HI' url = 'https://www.sdss.org/dr17/data_access/value-added-catalogs/?vac_id=hi-manga-data-release-1' # optional Marvin Tools to attach your vac to include = (marvin.tools.cube.Cube, marvin.tools.maps.Maps, marvin.tools.modelcube.ModelCube) # optional methods to attach to your main VAC tool in ~marvin.tools.vacs.VACs add_methods = ['plot_mass_fraction'] # Required method def set_summary_file(self, release): ''' Sets the path to the HI summary file ''' # define the variables to build a unique path to your VAC file self.path_params = {'ver': self.version[release], 'type': 'all', 'program': 'GBT16A_095'} # get_path returns False if the files do not exist locally self.summary_file = self.get_path("mangahisum", path_params=self.path_params) def set_program(self,plateifu): # download the vac from the SAS if it does not already exist locally if not self.file_exists(self.summary_file): self.summary_file = self.download_vac('mangahisum', path_params=self.path_params) # Find all entries in summary file with this plate-ifu. # Need the full summary file data. # Find best entry between GBT/ALFALFA based on dept and confusion. # Then update self.path_params['program'] with alfalfa or gbt. summary = HITarget(plateifu, vacfile=self.summary_file)._data galinfo = summary[summary['plateifu'] == plateifu] if len(galinfo) == 1 and galinfo['session']=='ALFALFA': program = 'alfalfa' elif len(galinfo) in [0, 1]: # if no entry found or session is GBT, default program to gbt program = 'gbt' else: par1 = {'program': 'gbt','snr': 0.,'rms': galinfo[0]['rms'], 'conf_prob': galinfo[0]['conf_prob']} par2 = {'program': 'gbt','snr': 0.,'rms': galinfo[1]['rms'], 'conf_prob': galinfo[1]['conf_prob']} if galinfo[0]['session']=='ALFALFA': par1['program'] = 'alfalfa' if galinfo[1]['session']=='ALFALFA': par2['program'] = 'alfalfa' if galinfo[0]['fhi'] > 0: par1['snr'] = galinfo[0]['fhi']/galinfo[0]['efhi'] if galinfo[1]['fhi'] > 0: par2['snr'] = galinfo[1]['fhi']/galinfo[1]['efhi'] program = choose_best_spectrum(par1,par2) log.info('Using HI data from {0}'.format(program)) # get path to ancillary VAC file for target HI spectra self.update_path_params({'program':program}) # Required method def get_target(self, parent_object): ''' Accesses VAC data for a specific target from a Marvin Tool object ''' # get any parameters you need from the parent object plateifu = parent_object.plateifu self.update_path_params({'plateifu': plateifu}) if parent_object.release in ['DR17', 'MPL-11']: self.set_program(plateifu) specfile = self.get_path('mangahispectra', path_params=self.path_params) # create container for more complex return data hidata = HITarget(plateifu, vacfile=self.summary_file, specfile=specfile) # get the spectral data for that row if it exists if hidata._indata and not self.file_exists(specfile): hidata._specfile = self.download_vac('mangahispectra', path_params=self.path_params) return hidata class HITarget(VACTarget): ''' A customized target class to also display HI spectra This class handles data from both the HI summary file and the individual spectral files. Row data from the summary file for the given target is returned via the `data` property. Spectral data can be displayed via the the `plot_spectrum` method. Parameters: targetid (str): The plateifu or mangaid designation vacfile (str): The path of the VAC summary file specfile (str): The path to the HI spectra Attributes: data: The target row data from the main VAC file targetid (str): The target identifier ''' def __init__(self, targetid, vacfile, specfile=None): super(HITarget, self).__init__(targetid, vacfile) self._specfile = specfile self._specdata = None def plot_spectrum(self): ''' Plot the HI spectrum ''' if self._specfile: if not self._specdata: self._specdata = self._get_data(self._specfile) vel = self._specdata['VHI'][0] flux = self._specdata['FHI'][0] spec = Spectrum(flux, unit=u.Jy, wavelength=vel, wavelength_unit=u.km / u.s) ax = spec.plot( ylabel='HI\ Flux\ Density', xlabel='Velocity', title=self.targetid, ytrim='minmax' ) return ax return None # # Functions to become available on your VAC in marvin.tools.vacs.VACs def plot_mass_fraction(vacdata_object): ''' Plot the HI mass fraction Computes and plots the HI mass fraction using the NSA elliptical Petrosian stellar mass from the MaNGA DRPall file. Only plots data for subset of targets in both the HI VAC and the DRPall file. Parameters: vacdata_object (object): The `~.VACDataClass` instance of the HI VAC Example: >>> from marvin.tools.vacs import VACs >>> v = VACs() >>> hi = v.HI >>> hi.plot_mass_fraction() ''' drpall = get_drpall_table() drpall.add_index('plateifu') data = vacdata_object.data[1].data subset = drpall.loc[data['plateifu']] log_stmass = np.log10(subset['nsa_elpetro_mass']) diff = data['logMHI'] - log_stmass fig, axes = scatplot( log_stmass, diff, with_hist=False, ylim=[-5, 5], xlabel=r'log $M_*$', ylabel=r'log $M_{HI}/M_*$', ) return axes[0]
sdss/marvin
python/marvin/contrib/vacs/hi.py
Python
bsd-3-clause
9,230
from djpcms import sites if sites.settings.CMS_ORM == 'django': from djpcms.core.cmsmodels._django import * elif sites.settings.CMS_ORM == 'stdnet': from djpcms.core.cmsmodels._stdnet import * else: raise NotImplementedError('Objecr Relational Mapper {0} not available for CMS models'.format(sites.settings.CMS_ORM))
strogo/djpcms
djpcms/models.py
Python
bsd-3-clause
354
/* * Copyright (C) 2008, 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "Threading.h" #include <wtf/OwnPtr.h> #include <wtf/PassOwnPtr.h> #include <string.h> namespace WTF { struct NewThreadContext { WTF_MAKE_FAST_ALLOCATED; public: NewThreadContext(ThreadFunction entryPoint, void* data, const char* name) : entryPoint(entryPoint) , data(data) , name(name) { } ThreadFunction entryPoint; void* data; const char* name; Mutex creationMutex; }; static void threadEntryPoint(void* contextData) { NewThreadContext* context = reinterpret_cast<NewThreadContext*>(contextData); // Block until our creating thread has completed any extra setup work, including // establishing ThreadIdentifier. { MutexLocker locker(context->creationMutex); } initializeCurrentThreadInternal(context->name); // Grab the info that we need out of the context, then deallocate it. ThreadFunction entryPoint = context->entryPoint; void* data = context->data; delete context; entryPoint(data); } ThreadIdentifier createThread(ThreadFunction entryPoint, void* data, const char* name) { // Visual Studio has a 31-character limit on thread names. Longer names will // be truncated silently, but we'd like callers to know about the limit. #if !LOG_DISABLED && PLATFORM(WIN) if (name && strlen(name) > 31) LOG_ERROR("Thread name \"%s\" is longer than 31 characters and will be truncated by Visual Studio", name); #endif NewThreadContext* context = new NewThreadContext(entryPoint, data, name); // Prevent the thread body from executing until we've established the thread identifier. MutexLocker locker(context->creationMutex); return createThreadInternal(threadEntryPoint, context, name); } #if PLATFORM(MAC) || PLATFORM(WIN) // For ABI compatibility with Safari on Mac / Windows: Safari uses the private // createThread() and waitForThreadCompletion() functions directly and we need // to keep the old ABI compatibility until it's been rebuilt. typedef void* (*ThreadFunctionWithReturnValue)(void* argument); WTF_EXPORT_PRIVATE ThreadIdentifier createThread(ThreadFunctionWithReturnValue entryPoint, void* data, const char* name); struct ThreadFunctionWithReturnValueInvocation { ThreadFunctionWithReturnValueInvocation(ThreadFunctionWithReturnValue function, void* data) : function(function) , data(data) { } ThreadFunctionWithReturnValue function; void* data; }; static void compatEntryPoint(void* param) { // Balanced by .leakPtr() in createThread. OwnPtr<ThreadFunctionWithReturnValueInvocation> invocation = adoptPtr(static_cast<ThreadFunctionWithReturnValueInvocation*>(param)); invocation->function(invocation->data); } ThreadIdentifier createThread(ThreadFunctionWithReturnValue entryPoint, void* data, const char* name) { auto invocation = createOwned<ThreadFunctionWithReturnValueInvocation>(entryPoint, data); // Balanced by adoptPtr() in compatEntryPoint. return createThread(compatEntryPoint, invocation.leakPtr(), name); } WTF_EXPORT_PRIVATE int waitForThreadCompletion(ThreadIdentifier, void**); int waitForThreadCompletion(ThreadIdentifier threadID, void**) { return waitForThreadCompletion(threadID); } // This function is deprecated but needs to be kept around for backward // compatibility. Use the 3-argument version of createThread above. WTF_EXPORT_PRIVATE ThreadIdentifier createThread(ThreadFunctionWithReturnValue entryPoint, void* data); ThreadIdentifier createThread(ThreadFunctionWithReturnValue entryPoint, void* data) { auto invocation = createOwned<ThreadFunctionWithReturnValueInvocation>(entryPoint, data); // Balanced by adoptPtr() in compatEntryPoint. return createThread(compatEntryPoint, invocation.leakPtr(), 0); } #endif } // namespace WTF
klim-iv/phantomjs-qt5
src/webkit/Source/WTF/wtf/Threading.cpp
C++
bsd-3-clause
5,208
// check that header compiles #include "pyffi/object_models/scope.hpp" int main() { pyffi::object_models::Scope scope; return 0; };
amorilia/pyffi-boost
test/pyffi/object_models/scope_header_test.cpp
C++
bsd-3-clause
140
<!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.6.0_21) on Mon Apr 16 12:29:32 EDT 2012 --> <TITLE> MappingTest </TITLE> <META NAME="date" CONTENT="2012-04-16"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="MappingTest"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= 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=2 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="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</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-files/index-1.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;<A HREF="../../../../../../gov/nih/nci/cbiit/cmts/test/Hl7V2Test.html" title="class in gov.nih.nci.cbiit.cmts.test"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../../gov/nih/nci/cbiit/cmts/test/TestCMTS_API.html" title="class in gov.nih.nci.cbiit.cmts.test"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?gov/nih/nci/cbiit/cmts/test/MappingTest.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="MappingTest.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> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> gov.nih.nci.cbiit.cmts.test</FONT> <BR> Class MappingTest</H2> <PRE> java.lang.Object <IMG SRC="../../../../../../resources/inherit.gif" ALT="extended by "><B>gov.nih.nci.cbiit.cmts.test.MappingTest</B> </PRE> <HR> <DL> <DT><PRE>public class <B>MappingTest</B><DT>extends java.lang.Object</DL> </PRE> <P> This class is to test the Mapping functions <P> <P> <DL> <DT><B>Since:</B></DT> <DD>CMTS v1.0</DD> </DL> <HR> <P> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../../gov/nih/nci/cbiit/cmts/test/MappingTest.html#MappingTest()">MappingTest</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../gov/nih/nci/cbiit/cmts/test/MappingTest.html#setUp()">setUp</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../gov/nih/nci/cbiit/cmts/test/MappingTest.html#tearDown()">tearDown</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../gov/nih/nci/cbiit/cmts/test/MappingTest.html#testFilePathRelatize()">testFilePathRelatize</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Test file relative path</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../gov/nih/nci/cbiit/cmts/test/MappingTest.html#testFindNodeById()">testFindNodeById</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;test find node method</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../gov/nih/nci/cbiit/cmts/test/MappingTest.html#testMarshalMapping()">testMarshalMapping</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;test create Mapping from a pair of XSD and marshaling the Mapping</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../gov/nih/nci/cbiit/cmts/test/MappingTest.html#testParseHL7v2XSD()">testParseHL7v2XSD</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;test HL7 v2 XSD parsing and marshaling of the generated Model Object</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../gov/nih/nci/cbiit/cmts/test/MappingTest.html#testParseHL7v3XSD()">testParseHL7v3XSD</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;test HL7 v3 XSD parsing and marshaling of the generated Model Object</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../gov/nih/nci/cbiit/cmts/test/MappingTest.html#testParseXSD()">testParseXSD</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;test XSD parsing and marshaling of the generated Model Object</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../../gov/nih/nci/cbiit/cmts/test/MappingTest.html#testUnmarshalMapping()">testUnmarshalMapping</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;test round trip marshaling and unmarshaling of Mapping</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="MappingTest()"><!-- --></A><H3> MappingTest</H3> <PRE> public <B>MappingTest</B>()</PRE> <DL> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="setUp()"><!-- --></A><H3> setUp</H3> <PRE> public void <B>setUp</B>() throws java.lang.Exception</PRE> <DL> <DD><DL> <DT><B>Throws:</B> <DD><CODE>java.lang.Exception</CODE></DL> </DD> </DL> <HR> <A NAME="tearDown()"><!-- --></A><H3> tearDown</H3> <PRE> public void <B>tearDown</B>() throws java.lang.Exception</PRE> <DL> <DD><DL> <DT><B>Throws:</B> <DD><CODE>java.lang.Exception</CODE></DL> </DD> </DL> <HR> <A NAME="testParseXSD()"><!-- --></A><H3> testParseXSD</H3> <PRE> public void <B>testParseXSD</B>() throws java.lang.Exception</PRE> <DL> <DD>test XSD parsing and marshaling of the generated Model Object <P> <DD><DL> <DT><B>Throws:</B> <DD><CODE>java.lang.Exception</CODE></DL> </DD> </DL> <HR> <A NAME="testParseHL7v2XSD()"><!-- --></A><H3> testParseHL7v2XSD</H3> <PRE> public void <B>testParseHL7v2XSD</B>() throws java.lang.Exception</PRE> <DL> <DD>test HL7 v2 XSD parsing and marshaling of the generated Model Object <P> <DD><DL> <DT><B>Throws:</B> <DD><CODE>java.lang.Exception</CODE></DL> </DD> </DL> <HR> <A NAME="testParseHL7v3XSD()"><!-- --></A><H3> testParseHL7v3XSD</H3> <PRE> public void <B>testParseHL7v3XSD</B>() throws java.lang.Exception</PRE> <DL> <DD>test HL7 v3 XSD parsing and marshaling of the generated Model Object <P> <DD><DL> <DT><B>Throws:</B> <DD><CODE>java.lang.Exception</CODE></DL> </DD> </DL> <HR> <A NAME="testFilePathRelatize()"><!-- --></A><H3> testFilePathRelatize</H3> <PRE> public void <B>testFilePathRelatize</B>()</PRE> <DL> <DD>Test file relative path <P> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="testMarshalMapping()"><!-- --></A><H3> testMarshalMapping</H3> <PRE> public void <B>testMarshalMapping</B>() throws java.lang.Exception</PRE> <DL> <DD>test create Mapping from a pair of XSD and marshaling the Mapping <P> <DD><DL> <DT><B>Throws:</B> <DD><CODE>java.lang.Exception</CODE></DL> </DD> </DL> <HR> <A NAME="testUnmarshalMapping()"><!-- --></A><H3> testUnmarshalMapping</H3> <PRE> public void <B>testUnmarshalMapping</B>() throws java.lang.Exception</PRE> <DL> <DD>test round trip marshaling and unmarshaling of Mapping <P> <DD><DL> <DT><B>Throws:</B> <DD><CODE>java.lang.Exception</CODE></DL> </DD> </DL> <HR> <A NAME="testFindNodeById()"><!-- --></A><H3> testFindNodeById</H3> <PRE> public void <B>testFindNodeById</B>() throws java.lang.Exception</PRE> <DL> <DD>test find node method <P> <DD><DL> <DT><B>Throws:</B> <DD><CODE>java.lang.Exception</CODE></DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <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=2 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="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</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-files/index-1.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;<A HREF="../../../../../../gov/nih/nci/cbiit/cmts/test/Hl7V2Test.html" title="class in gov.nih.nci.cbiit.cmts.test"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../../../../../gov/nih/nci/cbiit/cmts/test/TestCMTS_API.html" title="class in gov.nih.nci.cbiit.cmts.test"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?gov/nih/nci/cbiit/cmts/test/MappingTest.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="MappingTest.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> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;FIELD&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
NCIP/caadapter
software/cmts/doc/javadoc/gov/nih/nci/cbiit/cmts/test/MappingTest.html
HTML
bsd-3-clause
15,848
/*- * Cronyx-Sigma Driver Development Kit. * * Copyright (C) 1998 Cronyx Engineering. * Author: Pavel Novikov, <pavel@inr.net.kiae.su> * * Copyright (C) 1998-2003 Cronyx Engineering. * Author: Roman Kurakin, <rik@cronyx.ru> * * This software is distributed with NO WARRANTIES, not even the implied * warranties for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * Authors grant any other persons or organisations permission to use * or modify this software as long as this message is kept with the software, * all derivative works or modified versions. * * Cronyx Id: cxddk.c,v 1.1.2.2 2003/11/27 14:24:50 rik Exp $ */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: releng/9.3/sys/dev/cx/cxddk.c 139749 2005-01-06 01:43:34Z imp $"); #include <dev/cx/machdep.h> #include <dev/cx/cxddk.h> #include <dev/cx/cxreg.h> #include <dev/cx/cronyxfw.h> #include <dev/cx/csigmafw.h> #define BYTE *(unsigned char*)& /* standard base port set */ static short porttab [] = { 0x200, 0x220, 0x240, 0x260, 0x280, 0x2a0, 0x2c0, 0x2e0, 0x300, 0x320, 0x340, 0x360, 0x380, 0x3a0, 0x3c0, 0x3e0, 0 }; /* * Compute the optimal size of the receive buffer. */ static int cx_compute_buf_len (cx_chan_t *c) { int rbsz; if (c->mode == M_ASYNC) { rbsz = (c->rxbaud + 800 - 1) / 800 * 2; if (rbsz < 4) rbsz = 4; else if (rbsz > DMABUFSZ) rbsz = DMABUFSZ; } else rbsz = DMABUFSZ; return rbsz; } /* * Auto-detect the installed adapters. */ int cx_find (port_t *board_ports) { int i, n; for (i=0, n=0; porttab[i] && n<NBRD; i++) if (cx_probe_board (porttab[i], -1, -1)) board_ports[n++] = porttab[i]; return n; } /* * Initialize the adapter. */ int cx_open_board (cx_board_t *b, int num, port_t port, int irq, int dma) { cx_chan_t *c; if (num >= NBRD || ! cx_probe_board (port, irq, dma)) return 0; /* init callback pointers */ for (c=b->chan; c<b->chan+NCHAN; ++c) { c->call_on_tx = 0; c->call_on_rx = 0; c->call_on_msig = 0; c->call_on_err = 0; } cx_init (b, num, port, irq, dma); /* Loading firmware */ if (! cx_setup_board (b, csigma_fw_data, csigma_fw_len, csigma_fw_tvec)) return 0; return 1; } /* * Shutdown the adapter. */ void cx_close_board (cx_board_t *b) { cx_setup_board (b, 0, 0, 0); /* Reset the controller. */ outb (BCR0(b->port), 0); if (b->chan[8].type || b->chan[12].type) outb (BCR0(b->port+0x10), 0); } /* * Start the channel. */ void cx_start_chan (cx_chan_t *c, cx_buf_t *cb, unsigned long phys) { int command = 0; int mode = 0; int ier = 0; int rbsz; c->overflow = 0; /* Setting up buffers */ if (cb) { c->arbuf = cb->rbuffer[0]; c->brbuf = cb->rbuffer[1]; c->atbuf = cb->tbuffer[0]; c->btbuf = cb->tbuffer[1]; c->arphys = phys + ((char*)c->arbuf - (char*)cb); c->brphys = phys + ((char*)c->brbuf - (char*)cb); c->atphys = phys + ((char*)c->atbuf - (char*)cb); c->btphys = phys + ((char*)c->btbuf - (char*)cb); } /* Set current channel number */ outb (CAR(c->port), c->num & 3); /* set receiver A buffer physical address */ outw (ARBADRU(c->port), (unsigned short) (c->arphys>>16)); outw (ARBADRL(c->port), (unsigned short) c->arphys); /* set receiver B buffer physical address */ outw (BRBADRU(c->port), (unsigned short) (c->brphys>>16)); outw (BRBADRL(c->port), (unsigned short) c->brphys); /* set transmitter A buffer physical address */ outw (ATBADRU(c->port), (unsigned short) (c->atphys>>16)); outw (ATBADRL(c->port), (unsigned short) c->atphys); /* set transmitter B buffer physical address */ outw (BTBADRU(c->port), (unsigned short) (c->btphys>>16)); outw (BTBADRL(c->port), (unsigned short) c->btphys); /* rx */ command |= CCR_ENRX; ier |= IER_RXD; if (c->board->dma) { mode |= CMR_RXDMA; if (c->mode == M_ASYNC) ier |= IER_RET; } /* tx */ command |= CCR_ENTX; ier |= (c->mode == M_ASYNC) ? IER_TXD : (IER_TXD | IER_TXMPTY); if (c->board->dma) mode |= CMR_TXDMA; /* Set mode */ outb (CMR(c->port), mode | (c->mode == M_ASYNC ? CMR_ASYNC : CMR_HDLC)); /* Clear and initialize channel */ cx_cmd (c->port, CCR_CLRCH); cx_cmd (c->port, CCR_INITCH | command); if (c->mode == M_ASYNC) cx_cmd (c->port, CCR_ENTX); /* Start receiver */ rbsz = cx_compute_buf_len(c); outw (ARBCNT(c->port), rbsz); outw (BRBCNT(c->port), rbsz); outw (ARBSTS(c->port), BSTS_OWN24); outw (BRBSTS(c->port), BSTS_OWN24); if (c->mode == M_ASYNC) ier |= IER_MDM; /* Enable interrupts */ outb (IER(c->port), ier); /* Clear DTR and RTS */ cx_set_dtr (c, 0); cx_set_rts (c, 0); } /* * Turn the receiver on/off. */ void cx_enable_receive (cx_chan_t *c, int on) { unsigned char ier; if (cx_receive_enabled(c) && ! on) { outb (CAR(c->port), c->num & 3); if (c->mode == M_ASYNC) { ier = inb (IER(c->port)); outb (IER(c->port), ier & ~ (IER_RXD | IER_RET)); } cx_cmd (c->port, CCR_DISRX); } else if (! cx_receive_enabled(c) && on) { outb (CAR(c->port), c->num & 3); ier = inb (IER(c->port)); if (c->mode == M_ASYNC) outb (IER(c->port), ier | (IER_RXD | IER_RET)); else outb (IER(c->port), ier | IER_RXD); cx_cmd (c->port, CCR_ENRX); } } /* * Turn the transmiter on/off. */ void cx_enable_transmit (cx_chan_t *c, int on) { if (cx_transmit_enabled(c) && ! on) { outb (CAR(c->port), c->num & 3); if (c->mode != M_ASYNC) outb (STCR(c->port), STC_ABORTTX | STC_SNDSPC); cx_cmd (c->port, CCR_DISTX); } else if (! cx_transmit_enabled(c) && on) { outb (CAR(c->port), c->num & 3); cx_cmd (c->port, CCR_ENTX); } } /* * Get channel status. */ int cx_receive_enabled (cx_chan_t *c) { outb (CAR(c->port), c->num & 3); return (inb (CSR(c->port)) & CSRA_RXEN) != 0; } int cx_transmit_enabled (cx_chan_t *c) { outb (CAR(c->port), c->num & 3); return (inb (CSR(c->port)) & CSRA_TXEN) != 0; } unsigned long cx_get_baud (cx_chan_t *c) { return (c->opt.tcor.clk == CLK_EXT) ? 0 : c->txbaud; } int cx_get_loop (cx_chan_t *c) { return c->opt.tcor.llm ? 1 : 0; } int cx_get_nrzi (cx_chan_t *c) { return c->opt.rcor.encod == ENCOD_NRZI; } int cx_get_dpll (cx_chan_t *c) { return c->opt.rcor.dpll ? 1 : 0; } void cx_set_baud (cx_chan_t *c, unsigned long bps) { int clock, period; c->txbaud = c->rxbaud = bps; /* Set current channel number */ outb (CAR(c->port), c->num & 3); if (bps) { if (c->mode == M_ASYNC || c->opt.rcor.dpll || c->opt.tcor.llm) { /* Receive baud - internal */ cx_clock (c->oscfreq, c->rxbaud, &clock, &period); c->opt.rcor.clk = clock; outb (RCOR(c->port), BYTE c->opt.rcor); outb (RBPR(c->port), period); } else { /* Receive baud - external */ c->opt.rcor.clk = CLK_EXT; outb (RCOR(c->port), BYTE c->opt.rcor); outb (RBPR(c->port), 1); } /* Transmit baud - internal */ cx_clock (c->oscfreq, c->txbaud, &clock, &period); c->opt.tcor.clk = clock; c->opt.tcor.ext1x = 0; outb (TBPR(c->port), period); } else if (c->mode != M_ASYNC) { /* External clock - disable local loopback and DPLL */ c->opt.tcor.llm = 0; c->opt.rcor.dpll = 0; /* Transmit baud - external */ c->opt.tcor.ext1x = 1; c->opt.tcor.clk = CLK_EXT; outb (TBPR(c->port), 1); /* Receive baud - external */ c->opt.rcor.clk = CLK_EXT; outb (RCOR(c->port), BYTE c->opt.rcor); outb (RBPR(c->port), 1); } if (c->opt.tcor.llm) outb (COR2(c->port), (BYTE c->hopt.cor2) & ~3); else outb (COR2(c->port), BYTE c->hopt.cor2); outb (TCOR(c->port), BYTE c->opt.tcor); } void cx_set_loop (cx_chan_t *c, int on) { if (! c->txbaud) return; c->opt.tcor.llm = on ? 1 : 0; cx_set_baud (c, c->txbaud); } void cx_set_dpll (cx_chan_t *c, int on) { if (! c->txbaud) return; c->opt.rcor.dpll = on ? 1 : 0; cx_set_baud (c, c->txbaud); } void cx_set_nrzi (cx_chan_t *c, int nrzi) { c->opt.rcor.encod = (nrzi ? ENCOD_NRZI : ENCOD_NRZ); outb (CAR(c->port), c->num & 3); outb (RCOR(c->port), BYTE c->opt.rcor); } static int cx_send (cx_chan_t *c, char *data, int len, void *attachment) { unsigned char *buf; port_t cnt_port, sts_port; void **attp; /* Set the current channel number. */ outb (CAR(c->port), c->num & 3); /* Determine the buffer order. */ if (inb (DMABSTS(c->port)) & DMABSTS_NTBUF) { if (inb (BTBSTS(c->port)) & BSTS_OWN24) { buf = c->atbuf; cnt_port = ATBCNT(c->port); sts_port = ATBSTS(c->port); attp = &c->attach[0]; } else { buf = c->btbuf; cnt_port = BTBCNT(c->port); sts_port = BTBSTS(c->port); attp = &c->attach[1]; } } else { if (inb (ATBSTS(c->port)) & BSTS_OWN24) { buf = c->btbuf; cnt_port = BTBCNT(c->port); sts_port = BTBSTS(c->port); attp = &c->attach[1]; } else { buf = c->atbuf; cnt_port = ATBCNT(c->port); sts_port = ATBSTS(c->port); attp = &c->attach[0]; } } /* Is it busy? */ if (inb (sts_port) & BSTS_OWN24) return -1; memcpy (buf, data, len); *attp = attachment; /* Start transmitter. */ outw (cnt_port, len); outb (sts_port, BSTS_EOFR | BSTS_INTR | BSTS_OWN24); /* Enable TXMPTY interrupt, * to catch the case when the second buffer is empty. */ if (c->mode != M_ASYNC) { if ((inb(ATBSTS(c->port)) & BSTS_OWN24) && (inb(BTBSTS(c->port)) & BSTS_OWN24)) { outb (IER(c->port), IER_RXD | IER_TXD | IER_TXMPTY); } else outb (IER(c->port), IER_RXD | IER_TXD); } return 0; } /* * Number of free buffs */ int cx_buf_free (cx_chan_t *c) { return ! (inb (ATBSTS(c->port)) & BSTS_OWN24) + ! (inb (BTBSTS(c->port)) & BSTS_OWN24); } /* * Send the data packet. */ int cx_send_packet (cx_chan_t *c, char *data, int len, void *attachment) { if (len >= DMABUFSZ) return -2; if (c->mode == M_ASYNC) { static char buf [DMABUFSZ]; char *p, *t = buf; /* Async -- double all nulls. */ for (p=data; p < data+len && t < buf+DMABUFSZ-1; ++p) if ((*t++ = *p) == 0) *t++ = 0; return cx_send (c, buf, t-buf, attachment); } return cx_send (c, data, len, attachment); } static int cx_receive_interrupt (cx_chan_t *c) { unsigned short risr; int len = 0, rbsz; ++c->rintr; risr = inw (RISR(c->port)); /* Compute optimal receiver buffer length */ rbsz = cx_compute_buf_len(c); if (c->mode == M_ASYNC && (risr & RISA_TIMEOUT)) { unsigned long rcbadr = (unsigned short) inw (RCBADRL(c->port)) | (long) inw (RCBADRU(c->port)) << 16; unsigned char *buf = 0; port_t cnt_port = 0, sts_port = 0; if (rcbadr >= c->brphys && rcbadr < c->brphys+DMABUFSZ) { buf = c->brbuf; len = rcbadr - c->brphys; cnt_port = BRBCNT(c->port); sts_port = BRBSTS(c->port); } else if (rcbadr >= c->arphys && rcbadr < c->arphys+DMABUFSZ) { buf = c->arbuf; len = rcbadr - c->arphys; cnt_port = ARBCNT(c->port); sts_port = ARBSTS(c->port); } if (len) { c->ibytes += len; c->received_data = buf; c->received_len = len; /* Restart receiver. */ outw (cnt_port, rbsz); outb (sts_port, BSTS_OWN24); } return (REOI_TERMBUFF); } /* Receive errors. */ if (risr & RIS_OVERRUN) { ++c->ierrs; if (c->call_on_err) c->call_on_err (c, CX_OVERRUN); } else if (c->mode != M_ASYNC && (risr & RISH_CRCERR)) { ++c->ierrs; if (c->call_on_err) c->call_on_err (c, CX_CRC); } else if (c->mode != M_ASYNC && (risr & (RISH_RXABORT | RISH_RESIND))) { ++c->ierrs; if (c->call_on_err) c->call_on_err (c, CX_FRAME); } else if (c->mode == M_ASYNC && (risr & RISA_PARERR)) { ++c->ierrs; if (c->call_on_err) c->call_on_err (c, CX_CRC); } else if (c->mode == M_ASYNC && (risr & RISA_FRERR)) { ++c->ierrs; if (c->call_on_err) c->call_on_err (c, CX_FRAME); } else if (c->mode == M_ASYNC && (risr & RISA_BREAK)) { if (c->call_on_err) c->call_on_err (c, CX_BREAK); } else if (! (risr & RIS_EOBUF)) { ++c->ierrs; } else { /* Handle received data. */ len = (risr & RIS_BB) ? inw(BRBCNT(c->port)) : inw(ARBCNT(c->port)); if (len > DMABUFSZ) { /* Fatal error: actual DMA transfer size * exceeds our buffer size. It could be caused * by incorrectly programmed DMA register or * hardware fault. Possibly, should panic here. */ len = DMABUFSZ; } else if (c->mode != M_ASYNC && ! (risr & RIS_EOFR)) { /* The received frame does not fit in the DMA buffer. * It could be caused by serial lie noise, * or if the peer has too big MTU. */ if (! c->overflow) { if (c->call_on_err) c->call_on_err (c, CX_OVERFLOW); c->overflow = 1; ++c->ierrs; } } else if (! c->overflow) { if (risr & RIS_BB) { c->received_data = c->brbuf; c->received_len = len; } else { c->received_data = c->arbuf; c->received_len = len; } if (c->mode != M_ASYNC) ++c->ipkts; c->ibytes += len; } else c->overflow = 0; } /* Restart receiver. */ if (! (inb (ARBSTS(c->port)) & BSTS_OWN24)) { outw (ARBCNT(c->port), rbsz); outb (ARBSTS(c->port), BSTS_OWN24); } if (! (inb (BRBSTS(c->port)) & BSTS_OWN24)) { outw (BRBCNT(c->port), rbsz); outb (BRBSTS(c->port), BSTS_OWN24); } /* Discard exception characters. */ if ((risr & RISA_SCMASK) && c->aopt.cor2.ixon) return (REOI_DISCEXC); else return (0); } static void cx_transmit_interrupt (cx_chan_t *c) { unsigned char tisr; int len = 0; ++c->tintr; tisr = inb (TISR(c->port)); if (tisr & TIS_UNDERRUN) { /* Transmit underrun error */ if (c->call_on_err) c->call_on_err (c, CX_UNDERRUN); ++c->oerrs; } else if (tisr & (TIS_EOBUF | TIS_TXEMPTY | TIS_TXDATA)) { /* Call processing function */ if (tisr & TIS_BB) { len = inw(BTBCNT(c->port)); if (c->call_on_tx) c->call_on_tx (c, c->attach[1], len); } else { len = inw(ATBCNT(c->port)); if (c->call_on_tx) c->call_on_tx (c, c->attach[0], len); } if (c->mode != M_ASYNC && len != 0) ++c->opkts; c->obytes += len; } /* Enable TXMPTY interrupt, * to catch the case when the second buffer is empty. */ if (c->mode != M_ASYNC) { if ((inb (ATBSTS(c->port)) & BSTS_OWN24) && (inb (BTBSTS(c->port)) & BSTS_OWN24)) { outb (IER(c->port), IER_RXD | IER_TXD | IER_TXMPTY); } else outb (IER(c->port), IER_RXD | IER_TXD); } } void cx_int_handler (cx_board_t *b) { unsigned char livr; cx_chan_t *c; while (! (inw (BSR(b->port)) & BSR_NOINTR)) { /* Enter the interrupt context, using IACK bus cycle. Read the local interrupt vector register. */ livr = inb (IACK(b->port, BRD_INTR_LEVEL)); c = b->chan + (livr>>2 & 0xf); if (c->type == T_NONE) continue; switch (livr & 3) { case LIV_MODEM: /* modem interrupt */ ++c->mintr; if (c->call_on_msig) c->call_on_msig (c); outb (MEOIR(c->port), 0); break; case LIV_EXCEP: /* receive exception */ case LIV_RXDATA: /* receive interrupt */ outb (REOIR(c->port), cx_receive_interrupt (c)); if (c->call_on_rx && c->received_data) { c->call_on_rx (c, c->received_data, c->received_len); c->received_data = 0; } break; case LIV_TXDATA: /* transmit interrupt */ cx_transmit_interrupt (c); outb (TEOIR(c->port), 0); break; } } } /* * Register event processing functions */ void cx_register_transmit (cx_chan_t *c, void (*func) (cx_chan_t *c, void *attachment, int len)) { c->call_on_tx = func; } void cx_register_receive (cx_chan_t *c, void (*func) (cx_chan_t *c, char *data, int len)) { c->call_on_rx = func; } void cx_register_modem (cx_chan_t *c, void (*func) (cx_chan_t *c)) { c->call_on_msig = func; } void cx_register_error (cx_chan_t *c, void (*func) (cx_chan_t *c, int data)) { c->call_on_err = func; } /* * Async protocol functions. */ /* * Enable/disable transmitter. */ void cx_transmitter_ctl (cx_chan_t *c,int start) { outb (CAR(c->port), c->num & 3); cx_cmd (c->port, start ? CCR_ENTX : CCR_DISTX); } /* * Discard all data queued in transmitter. */ void cx_flush_transmit (cx_chan_t *c) { outb (CAR(c->port), c->num & 3); cx_cmd (c->port, CCR_CLRTX); } /* * Send the XON/XOFF flow control symbol. */ void cx_xflow_ctl (cx_chan_t *c, int on) { outb (CAR(c->port), c->num & 3); outb (STCR(c->port), STC_SNDSPC | (on ? STC_SSPC_1 : STC_SSPC_2)); } /* * Send the break signal for a given number of milliseconds. */ void cx_send_break (cx_chan_t *c, int msec) { static unsigned char buf [128]; unsigned char *p; p = buf; *p++ = 0; /* extended transmit command */ *p++ = 0x81; /* send break */ if (msec > 10000) /* max 10 seconds */ msec = 10000; if (msec < 10) /* min 10 msec */ msec = 10; while (msec > 0) { int ms = 250; /* 250 msec */ if (ms > msec) ms = msec; msec -= ms; *p++ = 0; /* extended transmit command */ *p++ = 0x82; /* insert delay */ *p++ = ms; } *p++ = 0; /* extended transmit command */ *p++ = 0x83; /* stop break */ cx_send (c, buf, p-buf, 0); } /* * Set async parameters. */ void cx_set_async_param (cx_chan_t *c, int baud, int bits, int parity, int stop2, int ignpar, int rtscts, int ixon, int ixany, int symstart, int symstop) { int clock, period; cx_cor1_async_t cor1; /* Set character length and parity mode. */ BYTE cor1 = 0; cor1.charlen = bits - 1; cor1.parmode = parity ? PARM_NORMAL : PARM_NOPAR; cor1.parity = parity==1 ? PAR_ODD : PAR_EVEN; cor1.ignpar = ignpar ? 1 : 0; /* Enable/disable hardware CTS. */ c->aopt.cor2.ctsae = rtscts ? 1 : 0; /* Enable extended transmit command mode. * Unfortunately, there is no other method for sending break. */ c->aopt.cor2.etc = 1; /* Enable/disable hardware XON/XOFF. */ c->aopt.cor2.ixon = ixon ? 1 : 0; c->aopt.cor2.ixany = ixany ? 1 : 0; /* Set the number of stop bits. */ if (stop2) c->aopt.cor3.stopb = STOPB_2; else c->aopt.cor3.stopb = STOPB_1; /* Disable/enable passing XON/XOFF chars to the host. */ c->aopt.cor3.scde = ixon ? 1 : 0; c->aopt.cor3.flowct = ixon ? FLOWCC_NOTPASS : FLOWCC_PASS; c->aopt.schr1 = symstart; /* XON */ c->aopt.schr2 = symstop; /* XOFF */ /* Set current channel number. */ outb (CAR(c->port), c->num & 3); /* Set up clock values. */ if (baud) { c->rxbaud = c->txbaud = baud; /* Receiver. */ cx_clock (c->oscfreq, c->rxbaud, &clock, &period); c->opt.rcor.clk = clock; outb (RCOR(c->port), BYTE c->opt.rcor); outb (RBPR(c->port), period); /* Transmitter. */ cx_clock (c->oscfreq, c->txbaud, &clock, &period); c->opt.tcor.clk = clock; c->opt.tcor.ext1x = 0; outb (TCOR(c->port), BYTE c->opt.tcor); outb (TBPR(c->port), period); } outb (COR2(c->port), BYTE c->aopt.cor2); outb (COR3(c->port), BYTE c->aopt.cor3); outb (SCHR1(c->port), c->aopt.schr1); outb (SCHR2(c->port), c->aopt.schr2); if (BYTE c->aopt.cor1 != BYTE cor1) { BYTE c->aopt.cor1 = BYTE cor1; outb (COR1(c->port), BYTE c->aopt.cor1); /* Any change to COR1 require reinitialization. */ /* Unfortunately, it may cause transmitter glitches... */ cx_cmd (c->port, CCR_INITCH); } } /* * Set mode: M_ASYNC or M_HDLC. * Both receiver and transmitter are disabled. */ int cx_set_mode (cx_chan_t *c, int mode) { if (mode == M_HDLC) { if (c->type == T_ASYNC) return -1; if (c->mode == M_HDLC) return 0; c->mode = M_HDLC; } else if (mode == M_ASYNC) { if (c->type == T_SYNC_RS232 || c->type == T_SYNC_V35 || c->type == T_SYNC_RS449) return -1; if (c->mode == M_ASYNC) return 0; c->mode = M_ASYNC; c->opt.tcor.ext1x = 0; c->opt.tcor.llm = 0; c->opt.rcor.dpll = 0; c->opt.rcor.encod = ENCOD_NRZ; if (! c->txbaud || ! c->rxbaud) c->txbaud = c->rxbaud = 9600; } else return -1; cx_setup_chan (c); cx_start_chan (c, 0, 0); cx_enable_receive (c, 0); cx_enable_transmit (c, 0); return 0; } /* * Set port type for old models of Sigma */ void cx_set_port (cx_chan_t *c, int iftype) { if (c->board->type == B_SIGMA_XXX) { switch (c->num) { case 0: if ((c->board->if0type != 0) == (iftype != 0)) return; c->board->if0type = iftype; c->board->bcr0 &= ~BCR0_UMASK; if (c->board->if0type && (c->type==T_UNIV_RS449 || c->type==T_UNIV_V35)) c->board->bcr0 |= BCR0_UI_RS449; outb (BCR0(c->board->port), c->board->bcr0); break; case 8: if ((c->board->if8type != 0) == (iftype != 0)) return; c->board->if8type = iftype; c->board->bcr0b &= ~BCR0_UMASK; if (c->board->if8type && (c->type==T_UNIV_RS449 || c->type==T_UNIV_V35)) c->board->bcr0b |= BCR0_UI_RS449; outb (BCR0(c->board->port+0x10), c->board->bcr0b); break; } } } /* * Get port type for old models of Sigma * -1 Fixed port type or auto detect * 0 RS232 * 1 V35 * 2 RS449 */ int cx_get_port (cx_chan_t *c) { int iftype; if (c->board->type == B_SIGMA_XXX) { switch (c->num) { case 0: iftype = c->board->if0type; break; case 8: iftype = c->board->if8type; break; default: return -1; } if (iftype) switch (c->type) { case T_UNIV_V35: return 1; break; case T_UNIV_RS449: return 2; break; default: return -1; break; } else return 0; } else return -1; } void cx_intr_off (cx_board_t *b) { outb (BCR0(b->port), b->bcr0 & ~BCR0_IRQ_MASK); if (b->chan[8].port || b->chan[12].port) outb (BCR0(b->port+0x10), b->bcr0b & ~BCR0_IRQ_MASK); } void cx_intr_on (cx_board_t *b) { outb (BCR0(b->port), b->bcr0); if (b->chan[8].port || b->chan[12].port) outb (BCR0(b->port+0x10), b->bcr0b); } int cx_checkintr (cx_board_t *b) { return (!(inw (BSR(b->port)) & BSR_NOINTR)); }
dcui/FreeBSD-9.3_kernel
sys/dev/cx/cxddk.c
C
bsd-3-clause
21,268