file_name
large_stringlengths 4
140
| prefix
large_stringlengths 0
39k
| suffix
large_stringlengths 0
36.1k
| middle
large_stringlengths 0
29.4k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
property_client.py
|
# This code is licensed under the MIT License (see LICENSE file for details)
import collections
import threading
import traceback
import zmq
from ..util import trie
class PropertyClient(threading.Thread):
"""A client for receiving property updates in a background thread.
The background thread is automatically started when this object is constructed.
To stop the thread, set the 'running' attribute to False.
"""
def __init__(self, daemon=True):
# properties is a local copy of tracked properties, in case that's useful
self.properties = {}
# callbacks is a dict mapping property names to lists of callbacks
self.callbacks = collections.defaultdict(set)
# prefix_callbacks is a trie used to match property names to prefixes
# which were registered for "wildcard" callbacks.
self.prefix_callbacks = trie.trie()
super().__init__(name='PropertyClient', daemon=daemon)
self.start()
def subscribe_from(self, other):
"""Copy subscriptions from other PropertyClient"""
for property_name, callbacks in other.callbacks.items():
for callback, valueonly in callbacks:
self.subscribe(property_name, callback, valueonly)
for property_prefix, callbacks in other.prefix_callbacks.items():
for callback, valueonly in callbacks:
self.subscribe_prefix(property_prefix, callback, valueonly)
def run(self):
"""Thread target: do not call directly."""
self.running = True
while True:
property_name, value = self._receive_update()
self.properties[property_name] = value
for callbacks in [self.callbacks[property_name]] + list(self.prefix_callbacks.values(property_name)):
for callback, valueonly in callbacks:
try:
if valueonly:
|
else:
callback(property_name, value)
except Exception as e:
print('Caught exception in PropertyClient callback:')
traceback.print_exception(type(e), e, e.__traceback__)
def stop(self):
self.running = False
self.join()
def subscribe(self, property_name, callback, valueonly=False):
"""Register a callback to be called any time the named property is updated.
If valueonly is True, the callback will be called as: callback(new_value);
if valueonly is False, it will be called as callback(property_name, new_value).
Multiple callbacks can be registered for a single property_name.
"""
self.callbacks[property_name].add((callback, valueonly))
def unsubscribe(self, property_name, callback, valueonly=False):
"""Unregister an exactly matching, previously registered callback. If
the same callback function is registered multiple times with identical
property_name and valueonly parameters, only one registration is removed."""
if property_name is None:
raise ValueError('property_name parameter must not be None.')
try:
callbacks = self.callbacks[property_name]
callbacks.remove((callback, valueonly))
except KeyError:
raise KeyError('No matching subscription found for property name "{}".'.format(property_name)) from None
if not callbacks:
del self.callbacks[property_name]
def subscribe_prefix(self, property_prefix, callback):
"""Register a callback to be called any time a named property which is
prefixed by the property_prefix parameter is updated. The callback is
called as callback(property_name, new_value).
Example: if property_prefix is 'camera.', then the callback will be called
when 'camera.foo' or 'camera.bar' or any such property name is updated.
An empty prefix ('') will match everything.
Multiple callbacks can be registered for a single property_prefix.
"""
if property_prefix not in self.prefix_callbacks:
self.prefix_callbacks[property_prefix] = set()
self.prefix_callbacks[property_prefix].add((callback, False))
def unsubscribe_prefix(self, property_prefix, callback):
"""Unregister an exactly matching, previously registered callback. If
the same callback function is registered multiple times with identical
property_prefix parameters, only one registration is removed."""
if property_prefix is None:
raise ValueError('property_prefix parameter must not be None.')
try:
callbacks = self.prefix_callbacks[property_prefix]
callbacks.remove((callback, False))
except KeyError:
raise KeyError('No matching subscription found for property name "{}".'.format(property_prefix))
if not callbacks:
del self.prefix_callbacks[property_prefix]
def _receive_update(self):
"""Receive an update from the server, or raise an error if self.running
goes False."""
raise NotImplementedError()
class ZMQClient(PropertyClient):
def __init__(self, addr, heartbeat_sec=None, context=None, daemon=True):
"""PropertyClient subclass that uses ZeroMQ PUB/SUB to receive out updates.
Parameters:
addr: a string ZeroMQ port identifier, like 'tcp://127.0.0.1:5555'.
context: a ZeroMQ context to share, if one already exists.
daemon: exit the client when the foreground thread exits.
"""
self.context = context if context is not None else zmq.Context()
self.addr = addr
self.heartbeat_sec = heartbeat_sec
self.connected = threading.Event()
super().__init__(daemon)
def run(self):
self._connect()
try:
super().run()
finally:
self.socket.close()
def reconnect(self):
self.connected.clear()
self.connected.wait()
def _connect(self):
self.socket = self.context.socket(zmq.SUB)
self.socket.RCVTIMEO = 0 # we use poll to determine whether there's data to receive, so we don't want to wait on recv
self.socket.LINGER = 0
if self.heartbeat_sec is not None:
heartbeat_ms = self.heartbeat_sec * 1000
self.socket.HEARTBEAT_IVL = heartbeat_ms
self.socket.HEARTBEAT_TIMEOUT = heartbeat_ms * 2
self.socket.HEARTBEAT_TTL = heartbeat_ms * 2
self.socket.connect(self.addr)
for property_name in list(self.callbacks) + list(self.prefix_callbacks):
self.socket.setsockopt_string(zmq.SUBSCRIBE, property_name)
self.connected.set()
def subscribe(self, property_name, callback, valueonly=False):
self.connected.wait()
self.socket.subscribe(property_name)
super().subscribe(property_name, callback, valueonly)
subscribe.__doc__ = PropertyClient.subscribe.__doc__
def unsubscribe(self, property_name, callback, valueonly=False):
super().unsubscribe(property_name, callback, valueonly)
self.connected.wait()
self.socket.unsubscribe(property_name)
unsubscribe.__doc__ = PropertyClient.unsubscribe.__doc__
def subscribe_prefix(self, property_prefix, callback):
self.connected.wait()
self.socket.subscribe(property_prefix)
super().subscribe_prefix(property_prefix, callback)
subscribe_prefix.__doc__ = PropertyClient.subscribe_prefix.__doc__
def unsubscribe_prefix(self, property_prefix, callback):
super().unsubscribe_prefix(property_prefix, callback)
self.connected.wait()
self.socket.unsubscribe(property_prefix)
unsubscribe_prefix.__doc__ = PropertyClient.unsubscribe_prefix.__doc__
def _receive_update(self):
while not self.socket.poll(500): # 500 ms wait before checking self.running again
if not self.running:
raise RuntimeError()
if not self.connected.is_set():
# reconnect was requested
self.socket.close()
self._connect()
# poll returned true: socket has data to recv
property_name = self.socket.recv_string()
assert(self.socket.getsockopt(zmq.RCVMORE))
value = self.socket.recv_json()
return property_name, value
|
callback(value)
|
conditional_block
|
property_client.py
|
# This code is licensed under the MIT License (see LICENSE file for details)
import collections
import threading
import traceback
import zmq
from ..util import trie
class PropertyClient(threading.Thread):
"""A client for receiving property updates in a background thread.
The background thread is automatically started when this object is constructed.
To stop the thread, set the 'running' attribute to False.
"""
def __init__(self, daemon=True):
# properties is a local copy of tracked properties, in case that's useful
self.properties = {}
# callbacks is a dict mapping property names to lists of callbacks
self.callbacks = collections.defaultdict(set)
# prefix_callbacks is a trie used to match property names to prefixes
# which were registered for "wildcard" callbacks.
self.prefix_callbacks = trie.trie()
super().__init__(name='PropertyClient', daemon=daemon)
self.start()
def subscribe_from(self, other):
"""Copy subscriptions from other PropertyClient"""
for property_name, callbacks in other.callbacks.items():
for callback, valueonly in callbacks:
self.subscribe(property_name, callback, valueonly)
for property_prefix, callbacks in other.prefix_callbacks.items():
for callback, valueonly in callbacks:
self.subscribe_prefix(property_prefix, callback, valueonly)
def run(self):
"""Thread target: do not call directly."""
self.running = True
while True:
property_name, value = self._receive_update()
self.properties[property_name] = value
for callbacks in [self.callbacks[property_name]] + list(self.prefix_callbacks.values(property_name)):
for callback, valueonly in callbacks:
try:
if valueonly:
callback(value)
else:
callback(property_name, value)
except Exception as e:
print('Caught exception in PropertyClient callback:')
traceback.print_exception(type(e), e, e.__traceback__)
def stop(self):
self.running = False
self.join()
def subscribe(self, property_name, callback, valueonly=False):
"""Register a callback to be called any time the named property is updated.
If valueonly is True, the callback will be called as: callback(new_value);
if valueonly is False, it will be called as callback(property_name, new_value).
Multiple callbacks can be registered for a single property_name.
"""
self.callbacks[property_name].add((callback, valueonly))
def unsubscribe(self, property_name, callback, valueonly=False):
"""Unregister an exactly matching, previously registered callback. If
the same callback function is registered multiple times with identical
property_name and valueonly parameters, only one registration is removed."""
if property_name is None:
raise ValueError('property_name parameter must not be None.')
try:
callbacks = self.callbacks[property_name]
callbacks.remove((callback, valueonly))
except KeyError:
raise KeyError('No matching subscription found for property name "{}".'.format(property_name)) from None
if not callbacks:
del self.callbacks[property_name]
def subscribe_prefix(self, property_prefix, callback):
"""Register a callback to be called any time a named property which is
prefixed by the property_prefix parameter is updated. The callback is
called as callback(property_name, new_value).
Example: if property_prefix is 'camera.', then the callback will be called
when 'camera.foo' or 'camera.bar' or any such property name is updated.
An empty prefix ('') will match everything.
Multiple callbacks can be registered for a single property_prefix.
"""
if property_prefix not in self.prefix_callbacks:
self.prefix_callbacks[property_prefix] = set()
self.prefix_callbacks[property_prefix].add((callback, False))
def unsubscribe_prefix(self, property_prefix, callback):
"""Unregister an exactly matching, previously registered callback. If
the same callback function is registered multiple times with identical
property_prefix parameters, only one registration is removed."""
if property_prefix is None:
raise ValueError('property_prefix parameter must not be None.')
try:
callbacks = self.prefix_callbacks[property_prefix]
callbacks.remove((callback, False))
except KeyError:
raise KeyError('No matching subscription found for property name "{}".'.format(property_prefix))
if not callbacks:
del self.prefix_callbacks[property_prefix]
def _receive_update(self):
"""Receive an update from the server, or raise an error if self.running
goes False."""
raise NotImplementedError()
class ZMQClient(PropertyClient):
def __init__(self, addr, heartbeat_sec=None, context=None, daemon=True):
"""PropertyClient subclass that uses ZeroMQ PUB/SUB to receive out updates.
Parameters:
addr: a string ZeroMQ port identifier, like 'tcp://127.0.0.1:5555'.
context: a ZeroMQ context to share, if one already exists.
daemon: exit the client when the foreground thread exits.
"""
self.context = context if context is not None else zmq.Context()
self.addr = addr
self.heartbeat_sec = heartbeat_sec
self.connected = threading.Event()
super().__init__(daemon)
def run(self):
self._connect()
try:
super().run()
finally:
self.socket.close()
def reconnect(self):
self.connected.clear()
self.connected.wait()
def _connect(self):
self.socket = self.context.socket(zmq.SUB)
self.socket.RCVTIMEO = 0 # we use poll to determine whether there's data to receive, so we don't want to wait on recv
self.socket.LINGER = 0
if self.heartbeat_sec is not None:
heartbeat_ms = self.heartbeat_sec * 1000
self.socket.HEARTBEAT_IVL = heartbeat_ms
self.socket.HEARTBEAT_TIMEOUT = heartbeat_ms * 2
self.socket.HEARTBEAT_TTL = heartbeat_ms * 2
self.socket.connect(self.addr)
for property_name in list(self.callbacks) + list(self.prefix_callbacks):
self.socket.setsockopt_string(zmq.SUBSCRIBE, property_name)
self.connected.set()
def subscribe(self, property_name, callback, valueonly=False):
self.connected.wait()
self.socket.subscribe(property_name)
super().subscribe(property_name, callback, valueonly)
subscribe.__doc__ = PropertyClient.subscribe.__doc__
def unsubscribe(self, property_name, callback, valueonly=False):
super().unsubscribe(property_name, callback, valueonly)
self.connected.wait()
self.socket.unsubscribe(property_name)
unsubscribe.__doc__ = PropertyClient.unsubscribe.__doc__
def subscribe_prefix(self, property_prefix, callback):
|
subscribe_prefix.__doc__ = PropertyClient.subscribe_prefix.__doc__
def unsubscribe_prefix(self, property_prefix, callback):
super().unsubscribe_prefix(property_prefix, callback)
self.connected.wait()
self.socket.unsubscribe(property_prefix)
unsubscribe_prefix.__doc__ = PropertyClient.unsubscribe_prefix.__doc__
def _receive_update(self):
while not self.socket.poll(500): # 500 ms wait before checking self.running again
if not self.running:
raise RuntimeError()
if not self.connected.is_set():
# reconnect was requested
self.socket.close()
self._connect()
# poll returned true: socket has data to recv
property_name = self.socket.recv_string()
assert(self.socket.getsockopt(zmq.RCVMORE))
value = self.socket.recv_json()
return property_name, value
|
self.connected.wait()
self.socket.subscribe(property_prefix)
super().subscribe_prefix(property_prefix, callback)
|
identifier_body
|
property_client.py
|
# This code is licensed under the MIT License (see LICENSE file for details)
import collections
import threading
import traceback
import zmq
from ..util import trie
class PropertyClient(threading.Thread):
"""A client for receiving property updates in a background thread.
The background thread is automatically started when this object is constructed.
To stop the thread, set the 'running' attribute to False.
"""
def __init__(self, daemon=True):
# properties is a local copy of tracked properties, in case that's useful
self.properties = {}
# callbacks is a dict mapping property names to lists of callbacks
self.callbacks = collections.defaultdict(set)
# prefix_callbacks is a trie used to match property names to prefixes
# which were registered for "wildcard" callbacks.
self.prefix_callbacks = trie.trie()
super().__init__(name='PropertyClient', daemon=daemon)
self.start()
def subscribe_from(self, other):
"""Copy subscriptions from other PropertyClient"""
for property_name, callbacks in other.callbacks.items():
for callback, valueonly in callbacks:
self.subscribe(property_name, callback, valueonly)
|
def run(self):
"""Thread target: do not call directly."""
self.running = True
while True:
property_name, value = self._receive_update()
self.properties[property_name] = value
for callbacks in [self.callbacks[property_name]] + list(self.prefix_callbacks.values(property_name)):
for callback, valueonly in callbacks:
try:
if valueonly:
callback(value)
else:
callback(property_name, value)
except Exception as e:
print('Caught exception in PropertyClient callback:')
traceback.print_exception(type(e), e, e.__traceback__)
def stop(self):
self.running = False
self.join()
def subscribe(self, property_name, callback, valueonly=False):
"""Register a callback to be called any time the named property is updated.
If valueonly is True, the callback will be called as: callback(new_value);
if valueonly is False, it will be called as callback(property_name, new_value).
Multiple callbacks can be registered for a single property_name.
"""
self.callbacks[property_name].add((callback, valueonly))
def unsubscribe(self, property_name, callback, valueonly=False):
"""Unregister an exactly matching, previously registered callback. If
the same callback function is registered multiple times with identical
property_name and valueonly parameters, only one registration is removed."""
if property_name is None:
raise ValueError('property_name parameter must not be None.')
try:
callbacks = self.callbacks[property_name]
callbacks.remove((callback, valueonly))
except KeyError:
raise KeyError('No matching subscription found for property name "{}".'.format(property_name)) from None
if not callbacks:
del self.callbacks[property_name]
def subscribe_prefix(self, property_prefix, callback):
"""Register a callback to be called any time a named property which is
prefixed by the property_prefix parameter is updated. The callback is
called as callback(property_name, new_value).
Example: if property_prefix is 'camera.', then the callback will be called
when 'camera.foo' or 'camera.bar' or any such property name is updated.
An empty prefix ('') will match everything.
Multiple callbacks can be registered for a single property_prefix.
"""
if property_prefix not in self.prefix_callbacks:
self.prefix_callbacks[property_prefix] = set()
self.prefix_callbacks[property_prefix].add((callback, False))
def unsubscribe_prefix(self, property_prefix, callback):
"""Unregister an exactly matching, previously registered callback. If
the same callback function is registered multiple times with identical
property_prefix parameters, only one registration is removed."""
if property_prefix is None:
raise ValueError('property_prefix parameter must not be None.')
try:
callbacks = self.prefix_callbacks[property_prefix]
callbacks.remove((callback, False))
except KeyError:
raise KeyError('No matching subscription found for property name "{}".'.format(property_prefix))
if not callbacks:
del self.prefix_callbacks[property_prefix]
def _receive_update(self):
"""Receive an update from the server, or raise an error if self.running
goes False."""
raise NotImplementedError()
class ZMQClient(PropertyClient):
def __init__(self, addr, heartbeat_sec=None, context=None, daemon=True):
"""PropertyClient subclass that uses ZeroMQ PUB/SUB to receive out updates.
Parameters:
addr: a string ZeroMQ port identifier, like 'tcp://127.0.0.1:5555'.
context: a ZeroMQ context to share, if one already exists.
daemon: exit the client when the foreground thread exits.
"""
self.context = context if context is not None else zmq.Context()
self.addr = addr
self.heartbeat_sec = heartbeat_sec
self.connected = threading.Event()
super().__init__(daemon)
def run(self):
self._connect()
try:
super().run()
finally:
self.socket.close()
def reconnect(self):
self.connected.clear()
self.connected.wait()
def _connect(self):
self.socket = self.context.socket(zmq.SUB)
self.socket.RCVTIMEO = 0 # we use poll to determine whether there's data to receive, so we don't want to wait on recv
self.socket.LINGER = 0
if self.heartbeat_sec is not None:
heartbeat_ms = self.heartbeat_sec * 1000
self.socket.HEARTBEAT_IVL = heartbeat_ms
self.socket.HEARTBEAT_TIMEOUT = heartbeat_ms * 2
self.socket.HEARTBEAT_TTL = heartbeat_ms * 2
self.socket.connect(self.addr)
for property_name in list(self.callbacks) + list(self.prefix_callbacks):
self.socket.setsockopt_string(zmq.SUBSCRIBE, property_name)
self.connected.set()
def subscribe(self, property_name, callback, valueonly=False):
self.connected.wait()
self.socket.subscribe(property_name)
super().subscribe(property_name, callback, valueonly)
subscribe.__doc__ = PropertyClient.subscribe.__doc__
def unsubscribe(self, property_name, callback, valueonly=False):
super().unsubscribe(property_name, callback, valueonly)
self.connected.wait()
self.socket.unsubscribe(property_name)
unsubscribe.__doc__ = PropertyClient.unsubscribe.__doc__
def subscribe_prefix(self, property_prefix, callback):
self.connected.wait()
self.socket.subscribe(property_prefix)
super().subscribe_prefix(property_prefix, callback)
subscribe_prefix.__doc__ = PropertyClient.subscribe_prefix.__doc__
def unsubscribe_prefix(self, property_prefix, callback):
super().unsubscribe_prefix(property_prefix, callback)
self.connected.wait()
self.socket.unsubscribe(property_prefix)
unsubscribe_prefix.__doc__ = PropertyClient.unsubscribe_prefix.__doc__
def _receive_update(self):
while not self.socket.poll(500): # 500 ms wait before checking self.running again
if not self.running:
raise RuntimeError()
if not self.connected.is_set():
# reconnect was requested
self.socket.close()
self._connect()
# poll returned true: socket has data to recv
property_name = self.socket.recv_string()
assert(self.socket.getsockopt(zmq.RCVMORE))
value = self.socket.recv_json()
return property_name, value
|
for property_prefix, callbacks in other.prefix_callbacks.items():
for callback, valueonly in callbacks:
self.subscribe_prefix(property_prefix, callback, valueonly)
|
random_line_split
|
property_client.py
|
# This code is licensed under the MIT License (see LICENSE file for details)
import collections
import threading
import traceback
import zmq
from ..util import trie
class PropertyClient(threading.Thread):
"""A client for receiving property updates in a background thread.
The background thread is automatically started when this object is constructed.
To stop the thread, set the 'running' attribute to False.
"""
def __init__(self, daemon=True):
# properties is a local copy of tracked properties, in case that's useful
self.properties = {}
# callbacks is a dict mapping property names to lists of callbacks
self.callbacks = collections.defaultdict(set)
# prefix_callbacks is a trie used to match property names to prefixes
# which were registered for "wildcard" callbacks.
self.prefix_callbacks = trie.trie()
super().__init__(name='PropertyClient', daemon=daemon)
self.start()
def subscribe_from(self, other):
"""Copy subscriptions from other PropertyClient"""
for property_name, callbacks in other.callbacks.items():
for callback, valueonly in callbacks:
self.subscribe(property_name, callback, valueonly)
for property_prefix, callbacks in other.prefix_callbacks.items():
for callback, valueonly in callbacks:
self.subscribe_prefix(property_prefix, callback, valueonly)
def run(self):
"""Thread target: do not call directly."""
self.running = True
while True:
property_name, value = self._receive_update()
self.properties[property_name] = value
for callbacks in [self.callbacks[property_name]] + list(self.prefix_callbacks.values(property_name)):
for callback, valueonly in callbacks:
try:
if valueonly:
callback(value)
else:
callback(property_name, value)
except Exception as e:
print('Caught exception in PropertyClient callback:')
traceback.print_exception(type(e), e, e.__traceback__)
def stop(self):
self.running = False
self.join()
def subscribe(self, property_name, callback, valueonly=False):
"""Register a callback to be called any time the named property is updated.
If valueonly is True, the callback will be called as: callback(new_value);
if valueonly is False, it will be called as callback(property_name, new_value).
Multiple callbacks can be registered for a single property_name.
"""
self.callbacks[property_name].add((callback, valueonly))
def unsubscribe(self, property_name, callback, valueonly=False):
"""Unregister an exactly matching, previously registered callback. If
the same callback function is registered multiple times with identical
property_name and valueonly parameters, only one registration is removed."""
if property_name is None:
raise ValueError('property_name parameter must not be None.')
try:
callbacks = self.callbacks[property_name]
callbacks.remove((callback, valueonly))
except KeyError:
raise KeyError('No matching subscription found for property name "{}".'.format(property_name)) from None
if not callbacks:
del self.callbacks[property_name]
def subscribe_prefix(self, property_prefix, callback):
"""Register a callback to be called any time a named property which is
prefixed by the property_prefix parameter is updated. The callback is
called as callback(property_name, new_value).
Example: if property_prefix is 'camera.', then the callback will be called
when 'camera.foo' or 'camera.bar' or any such property name is updated.
An empty prefix ('') will match everything.
Multiple callbacks can be registered for a single property_prefix.
"""
if property_prefix not in self.prefix_callbacks:
self.prefix_callbacks[property_prefix] = set()
self.prefix_callbacks[property_prefix].add((callback, False))
def
|
(self, property_prefix, callback):
"""Unregister an exactly matching, previously registered callback. If
the same callback function is registered multiple times with identical
property_prefix parameters, only one registration is removed."""
if property_prefix is None:
raise ValueError('property_prefix parameter must not be None.')
try:
callbacks = self.prefix_callbacks[property_prefix]
callbacks.remove((callback, False))
except KeyError:
raise KeyError('No matching subscription found for property name "{}".'.format(property_prefix))
if not callbacks:
del self.prefix_callbacks[property_prefix]
def _receive_update(self):
"""Receive an update from the server, or raise an error if self.running
goes False."""
raise NotImplementedError()
class ZMQClient(PropertyClient):
def __init__(self, addr, heartbeat_sec=None, context=None, daemon=True):
"""PropertyClient subclass that uses ZeroMQ PUB/SUB to receive out updates.
Parameters:
addr: a string ZeroMQ port identifier, like 'tcp://127.0.0.1:5555'.
context: a ZeroMQ context to share, if one already exists.
daemon: exit the client when the foreground thread exits.
"""
self.context = context if context is not None else zmq.Context()
self.addr = addr
self.heartbeat_sec = heartbeat_sec
self.connected = threading.Event()
super().__init__(daemon)
def run(self):
self._connect()
try:
super().run()
finally:
self.socket.close()
def reconnect(self):
self.connected.clear()
self.connected.wait()
def _connect(self):
self.socket = self.context.socket(zmq.SUB)
self.socket.RCVTIMEO = 0 # we use poll to determine whether there's data to receive, so we don't want to wait on recv
self.socket.LINGER = 0
if self.heartbeat_sec is not None:
heartbeat_ms = self.heartbeat_sec * 1000
self.socket.HEARTBEAT_IVL = heartbeat_ms
self.socket.HEARTBEAT_TIMEOUT = heartbeat_ms * 2
self.socket.HEARTBEAT_TTL = heartbeat_ms * 2
self.socket.connect(self.addr)
for property_name in list(self.callbacks) + list(self.prefix_callbacks):
self.socket.setsockopt_string(zmq.SUBSCRIBE, property_name)
self.connected.set()
def subscribe(self, property_name, callback, valueonly=False):
self.connected.wait()
self.socket.subscribe(property_name)
super().subscribe(property_name, callback, valueonly)
subscribe.__doc__ = PropertyClient.subscribe.__doc__
def unsubscribe(self, property_name, callback, valueonly=False):
super().unsubscribe(property_name, callback, valueonly)
self.connected.wait()
self.socket.unsubscribe(property_name)
unsubscribe.__doc__ = PropertyClient.unsubscribe.__doc__
def subscribe_prefix(self, property_prefix, callback):
self.connected.wait()
self.socket.subscribe(property_prefix)
super().subscribe_prefix(property_prefix, callback)
subscribe_prefix.__doc__ = PropertyClient.subscribe_prefix.__doc__
def unsubscribe_prefix(self, property_prefix, callback):
super().unsubscribe_prefix(property_prefix, callback)
self.connected.wait()
self.socket.unsubscribe(property_prefix)
unsubscribe_prefix.__doc__ = PropertyClient.unsubscribe_prefix.__doc__
def _receive_update(self):
while not self.socket.poll(500): # 500 ms wait before checking self.running again
if not self.running:
raise RuntimeError()
if not self.connected.is_set():
# reconnect was requested
self.socket.close()
self._connect()
# poll returned true: socket has data to recv
property_name = self.socket.recv_string()
assert(self.socket.getsockopt(zmq.RCVMORE))
value = self.socket.recv_json()
return property_name, value
|
unsubscribe_prefix
|
identifier_name
|
d3d11on12.rs
|
// Copyright © 2017 winapi-rs developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according to those terms.
//! Mappings for the content of d3d11on12.h
use ctypes::c_void;
use shared::guiddef::IID;
use shared::minwindef::UINT;
use um::d3d11::{ID3D11Device, ID3D11DeviceContext, ID3D11Resource};
use um::d3d12::D3D12_RESOURCE_STATES;
use um::d3dcommon::D3D_FEATURE_LEVEL;
use um::unknwnbase::{IUnknown, IUnknownVtbl};
use um::winnt::HRESULT;
FN!{stdcall PFN_D3D11ON12_CREATE_DEVICE(
*mut IUnknown,
UINT,
*const D3D_FEATURE_LEVEL,
UINT,
*mut *mut IUnknown,
UINT,
UINT,
*mut *mut ID3D11Device,
*mut *mut ID3D11DeviceContext,
*mut D3D_FEATURE_LEVEL,
) -> HRESULT}
extern "system"{
pub fn D3D11On12CreateDevice(
pDevice: *mut IUnknown,
Flags: UINT,
pFeatureLevels: *const D3D_FEATURE_LEVEL,
FeatureLevels: UINT,
ppCommandQueues: *mut *mut IUnknown,
NumQueues: UINT,
NodeMask: UINT,
ppDevice: *mut *mut ID3D11Device,
ppImmediateContext: *mut *mut ID3D11DeviceContext,
pChosenFeatureLevel: *mut D3D_FEATURE_LEVEL
) -> HRESULT;
}
STRUCT!{struct D3D11_RESOURCE_FLAGS {
BindFlags: UINT,
MiscFlags: UINT,
CPUAccessFlags: UINT,
StructureByteStride: UINT,
}}
RIDL!{#[uuid(0x85611e73, 0x70a9, 0x490e, 0x96, 0x14, 0xa9, 0xe3, 0x02, 0x77, 0x79, 0x04)]
interface ID3D11On12Device(ID3D11On12DeviceVtbl): IUnknown(IUnknownVtbl) {
fn CreateWrappedResource(
pResource12: *mut IUnknown,
pFlags11: *const D3D11_RESOURCE_FLAGS,
InState: D3D12_RESOURCE_STATES,
OutState: D3D12_RESOURCE_STATES,
riid: *const IID,
ppResource11: *mut *mut c_void,
) -> HRESULT,
fn ReleaseWrappedResources(
ppResources: *mut *mut ID3D11Resource,
NumResources: UINT,
) -> (),
|
ppResources: *mut *mut ID3D11Resource,
NumResources: UINT,
) -> (),
}}
DEFINE_GUID!{IID_ID3D11On12Device,
0x85611e73, 0x70a9, 0x490e, 0x96, 0x14, 0xa9, 0xe3, 0x02, 0x77, 0x79, 0x04}
|
fn AcquireWrappedResources(
|
random_line_split
|
tree.rs
|
use ai;
use ai::value;
use ai::StatelessAI;
use game;
use game::Position2;
pub fn recursive_judgement(
state: &game::State,
my_color: game::Color,
depth: u8,
value_function: value::Simple,
) -> i32 {
if depth == 0 || !state.victory_state.active() {
value_function.value_of(state, my_color)
} else {
let values = state.legal_actions().map(|action| {
let mut new_state = state.clone();
new_state.execute(action);
let value = recursive_judgement(&new_state, my_color, depth - 1, value_function);
value
});
if state.current_color == my_color
|
else {
values.min()
}.unwrap()
}
}
pub struct TreeJudgementAI {
search_depth: u8,
value_function: value::Simple,
}
impl TreeJudgementAI {
pub fn new(depth: u8, value_function: value::Simple) -> TreeJudgementAI {
TreeJudgementAI {
search_depth: depth,
value_function,
}
}
}
impl StatelessAI for TreeJudgementAI {
fn action(&self, state: &game::State) -> Position2 {
let my_color = state.current_color;
let graded_actions = state.legal_actions().map(|action| {
let mut new_state = state.clone();
new_state.execute(action);
let value = recursive_judgement(
&new_state,
my_color,
self.search_depth - 1,
self.value_function,
);
(action, value)
});
ai::random_best_move(graded_actions)
}
}
|
{
values.max()
}
|
conditional_block
|
tree.rs
|
use ai;
use ai::value;
use ai::StatelessAI;
use game;
use game::Position2;
pub fn recursive_judgement(
state: &game::State,
my_color: game::Color,
depth: u8,
value_function: value::Simple,
) -> i32 {
if depth == 0 || !state.victory_state.active() {
value_function.value_of(state, my_color)
} else {
let values = state.legal_actions().map(|action| {
let mut new_state = state.clone();
new_state.execute(action);
let value = recursive_judgement(&new_state, my_color, depth - 1, value_function);
value
});
if state.current_color == my_color {
values.max()
} else {
values.min()
}.unwrap()
}
}
pub struct TreeJudgementAI {
search_depth: u8,
value_function: value::Simple,
}
impl TreeJudgementAI {
pub fn new(depth: u8, value_function: value::Simple) -> TreeJudgementAI
|
}
impl StatelessAI for TreeJudgementAI {
fn action(&self, state: &game::State) -> Position2 {
let my_color = state.current_color;
let graded_actions = state.legal_actions().map(|action| {
let mut new_state = state.clone();
new_state.execute(action);
let value = recursive_judgement(
&new_state,
my_color,
self.search_depth - 1,
self.value_function,
);
(action, value)
});
ai::random_best_move(graded_actions)
}
}
|
{
TreeJudgementAI {
search_depth: depth,
value_function,
}
}
|
identifier_body
|
tree.rs
|
use ai;
use ai::value;
use ai::StatelessAI;
use game;
use game::Position2;
pub fn recursive_judgement(
state: &game::State,
my_color: game::Color,
depth: u8,
value_function: value::Simple,
) -> i32 {
if depth == 0 || !state.victory_state.active() {
value_function.value_of(state, my_color)
} else {
let values = state.legal_actions().map(|action| {
let mut new_state = state.clone();
new_state.execute(action);
|
let value = recursive_judgement(&new_state, my_color, depth - 1, value_function);
value
});
if state.current_color == my_color {
values.max()
} else {
values.min()
}.unwrap()
}
}
pub struct TreeJudgementAI {
search_depth: u8,
value_function: value::Simple,
}
impl TreeJudgementAI {
pub fn new(depth: u8, value_function: value::Simple) -> TreeJudgementAI {
TreeJudgementAI {
search_depth: depth,
value_function,
}
}
}
impl StatelessAI for TreeJudgementAI {
fn action(&self, state: &game::State) -> Position2 {
let my_color = state.current_color;
let graded_actions = state.legal_actions().map(|action| {
let mut new_state = state.clone();
new_state.execute(action);
let value = recursive_judgement(
&new_state,
my_color,
self.search_depth - 1,
self.value_function,
);
(action, value)
});
ai::random_best_move(graded_actions)
}
}
|
random_line_split
|
|
tree.rs
|
use ai;
use ai::value;
use ai::StatelessAI;
use game;
use game::Position2;
pub fn
|
(
state: &game::State,
my_color: game::Color,
depth: u8,
value_function: value::Simple,
) -> i32 {
if depth == 0 || !state.victory_state.active() {
value_function.value_of(state, my_color)
} else {
let values = state.legal_actions().map(|action| {
let mut new_state = state.clone();
new_state.execute(action);
let value = recursive_judgement(&new_state, my_color, depth - 1, value_function);
value
});
if state.current_color == my_color {
values.max()
} else {
values.min()
}.unwrap()
}
}
pub struct TreeJudgementAI {
search_depth: u8,
value_function: value::Simple,
}
impl TreeJudgementAI {
pub fn new(depth: u8, value_function: value::Simple) -> TreeJudgementAI {
TreeJudgementAI {
search_depth: depth,
value_function,
}
}
}
impl StatelessAI for TreeJudgementAI {
fn action(&self, state: &game::State) -> Position2 {
let my_color = state.current_color;
let graded_actions = state.legal_actions().map(|action| {
let mut new_state = state.clone();
new_state.execute(action);
let value = recursive_judgement(
&new_state,
my_color,
self.search_depth - 1,
self.value_function,
);
(action, value)
});
ai::random_best_move(graded_actions)
}
}
|
recursive_judgement
|
identifier_name
|
SettingsListItemColorPicker.js
|
import PropTypes from 'prop-types'
import React from 'react'
import { Button } from '@material-ui/core'
import shallowCompare from 'react-addons-shallow-compare'
import { withStyles } from '@material-ui/core/styles'
import SettingsListItem from './SettingsListItem'
import ColorPickerButton from './ColorPickerButton'
const styles = {
colorPickerButton: {
overflow: 'hidden',
marginRight: 6
},
colorPreview: {
marginTop: -9,
marginRight: 6,
marginBottom: -9,
marginLeft: -9,
width: 32,
height: 34,
verticalAlign: 'middle',
backgroundImage: 'repeating-linear-gradient(45deg, #EEE, #EEE 2px, #FFF 2px, #FFF 5px)'
},
colorPreviewIcon: {
width: '100%',
height: '100%',
padding: 7
},
buttonIcon: {
marginRight: 6,
width: 18,
height: 18,
verticalAlign: 'middle'
}
}
@withStyles(styles)
class SettingsListItemColorPicker extends React.Component {
/* **************************************************************************/
|
static propTypes = {
labelText: PropTypes.string.isRequired,
IconClass: PropTypes.func,
disabled: PropTypes.bool,
value: PropTypes.string,
onChange: PropTypes.func,
showClear: PropTypes.bool.isRequired,
ClearIconClass: PropTypes.func,
clearLabelText: PropTypes.string
}
static defaultProps = {
showClear: true
}
/* **************************************************************************/
// Rendering
/* **************************************************************************/
shouldComponentUpdate (nextProps, nextState) {
return shallowCompare(this, nextProps, nextState)
}
render () {
const {
classes,
labelText,
IconClass,
disabled,
value,
onChange,
showClear,
ClearIconClass,
clearLabelText,
...passProps
} = this.props
return (
<SettingsListItem {...passProps}>
<ColorPickerButton
buttonProps={{ variant: 'contained', size: 'small', className: classes.colorPickerButton }}
value={value}
disabled={disabled}
onChange={onChange}>
{IconClass ? (
<span className={classes.colorPreview}>
<IconClass
className={classes.colorPreviewIcon}
style={disabled ? undefined : ColorPickerButton.generatePreviewIconColors(value)} />
</span>
) : undefined}
{labelText}
</ColorPickerButton>
{showClear ? (
<Button
variant='contained'
size='small'
disabled={disabled}
onClick={() => { if (onChange) { onChange(undefined) } }}>
{ClearIconClass ? (
<ClearIconClass className={classes.buttonIcon} />
) : undefined}
{clearLabelText}
</Button>
) : undefined}
</SettingsListItem>
)
}
}
export default SettingsListItemColorPicker
|
// Class
/* **************************************************************************/
|
random_line_split
|
SettingsListItemColorPicker.js
|
import PropTypes from 'prop-types'
import React from 'react'
import { Button } from '@material-ui/core'
import shallowCompare from 'react-addons-shallow-compare'
import { withStyles } from '@material-ui/core/styles'
import SettingsListItem from './SettingsListItem'
import ColorPickerButton from './ColorPickerButton'
const styles = {
colorPickerButton: {
overflow: 'hidden',
marginRight: 6
},
colorPreview: {
marginTop: -9,
marginRight: 6,
marginBottom: -9,
marginLeft: -9,
width: 32,
height: 34,
verticalAlign: 'middle',
backgroundImage: 'repeating-linear-gradient(45deg, #EEE, #EEE 2px, #FFF 2px, #FFF 5px)'
},
colorPreviewIcon: {
width: '100%',
height: '100%',
padding: 7
},
buttonIcon: {
marginRight: 6,
width: 18,
height: 18,
verticalAlign: 'middle'
}
}
@withStyles(styles)
class SettingsListItemColorPicker extends React.Component {
/* **************************************************************************/
// Class
/* **************************************************************************/
static propTypes = {
labelText: PropTypes.string.isRequired,
IconClass: PropTypes.func,
disabled: PropTypes.bool,
value: PropTypes.string,
onChange: PropTypes.func,
showClear: PropTypes.bool.isRequired,
ClearIconClass: PropTypes.func,
clearLabelText: PropTypes.string
}
static defaultProps = {
showClear: true
}
/* **************************************************************************/
// Rendering
/* **************************************************************************/
shouldComponentUpdate (nextProps, nextState)
|
render () {
const {
classes,
labelText,
IconClass,
disabled,
value,
onChange,
showClear,
ClearIconClass,
clearLabelText,
...passProps
} = this.props
return (
<SettingsListItem {...passProps}>
<ColorPickerButton
buttonProps={{ variant: 'contained', size: 'small', className: classes.colorPickerButton }}
value={value}
disabled={disabled}
onChange={onChange}>
{IconClass ? (
<span className={classes.colorPreview}>
<IconClass
className={classes.colorPreviewIcon}
style={disabled ? undefined : ColorPickerButton.generatePreviewIconColors(value)} />
</span>
) : undefined}
{labelText}
</ColorPickerButton>
{showClear ? (
<Button
variant='contained'
size='small'
disabled={disabled}
onClick={() => { if (onChange) { onChange(undefined) } }}>
{ClearIconClass ? (
<ClearIconClass className={classes.buttonIcon} />
) : undefined}
{clearLabelText}
</Button>
) : undefined}
</SettingsListItem>
)
}
}
export default SettingsListItemColorPicker
|
{
return shallowCompare(this, nextProps, nextState)
}
|
identifier_body
|
SettingsListItemColorPicker.js
|
import PropTypes from 'prop-types'
import React from 'react'
import { Button } from '@material-ui/core'
import shallowCompare from 'react-addons-shallow-compare'
import { withStyles } from '@material-ui/core/styles'
import SettingsListItem from './SettingsListItem'
import ColorPickerButton from './ColorPickerButton'
const styles = {
colorPickerButton: {
overflow: 'hidden',
marginRight: 6
},
colorPreview: {
marginTop: -9,
marginRight: 6,
marginBottom: -9,
marginLeft: -9,
width: 32,
height: 34,
verticalAlign: 'middle',
backgroundImage: 'repeating-linear-gradient(45deg, #EEE, #EEE 2px, #FFF 2px, #FFF 5px)'
},
colorPreviewIcon: {
width: '100%',
height: '100%',
padding: 7
},
buttonIcon: {
marginRight: 6,
width: 18,
height: 18,
verticalAlign: 'middle'
}
}
@withStyles(styles)
class SettingsListItemColorPicker extends React.Component {
/* **************************************************************************/
// Class
/* **************************************************************************/
static propTypes = {
labelText: PropTypes.string.isRequired,
IconClass: PropTypes.func,
disabled: PropTypes.bool,
value: PropTypes.string,
onChange: PropTypes.func,
showClear: PropTypes.bool.isRequired,
ClearIconClass: PropTypes.func,
clearLabelText: PropTypes.string
}
static defaultProps = {
showClear: true
}
/* **************************************************************************/
// Rendering
/* **************************************************************************/
shouldComponentUpdate (nextProps, nextState) {
return shallowCompare(this, nextProps, nextState)
}
render () {
const {
classes,
labelText,
IconClass,
disabled,
value,
onChange,
showClear,
ClearIconClass,
clearLabelText,
...passProps
} = this.props
return (
<SettingsListItem {...passProps}>
<ColorPickerButton
buttonProps={{ variant: 'contained', size: 'small', className: classes.colorPickerButton }}
value={value}
disabled={disabled}
onChange={onChange}>
{IconClass ? (
<span className={classes.colorPreview}>
<IconClass
className={classes.colorPreviewIcon}
style={disabled ? undefined : ColorPickerButton.generatePreviewIconColors(value)} />
</span>
) : undefined}
{labelText}
</ColorPickerButton>
{showClear ? (
<Button
variant='contained'
size='small'
disabled={disabled}
onClick={() => { if (onChange)
|
}}>
{ClearIconClass ? (
<ClearIconClass className={classes.buttonIcon} />
) : undefined}
{clearLabelText}
</Button>
) : undefined}
</SettingsListItem>
)
}
}
export default SettingsListItemColorPicker
|
{ onChange(undefined) }
|
conditional_block
|
SettingsListItemColorPicker.js
|
import PropTypes from 'prop-types'
import React from 'react'
import { Button } from '@material-ui/core'
import shallowCompare from 'react-addons-shallow-compare'
import { withStyles } from '@material-ui/core/styles'
import SettingsListItem from './SettingsListItem'
import ColorPickerButton from './ColorPickerButton'
const styles = {
colorPickerButton: {
overflow: 'hidden',
marginRight: 6
},
colorPreview: {
marginTop: -9,
marginRight: 6,
marginBottom: -9,
marginLeft: -9,
width: 32,
height: 34,
verticalAlign: 'middle',
backgroundImage: 'repeating-linear-gradient(45deg, #EEE, #EEE 2px, #FFF 2px, #FFF 5px)'
},
colorPreviewIcon: {
width: '100%',
height: '100%',
padding: 7
},
buttonIcon: {
marginRight: 6,
width: 18,
height: 18,
verticalAlign: 'middle'
}
}
@withStyles(styles)
class SettingsListItemColorPicker extends React.Component {
/* **************************************************************************/
// Class
/* **************************************************************************/
static propTypes = {
labelText: PropTypes.string.isRequired,
IconClass: PropTypes.func,
disabled: PropTypes.bool,
value: PropTypes.string,
onChange: PropTypes.func,
showClear: PropTypes.bool.isRequired,
ClearIconClass: PropTypes.func,
clearLabelText: PropTypes.string
}
static defaultProps = {
showClear: true
}
/* **************************************************************************/
// Rendering
/* **************************************************************************/
shouldComponentUpdate (nextProps, nextState) {
return shallowCompare(this, nextProps, nextState)
}
|
() {
const {
classes,
labelText,
IconClass,
disabled,
value,
onChange,
showClear,
ClearIconClass,
clearLabelText,
...passProps
} = this.props
return (
<SettingsListItem {...passProps}>
<ColorPickerButton
buttonProps={{ variant: 'contained', size: 'small', className: classes.colorPickerButton }}
value={value}
disabled={disabled}
onChange={onChange}>
{IconClass ? (
<span className={classes.colorPreview}>
<IconClass
className={classes.colorPreviewIcon}
style={disabled ? undefined : ColorPickerButton.generatePreviewIconColors(value)} />
</span>
) : undefined}
{labelText}
</ColorPickerButton>
{showClear ? (
<Button
variant='contained'
size='small'
disabled={disabled}
onClick={() => { if (onChange) { onChange(undefined) } }}>
{ClearIconClass ? (
<ClearIconClass className={classes.buttonIcon} />
) : undefined}
{clearLabelText}
</Button>
) : undefined}
</SettingsListItem>
)
}
}
export default SettingsListItemColorPicker
|
render
|
identifier_name
|
ClientConnectionManager.ts
|
import * as Promise from 'bluebird';
import Address = require('../Address');
import ClientConnection = require('./ClientConnection');
import InvocationService = require('./InvocationService');
import {GroupConfig, ClientNetworkConfig} from '../Config';
import ConnectionAuthenticator = require('./ConnectionAuthenticator');
import {LoggingService} from '../logging/LoggingService';
import {EventEmitter} from 'events';
import HazelcastClient from '../HazelcastClient';
const EMIT_CONNECTION_CLOSED = 'connectionClosed';
const EMIT_CONNECTION_OPENED = 'connectionOpened';
/**
* Maintains connections between the client and members of the cluster.
*/
class ClientConnectionManager extends EventEmitter {
private client: HazelcastClient;
private pendingConnections: {[address: string]: Promise.Resolver<ClientConnection>} = {};
private logger = LoggingService.getLoggingService();
establishedConnections: {[address: string]: ClientConnection} = {};
constructor(client: HazelcastClient) {
super();
this.client = client;
}
/**
* Returns the {@link ClientConnection} with given {@link Address}. If there is no such connection established,
* it first connects to the address and then return the {@link ClientConnection}.
* @param address
* @param ownerConnection Sets the connected node as owner of this client if true.
* @returns {Promise<ClientConnection>|Promise<T>}
*/
getOrConnect(address: Address, ownerConnection: boolean = false): Promise<ClientConnection> {
var addressIndex = Address.encodeToString(address);
var result: Promise.Resolver<ClientConnection> = Promise.defer<ClientConnection>();
var establishedConnection = this.establishedConnections[addressIndex];
if (establishedConnection) {
result.resolve(establishedConnection);
return result.promise;
}
var pendingConnection = this.pendingConnections[addressIndex];
if (pendingConnection) {
return pendingConnection.promise;
}
this.pendingConnections[addressIndex] = result;
var clientConnection = new ClientConnection(address);
clientConnection.connect().then(() => {
clientConnection.registerResponseCallback((data: Buffer) => {
this.client.getInvocationService().processResponse(data);
});
}).then(() => {
return this.authenticate(clientConnection, ownerConnection);
}).then((authenticated: boolean) => {
if (authenticated) {
this.establishedConnections[Address.encodeToString(clientConnection.address)] = clientConnection;
} else {
throw new Error('Authentication failed');
}
}).then(() => {
this.onConnectionOpened(clientConnection);
result.resolve(clientConnection);
}).catch((e: any) => {
result.reject(e);
}).finally(() => {
delete this.pendingConnections[addressIndex];
});
return result.promise;
}
/**
* Destroys the connection with given node address.
* @param address
*/
destroyConnection(address: Address): void {
var addressStr = Address.encodeToString(address);
if (this.pendingConnections.hasOwnProperty(addressStr))
|
if (this.establishedConnections.hasOwnProperty(addressStr)) {
var conn = this.establishedConnections[addressStr];
conn.close();
delete this.establishedConnections[addressStr];
this.onConnectionClosed(conn);
}
}
shutdown() {
for (var pending in this.pendingConnections) {
this.pendingConnections[pending].reject(new Error('Client is shutting down!'));
}
for (var conn in this.establishedConnections) {
this.establishedConnections[conn].close();
}
}
private onConnectionClosed(connection: ClientConnection) {
this.emit(EMIT_CONNECTION_CLOSED, connection);
}
private onConnectionOpened(connection: ClientConnection) {
this.emit(EMIT_CONNECTION_OPENED, connection);
}
private authenticate(connection: ClientConnection, ownerConnection: boolean): Promise<boolean> {
var authenticator = new ConnectionAuthenticator(connection, this.client);
return authenticator.authenticate(ownerConnection);
}
}
export = ClientConnectionManager;
|
{
this.pendingConnections[addressStr].reject(null);
}
|
conditional_block
|
ClientConnectionManager.ts
|
import * as Promise from 'bluebird';
import Address = require('../Address');
import ClientConnection = require('./ClientConnection');
import InvocationService = require('./InvocationService');
import {GroupConfig, ClientNetworkConfig} from '../Config';
import ConnectionAuthenticator = require('./ConnectionAuthenticator');
import {LoggingService} from '../logging/LoggingService';
import {EventEmitter} from 'events';
import HazelcastClient from '../HazelcastClient';
const EMIT_CONNECTION_CLOSED = 'connectionClosed';
const EMIT_CONNECTION_OPENED = 'connectionOpened';
/**
* Maintains connections between the client and members of the cluster.
*/
class ClientConnectionManager extends EventEmitter {
private client: HazelcastClient;
private pendingConnections: {[address: string]: Promise.Resolver<ClientConnection>} = {};
private logger = LoggingService.getLoggingService();
establishedConnections: {[address: string]: ClientConnection} = {};
constructor(client: HazelcastClient) {
super();
this.client = client;
}
/**
* Returns the {@link ClientConnection} with given {@link Address}. If there is no such connection established,
* it first connects to the address and then return the {@link ClientConnection}.
* @param address
* @param ownerConnection Sets the connected node as owner of this client if true.
* @returns {Promise<ClientConnection>|Promise<T>}
*/
getOrConnect(address: Address, ownerConnection: boolean = false): Promise<ClientConnection> {
var addressIndex = Address.encodeToString(address);
var result: Promise.Resolver<ClientConnection> = Promise.defer<ClientConnection>();
var establishedConnection = this.establishedConnections[addressIndex];
if (establishedConnection) {
result.resolve(establishedConnection);
return result.promise;
}
var pendingConnection = this.pendingConnections[addressIndex];
if (pendingConnection) {
return pendingConnection.promise;
}
this.pendingConnections[addressIndex] = result;
var clientConnection = new ClientConnection(address);
clientConnection.connect().then(() => {
clientConnection.registerResponseCallback((data: Buffer) => {
this.client.getInvocationService().processResponse(data);
});
}).then(() => {
return this.authenticate(clientConnection, ownerConnection);
}).then((authenticated: boolean) => {
if (authenticated) {
this.establishedConnections[Address.encodeToString(clientConnection.address)] = clientConnection;
} else {
throw new Error('Authentication failed');
}
}).then(() => {
this.onConnectionOpened(clientConnection);
result.resolve(clientConnection);
}).catch((e: any) => {
result.reject(e);
}).finally(() => {
delete this.pendingConnections[addressIndex];
});
return result.promise;
}
/**
* Destroys the connection with given node address.
* @param address
*/
destroyConnection(address: Address): void
|
shutdown() {
for (var pending in this.pendingConnections) {
this.pendingConnections[pending].reject(new Error('Client is shutting down!'));
}
for (var conn in this.establishedConnections) {
this.establishedConnections[conn].close();
}
}
private onConnectionClosed(connection: ClientConnection) {
this.emit(EMIT_CONNECTION_CLOSED, connection);
}
private onConnectionOpened(connection: ClientConnection) {
this.emit(EMIT_CONNECTION_OPENED, connection);
}
private authenticate(connection: ClientConnection, ownerConnection: boolean): Promise<boolean> {
var authenticator = new ConnectionAuthenticator(connection, this.client);
return authenticator.authenticate(ownerConnection);
}
}
export = ClientConnectionManager;
|
{
var addressStr = Address.encodeToString(address);
if (this.pendingConnections.hasOwnProperty(addressStr)) {
this.pendingConnections[addressStr].reject(null);
}
if (this.establishedConnections.hasOwnProperty(addressStr)) {
var conn = this.establishedConnections[addressStr];
conn.close();
delete this.establishedConnections[addressStr];
this.onConnectionClosed(conn);
}
}
|
identifier_body
|
ClientConnectionManager.ts
|
import * as Promise from 'bluebird';
import Address = require('../Address');
import ClientConnection = require('./ClientConnection');
import InvocationService = require('./InvocationService');
import {GroupConfig, ClientNetworkConfig} from '../Config';
import ConnectionAuthenticator = require('./ConnectionAuthenticator');
import {LoggingService} from '../logging/LoggingService';
import {EventEmitter} from 'events';
import HazelcastClient from '../HazelcastClient';
const EMIT_CONNECTION_CLOSED = 'connectionClosed';
const EMIT_CONNECTION_OPENED = 'connectionOpened';
/**
* Maintains connections between the client and members of the cluster.
*/
class ClientConnectionManager extends EventEmitter {
private client: HazelcastClient;
private pendingConnections: {[address: string]: Promise.Resolver<ClientConnection>} = {};
private logger = LoggingService.getLoggingService();
establishedConnections: {[address: string]: ClientConnection} = {};
constructor(client: HazelcastClient) {
super();
this.client = client;
}
/**
* Returns the {@link ClientConnection} with given {@link Address}. If there is no such connection established,
* it first connects to the address and then return the {@link ClientConnection}.
* @param address
* @param ownerConnection Sets the connected node as owner of this client if true.
* @returns {Promise<ClientConnection>|Promise<T>}
*/
getOrConnect(address: Address, ownerConnection: boolean = false): Promise<ClientConnection> {
var addressIndex = Address.encodeToString(address);
var result: Promise.Resolver<ClientConnection> = Promise.defer<ClientConnection>();
var establishedConnection = this.establishedConnections[addressIndex];
if (establishedConnection) {
result.resolve(establishedConnection);
return result.promise;
}
var pendingConnection = this.pendingConnections[addressIndex];
if (pendingConnection) {
return pendingConnection.promise;
}
this.pendingConnections[addressIndex] = result;
var clientConnection = new ClientConnection(address);
clientConnection.connect().then(() => {
clientConnection.registerResponseCallback((data: Buffer) => {
this.client.getInvocationService().processResponse(data);
});
}).then(() => {
return this.authenticate(clientConnection, ownerConnection);
}).then((authenticated: boolean) => {
if (authenticated) {
this.establishedConnections[Address.encodeToString(clientConnection.address)] = clientConnection;
} else {
throw new Error('Authentication failed');
}
}).then(() => {
this.onConnectionOpened(clientConnection);
result.resolve(clientConnection);
}).catch((e: any) => {
result.reject(e);
}).finally(() => {
delete this.pendingConnections[addressIndex];
});
return result.promise;
}
/**
* Destroys the connection with given node address.
* @param address
*/
destroyConnection(address: Address): void {
var addressStr = Address.encodeToString(address);
if (this.pendingConnections.hasOwnProperty(addressStr)) {
this.pendingConnections[addressStr].reject(null);
}
if (this.establishedConnections.hasOwnProperty(addressStr)) {
var conn = this.establishedConnections[addressStr];
conn.close();
delete this.establishedConnections[addressStr];
this.onConnectionClosed(conn);
}
}
shutdown() {
for (var pending in this.pendingConnections) {
this.pendingConnections[pending].reject(new Error('Client is shutting down!'));
}
for (var conn in this.establishedConnections) {
this.establishedConnections[conn].close();
}
}
private onConnectionClosed(connection: ClientConnection) {
this.emit(EMIT_CONNECTION_CLOSED, connection);
}
private onConnectionOpened(connection: ClientConnection) {
this.emit(EMIT_CONNECTION_OPENED, connection);
}
private authenticate(connection: ClientConnection, ownerConnection: boolean): Promise<boolean> {
var authenticator = new ConnectionAuthenticator(connection, this.client);
return authenticator.authenticate(ownerConnection);
}
}
|
export = ClientConnectionManager;
|
random_line_split
|
|
ClientConnectionManager.ts
|
import * as Promise from 'bluebird';
import Address = require('../Address');
import ClientConnection = require('./ClientConnection');
import InvocationService = require('./InvocationService');
import {GroupConfig, ClientNetworkConfig} from '../Config';
import ConnectionAuthenticator = require('./ConnectionAuthenticator');
import {LoggingService} from '../logging/LoggingService';
import {EventEmitter} from 'events';
import HazelcastClient from '../HazelcastClient';
const EMIT_CONNECTION_CLOSED = 'connectionClosed';
const EMIT_CONNECTION_OPENED = 'connectionOpened';
/**
* Maintains connections between the client and members of the cluster.
*/
class ClientConnectionManager extends EventEmitter {
private client: HazelcastClient;
private pendingConnections: {[address: string]: Promise.Resolver<ClientConnection>} = {};
private logger = LoggingService.getLoggingService();
establishedConnections: {[address: string]: ClientConnection} = {};
constructor(client: HazelcastClient) {
super();
this.client = client;
}
/**
* Returns the {@link ClientConnection} with given {@link Address}. If there is no such connection established,
* it first connects to the address and then return the {@link ClientConnection}.
* @param address
* @param ownerConnection Sets the connected node as owner of this client if true.
* @returns {Promise<ClientConnection>|Promise<T>}
*/
getOrConnect(address: Address, ownerConnection: boolean = false): Promise<ClientConnection> {
var addressIndex = Address.encodeToString(address);
var result: Promise.Resolver<ClientConnection> = Promise.defer<ClientConnection>();
var establishedConnection = this.establishedConnections[addressIndex];
if (establishedConnection) {
result.resolve(establishedConnection);
return result.promise;
}
var pendingConnection = this.pendingConnections[addressIndex];
if (pendingConnection) {
return pendingConnection.promise;
}
this.pendingConnections[addressIndex] = result;
var clientConnection = new ClientConnection(address);
clientConnection.connect().then(() => {
clientConnection.registerResponseCallback((data: Buffer) => {
this.client.getInvocationService().processResponse(data);
});
}).then(() => {
return this.authenticate(clientConnection, ownerConnection);
}).then((authenticated: boolean) => {
if (authenticated) {
this.establishedConnections[Address.encodeToString(clientConnection.address)] = clientConnection;
} else {
throw new Error('Authentication failed');
}
}).then(() => {
this.onConnectionOpened(clientConnection);
result.resolve(clientConnection);
}).catch((e: any) => {
result.reject(e);
}).finally(() => {
delete this.pendingConnections[addressIndex];
});
return result.promise;
}
/**
* Destroys the connection with given node address.
* @param address
*/
destroyConnection(address: Address): void {
var addressStr = Address.encodeToString(address);
if (this.pendingConnections.hasOwnProperty(addressStr)) {
this.pendingConnections[addressStr].reject(null);
}
if (this.establishedConnections.hasOwnProperty(addressStr)) {
var conn = this.establishedConnections[addressStr];
conn.close();
delete this.establishedConnections[addressStr];
this.onConnectionClosed(conn);
}
}
|
() {
for (var pending in this.pendingConnections) {
this.pendingConnections[pending].reject(new Error('Client is shutting down!'));
}
for (var conn in this.establishedConnections) {
this.establishedConnections[conn].close();
}
}
private onConnectionClosed(connection: ClientConnection) {
this.emit(EMIT_CONNECTION_CLOSED, connection);
}
private onConnectionOpened(connection: ClientConnection) {
this.emit(EMIT_CONNECTION_OPENED, connection);
}
private authenticate(connection: ClientConnection, ownerConnection: boolean): Promise<boolean> {
var authenticator = new ConnectionAuthenticator(connection, this.client);
return authenticator.authenticate(ownerConnection);
}
}
export = ClientConnectionManager;
|
shutdown
|
identifier_name
|
mkin.js
|
function completeWriteDocument(ret_obj) {
var error = ret_obj['error'];
var message = ret_obj['message'];
var document_srl = ret_obj['document_srl'];
var url;
if(!document_srl)
{
url = current_url.setQuery('act','');
}
else
{
url = current_url.setQuery('document_srl',document_srl).setQuery('act','');
}
|
function completeWriteReply(ret_obj) {
alert(ret_obj['message']);
var url = request_uri.setQuery('mid', current_mid).setQuery('document_srl', ret_obj['document_srl']).setQuery('act','dispKinView');
if(typeof(xeVid)!='undefined') url = url.setQuery('vid', xeVid);
location.href = url;
}
function doDeleteDocument(document_srl) {
var params = new Array();
params['document_srl'] = document_srl;
var url = request_uri.setQuery('mid', current_mid).setQuery('document_srl', '').setQuery('act','');
if(typeof(xeVid)!='undefined') url = url.setQuery('vid', xeVid);
exec_xml('kin','procKinDeleteDocument', params, function() { location.href=url; });
}
function loadPage(document_srl, page) {
var params = {};
params["cpage"] = page;
params["document_srl"] = document_srl;
params["mid"] = current_mid;
exec_xml("board", "getKinCommentPage", params, completeGetPage, ['html','error','message'], params);
}
function completeGetPage(ret_val) {
jQuery("#cl").remove();
jQuery("#clpn").remove();
jQuery("#clb").after(ret_val['html']);
}
function doDeleteReply(comment_srl) {
var params = new Array();
params['comment_srl'] = comment_srl;
exec_xml('kin','procKinDeleteReply', params, function() { location.reload(); });
}
function doSelectReply(comment_srl) {
var params = new Array();
params['comment_srl'] = comment_srl;
exec_xml('kin','procKinSelectReply', params, function() { location.reload(); });
}
function doGetComments(parent_srl, page) {
var o = jQuery('#replies_'+parent_srl);
var o = jQuery('#replies_content_'+parent_srl);
if(o.css('display')=='block' && typeof(page)=='undefined') o.css('display','none');
else {
var params = new Array();
params['mid'] = current_mid;
params['parent_srl'] = parent_srl;
if(typeof(page)=='undefined') page = 1;
params['page'] = page;
exec_xml('kin','getKinComments', params, displayComments, new Array('error','message','parent_srl','html'));
}
}
function displayComments(ret_obj) {
var parent_srl = ret_obj['parent_srl'];
var html = ret_obj['html'];
var o = jQuery('#replies_'+parent_srl);
var o = jQuery('#replies_content_'+parent_srl);
o.html(html).css('display','block');
}
function doDeleteComment(parent_srl,reply_srl) {
var params = new Array();
params['parent_srl'] = parent_srl;
params['reply_srl'] = reply_srl;
params['mid'] = current_mid;
exec_xml('kin','procKinDeleteComment', params, displayComments, new Array('error','message','parent_srl','html'));
}
|
location.href = url;
}
|
random_line_split
|
mkin.js
|
function completeWriteDocument(ret_obj)
|
function completeWriteReply(ret_obj) {
alert(ret_obj['message']);
var url = request_uri.setQuery('mid', current_mid).setQuery('document_srl', ret_obj['document_srl']).setQuery('act','dispKinView');
if(typeof(xeVid)!='undefined') url = url.setQuery('vid', xeVid);
location.href = url;
}
function doDeleteDocument(document_srl) {
var params = new Array();
params['document_srl'] = document_srl;
var url = request_uri.setQuery('mid', current_mid).setQuery('document_srl', '').setQuery('act','');
if(typeof(xeVid)!='undefined') url = url.setQuery('vid', xeVid);
exec_xml('kin','procKinDeleteDocument', params, function() { location.href=url; });
}
function loadPage(document_srl, page) {
var params = {};
params["cpage"] = page;
params["document_srl"] = document_srl;
params["mid"] = current_mid;
exec_xml("board", "getKinCommentPage", params, completeGetPage, ['html','error','message'], params);
}
function completeGetPage(ret_val) {
jQuery("#cl").remove();
jQuery("#clpn").remove();
jQuery("#clb").after(ret_val['html']);
}
function doDeleteReply(comment_srl) {
var params = new Array();
params['comment_srl'] = comment_srl;
exec_xml('kin','procKinDeleteReply', params, function() { location.reload(); });
}
function doSelectReply(comment_srl) {
var params = new Array();
params['comment_srl'] = comment_srl;
exec_xml('kin','procKinSelectReply', params, function() { location.reload(); });
}
function doGetComments(parent_srl, page) {
var o = jQuery('#replies_'+parent_srl);
var o = jQuery('#replies_content_'+parent_srl);
if(o.css('display')=='block' && typeof(page)=='undefined') o.css('display','none');
else {
var params = new Array();
params['mid'] = current_mid;
params['parent_srl'] = parent_srl;
if(typeof(page)=='undefined') page = 1;
params['page'] = page;
exec_xml('kin','getKinComments', params, displayComments, new Array('error','message','parent_srl','html'));
}
}
function displayComments(ret_obj) {
var parent_srl = ret_obj['parent_srl'];
var html = ret_obj['html'];
var o = jQuery('#replies_'+parent_srl);
var o = jQuery('#replies_content_'+parent_srl);
o.html(html).css('display','block');
}
function doDeleteComment(parent_srl,reply_srl) {
var params = new Array();
params['parent_srl'] = parent_srl;
params['reply_srl'] = reply_srl;
params['mid'] = current_mid;
exec_xml('kin','procKinDeleteComment', params, displayComments, new Array('error','message','parent_srl','html'));
}
|
{
var error = ret_obj['error'];
var message = ret_obj['message'];
var document_srl = ret_obj['document_srl'];
var url;
if(!document_srl)
{
url = current_url.setQuery('act','');
}
else
{
url = current_url.setQuery('document_srl',document_srl).setQuery('act','');
}
location.href = url;
}
|
identifier_body
|
mkin.js
|
function
|
(ret_obj) {
var error = ret_obj['error'];
var message = ret_obj['message'];
var document_srl = ret_obj['document_srl'];
var url;
if(!document_srl)
{
url = current_url.setQuery('act','');
}
else
{
url = current_url.setQuery('document_srl',document_srl).setQuery('act','');
}
location.href = url;
}
function completeWriteReply(ret_obj) {
alert(ret_obj['message']);
var url = request_uri.setQuery('mid', current_mid).setQuery('document_srl', ret_obj['document_srl']).setQuery('act','dispKinView');
if(typeof(xeVid)!='undefined') url = url.setQuery('vid', xeVid);
location.href = url;
}
function doDeleteDocument(document_srl) {
var params = new Array();
params['document_srl'] = document_srl;
var url = request_uri.setQuery('mid', current_mid).setQuery('document_srl', '').setQuery('act','');
if(typeof(xeVid)!='undefined') url = url.setQuery('vid', xeVid);
exec_xml('kin','procKinDeleteDocument', params, function() { location.href=url; });
}
function loadPage(document_srl, page) {
var params = {};
params["cpage"] = page;
params["document_srl"] = document_srl;
params["mid"] = current_mid;
exec_xml("board", "getKinCommentPage", params, completeGetPage, ['html','error','message'], params);
}
function completeGetPage(ret_val) {
jQuery("#cl").remove();
jQuery("#clpn").remove();
jQuery("#clb").after(ret_val['html']);
}
function doDeleteReply(comment_srl) {
var params = new Array();
params['comment_srl'] = comment_srl;
exec_xml('kin','procKinDeleteReply', params, function() { location.reload(); });
}
function doSelectReply(comment_srl) {
var params = new Array();
params['comment_srl'] = comment_srl;
exec_xml('kin','procKinSelectReply', params, function() { location.reload(); });
}
function doGetComments(parent_srl, page) {
var o = jQuery('#replies_'+parent_srl);
var o = jQuery('#replies_content_'+parent_srl);
if(o.css('display')=='block' && typeof(page)=='undefined') o.css('display','none');
else {
var params = new Array();
params['mid'] = current_mid;
params['parent_srl'] = parent_srl;
if(typeof(page)=='undefined') page = 1;
params['page'] = page;
exec_xml('kin','getKinComments', params, displayComments, new Array('error','message','parent_srl','html'));
}
}
function displayComments(ret_obj) {
var parent_srl = ret_obj['parent_srl'];
var html = ret_obj['html'];
var o = jQuery('#replies_'+parent_srl);
var o = jQuery('#replies_content_'+parent_srl);
o.html(html).css('display','block');
}
function doDeleteComment(parent_srl,reply_srl) {
var params = new Array();
params['parent_srl'] = parent_srl;
params['reply_srl'] = reply_srl;
params['mid'] = current_mid;
exec_xml('kin','procKinDeleteComment', params, displayComments, new Array('error','message','parent_srl','html'));
}
|
completeWriteDocument
|
identifier_name
|
postoffice.rs
|
// Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{agent_error::ImlAgentError, env};
use std::collections::BTreeSet;
use std::iter::FromIterator;
use tokio::{fs, io::AsyncWriteExt};
async fn write_config(routes: BTreeSet<String>) -> Result<(), ImlAgentError> {
let conf_file = env::get_var("POSTMAN_CONF_PATH");
let mut file = fs::File::create(conf_file).await?;
let rt: Vec<String> = Vec::from_iter(routes);
file.write_all(rt.join("\n").as_bytes()).await?;
file.write(b"\n").await?;
Ok(())
}
async fn
|
() -> Result<BTreeSet<String>, ImlAgentError> {
let conf_file = env::get_var("POSTMAN_CONF_PATH");
Ok(fs::read_to_string(conf_file)
.await?
.lines()
.map(|s| s.to_string())
.collect())
}
pub async fn route_add(mailbox: String) -> Result<(), ImlAgentError> {
let mut conf = read_config().await?;
if conf.insert(mailbox) {
write_config(conf).await
} else {
Ok(())
}
}
pub async fn route_remove(mailbox: String) -> Result<(), ImlAgentError> {
let mut conf = read_config().await?;
if conf.remove(&mailbox) {
write_config(conf).await
} else {
Ok(())
}
}
|
read_config
|
identifier_name
|
postoffice.rs
|
// Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{agent_error::ImlAgentError, env};
use std::collections::BTreeSet;
use std::iter::FromIterator;
use tokio::{fs, io::AsyncWriteExt};
async fn write_config(routes: BTreeSet<String>) -> Result<(), ImlAgentError> {
let conf_file = env::get_var("POSTMAN_CONF_PATH");
let mut file = fs::File::create(conf_file).await?;
let rt: Vec<String> = Vec::from_iter(routes);
file.write_all(rt.join("\n").as_bytes()).await?;
file.write(b"\n").await?;
Ok(())
}
async fn read_config() -> Result<BTreeSet<String>, ImlAgentError> {
let conf_file = env::get_var("POSTMAN_CONF_PATH");
Ok(fs::read_to_string(conf_file)
.await?
.lines()
.map(|s| s.to_string())
.collect())
}
pub async fn route_add(mailbox: String) -> Result<(), ImlAgentError> {
let mut conf = read_config().await?;
if conf.insert(mailbox) {
write_config(conf).await
} else {
Ok(())
}
}
pub async fn route_remove(mailbox: String) -> Result<(), ImlAgentError>
|
{
let mut conf = read_config().await?;
if conf.remove(&mailbox) {
write_config(conf).await
} else {
Ok(())
}
}
|
identifier_body
|
|
postoffice.rs
|
// Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{agent_error::ImlAgentError, env};
use std::collections::BTreeSet;
use std::iter::FromIterator;
use tokio::{fs, io::AsyncWriteExt};
async fn write_config(routes: BTreeSet<String>) -> Result<(), ImlAgentError> {
let conf_file = env::get_var("POSTMAN_CONF_PATH");
let mut file = fs::File::create(conf_file).await?;
|
Ok(())
}
async fn read_config() -> Result<BTreeSet<String>, ImlAgentError> {
let conf_file = env::get_var("POSTMAN_CONF_PATH");
Ok(fs::read_to_string(conf_file)
.await?
.lines()
.map(|s| s.to_string())
.collect())
}
pub async fn route_add(mailbox: String) -> Result<(), ImlAgentError> {
let mut conf = read_config().await?;
if conf.insert(mailbox) {
write_config(conf).await
} else {
Ok(())
}
}
pub async fn route_remove(mailbox: String) -> Result<(), ImlAgentError> {
let mut conf = read_config().await?;
if conf.remove(&mailbox) {
write_config(conf).await
} else {
Ok(())
}
}
|
let rt: Vec<String> = Vec::from_iter(routes);
file.write_all(rt.join("\n").as_bytes()).await?;
file.write(b"\n").await?;
|
random_line_split
|
postoffice.rs
|
// Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::{agent_error::ImlAgentError, env};
use std::collections::BTreeSet;
use std::iter::FromIterator;
use tokio::{fs, io::AsyncWriteExt};
async fn write_config(routes: BTreeSet<String>) -> Result<(), ImlAgentError> {
let conf_file = env::get_var("POSTMAN_CONF_PATH");
let mut file = fs::File::create(conf_file).await?;
let rt: Vec<String> = Vec::from_iter(routes);
file.write_all(rt.join("\n").as_bytes()).await?;
file.write(b"\n").await?;
Ok(())
}
async fn read_config() -> Result<BTreeSet<String>, ImlAgentError> {
let conf_file = env::get_var("POSTMAN_CONF_PATH");
Ok(fs::read_to_string(conf_file)
.await?
.lines()
.map(|s| s.to_string())
.collect())
}
pub async fn route_add(mailbox: String) -> Result<(), ImlAgentError> {
let mut conf = read_config().await?;
if conf.insert(mailbox) {
write_config(conf).await
} else {
Ok(())
}
}
pub async fn route_remove(mailbox: String) -> Result<(), ImlAgentError> {
let mut conf = read_config().await?;
if conf.remove(&mailbox)
|
else {
Ok(())
}
}
|
{
write_config(conf).await
}
|
conditional_block
|
3_16_exercise_springs.rs
|
// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Example 3-16: Exercise Springs
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
// Spring Type describes an anchor point that can connect to "Bob" objects via a spring
// Thank you: http://www.myphysicslab.com/spring2d.html
struct Spring {
// Rest length and spring constant
len: f32,
k: f32,
}
impl Spring {
fn new(l: f32) -> Self {
Spring { len: l, k: 0.2 }
}
// Calculate spring force
fn update(&self, a: &mut Bob, b: &mut Bob) {
// Vector pointing from anchor to bob position
let mut force = a.position - b.position;
// What is the distance
let d = force.magnitude();
// Stretch is difference between current distance and rest length
let stretch = d - self.len;
// Calculate force according to Hooke's Law
// F = k * stretch
force = force.normalize();
force *= -1.0 * self.k * stretch;
a.apply_force(force);
force *= -1.0;
b.apply_force(force);
}
fn display(&self, draw: &Draw, a: &Bob, b: &Bob) {
draw.line()
.start(a.position)
.end(b.position)
.color(BLACK)
.stroke_weight(2.0);
}
}
struct Bob {
position: Point2,
velocity: Vector2,
acceleration: Vector2,
mass: f32,
damping: f32,
drag_offset: Vector2,
dragging: bool,
}
impl Bob {
fn new(x: f32, y: f32) -> Self {
Bob {
position: pt2(x, y),
velocity: vec2(0.0, 0.0),
acceleration: vec2(0.0, 0.0),
mass: 12.0,
damping: 0.95, // Arbitrary damping to simulate friction / drag
drag_offset: vec2(0.0, 0.0),
dragging: false,
}
}
// Standard Euler integration
fn update(&mut self) {
self.velocity += self.acceleration;
self.velocity *= self.damping;
self.position += self.velocity;
self.acceleration *= 0.0;
}
// Newton's law: F = M * A
fn apply_force(&mut self, force: Vector2) {
let f = force / self.mass;
self.acceleration += f;
}
fn display(&self, draw: &Draw) {
let c = if self.dragging { GREY } else { DARKGREY };
draw.ellipse()
.xy(self.position)
.w_h(self.mass * 2.0, self.mass * 2.0)
.color(c)
.stroke(BLACK)
.stroke_weight(2.0);
}
// The methods below are for mouse interaction
// This checks to see if we clicked on the mover
fn clicked(&mut self, mx: f32, my: f32) {
let d = pt2(mx, my).distance(self.position);
if d < self.mass {
self.dragging = true;
self.drag_offset.x = self.position.x - mx;
self.drag_offset.y = self.position.y - my;
}
}
fn stop_dragging(&mut self)
|
fn drag(&mut self, mx: f32, my: f32) {
if self.dragging {
self.position.x = mx + self.drag_offset.x;
self.position.y = my - self.drag_offset.y;
}
}
}
struct Model {
b1: Bob,
b2: Bob,
b3: Bob,
s1: Spring,
s2: Spring,
s3: Spring,
}
fn model(app: &App) -> Model {
app.new_window()
.size(640, 360)
.view(view)
.mouse_pressed(mouse_pressed)
.mouse_released(mouse_released)
.build()
.unwrap();
// Create objects at starting position
// Note third argument in Spring constructor is "rest length"
let win = app.window_rect();
Model {
b1: Bob::new(0.0, win.top() - 100.0),
b2: Bob::new(0.0, win.top() - 200.0),
b3: Bob::new(0.0, win.top() - 300.0),
s1: Spring::new(100.0),
s2: Spring::new(100.0),
s3: Spring::new(100.0),
}
}
fn update(app: &App, m: &mut Model, _update: Update) {
m.s1.update(&mut m.b1, &mut m.b2);
m.s2.update(&mut m.b2, &mut m.b3);
m.s3.update(&mut m.b1, &mut m.b3);
m.b1.update();
m.b2.update();
m.b3.update();
m.b1.drag(app.mouse.x, app.mouse.y);
}
fn view(app: &App, m: &Model, frame: Frame) {
// Begin drawing
let draw = app.draw();
draw.background().color(WHITE);
m.s1.display(&draw, &m.b1, &m.b2);
m.s2.display(&draw, &m.b2, &m.b3);
m.s3.display(&draw, &m.b1, &m.b3);
m.b1.display(&draw);
m.b2.display(&draw);
m.b3.display(&draw);
// Write the result of our drawing to the window's frame.
draw.to_frame(app, &frame).unwrap();
}
fn mouse_pressed(app: &App, m: &mut Model, _button: MouseButton) {
m.b1.clicked(app.mouse.x, app.mouse.y);
}
fn mouse_released(_app: &App, m: &mut Model, _button: MouseButton) {
m.b1.stop_dragging();
}
|
{
self.dragging = false;
}
|
identifier_body
|
3_16_exercise_springs.rs
|
// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Example 3-16: Exercise Springs
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
// Spring Type describes an anchor point that can connect to "Bob" objects via a spring
// Thank you: http://www.myphysicslab.com/spring2d.html
struct Spring {
// Rest length and spring constant
len: f32,
k: f32,
}
impl Spring {
fn new(l: f32) -> Self {
Spring { len: l, k: 0.2 }
}
// Calculate spring force
fn update(&self, a: &mut Bob, b: &mut Bob) {
// Vector pointing from anchor to bob position
let mut force = a.position - b.position;
// What is the distance
let d = force.magnitude();
// Stretch is difference between current distance and rest length
let stretch = d - self.len;
// Calculate force according to Hooke's Law
// F = k * stretch
force = force.normalize();
force *= -1.0 * self.k * stretch;
a.apply_force(force);
force *= -1.0;
b.apply_force(force);
}
fn
|
(&self, draw: &Draw, a: &Bob, b: &Bob) {
draw.line()
.start(a.position)
.end(b.position)
.color(BLACK)
.stroke_weight(2.0);
}
}
struct Bob {
position: Point2,
velocity: Vector2,
acceleration: Vector2,
mass: f32,
damping: f32,
drag_offset: Vector2,
dragging: bool,
}
impl Bob {
fn new(x: f32, y: f32) -> Self {
Bob {
position: pt2(x, y),
velocity: vec2(0.0, 0.0),
acceleration: vec2(0.0, 0.0),
mass: 12.0,
damping: 0.95, // Arbitrary damping to simulate friction / drag
drag_offset: vec2(0.0, 0.0),
dragging: false,
}
}
// Standard Euler integration
fn update(&mut self) {
self.velocity += self.acceleration;
self.velocity *= self.damping;
self.position += self.velocity;
self.acceleration *= 0.0;
}
// Newton's law: F = M * A
fn apply_force(&mut self, force: Vector2) {
let f = force / self.mass;
self.acceleration += f;
}
fn display(&self, draw: &Draw) {
let c = if self.dragging { GREY } else { DARKGREY };
draw.ellipse()
.xy(self.position)
.w_h(self.mass * 2.0, self.mass * 2.0)
.color(c)
.stroke(BLACK)
.stroke_weight(2.0);
}
// The methods below are for mouse interaction
// This checks to see if we clicked on the mover
fn clicked(&mut self, mx: f32, my: f32) {
let d = pt2(mx, my).distance(self.position);
if d < self.mass {
self.dragging = true;
self.drag_offset.x = self.position.x - mx;
self.drag_offset.y = self.position.y - my;
}
}
fn stop_dragging(&mut self) {
self.dragging = false;
}
fn drag(&mut self, mx: f32, my: f32) {
if self.dragging {
self.position.x = mx + self.drag_offset.x;
self.position.y = my - self.drag_offset.y;
}
}
}
struct Model {
b1: Bob,
b2: Bob,
b3: Bob,
s1: Spring,
s2: Spring,
s3: Spring,
}
fn model(app: &App) -> Model {
app.new_window()
.size(640, 360)
.view(view)
.mouse_pressed(mouse_pressed)
.mouse_released(mouse_released)
.build()
.unwrap();
// Create objects at starting position
// Note third argument in Spring constructor is "rest length"
let win = app.window_rect();
Model {
b1: Bob::new(0.0, win.top() - 100.0),
b2: Bob::new(0.0, win.top() - 200.0),
b3: Bob::new(0.0, win.top() - 300.0),
s1: Spring::new(100.0),
s2: Spring::new(100.0),
s3: Spring::new(100.0),
}
}
fn update(app: &App, m: &mut Model, _update: Update) {
m.s1.update(&mut m.b1, &mut m.b2);
m.s2.update(&mut m.b2, &mut m.b3);
m.s3.update(&mut m.b1, &mut m.b3);
m.b1.update();
m.b2.update();
m.b3.update();
m.b1.drag(app.mouse.x, app.mouse.y);
}
fn view(app: &App, m: &Model, frame: Frame) {
// Begin drawing
let draw = app.draw();
draw.background().color(WHITE);
m.s1.display(&draw, &m.b1, &m.b2);
m.s2.display(&draw, &m.b2, &m.b3);
m.s3.display(&draw, &m.b1, &m.b3);
m.b1.display(&draw);
m.b2.display(&draw);
m.b3.display(&draw);
// Write the result of our drawing to the window's frame.
draw.to_frame(app, &frame).unwrap();
}
fn mouse_pressed(app: &App, m: &mut Model, _button: MouseButton) {
m.b1.clicked(app.mouse.x, app.mouse.y);
}
fn mouse_released(_app: &App, m: &mut Model, _button: MouseButton) {
m.b1.stop_dragging();
}
|
display
|
identifier_name
|
3_16_exercise_springs.rs
|
// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
|
// Example 3-16: Exercise Springs
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
// Spring Type describes an anchor point that can connect to "Bob" objects via a spring
// Thank you: http://www.myphysicslab.com/spring2d.html
struct Spring {
// Rest length and spring constant
len: f32,
k: f32,
}
impl Spring {
fn new(l: f32) -> Self {
Spring { len: l, k: 0.2 }
}
// Calculate spring force
fn update(&self, a: &mut Bob, b: &mut Bob) {
// Vector pointing from anchor to bob position
let mut force = a.position - b.position;
// What is the distance
let d = force.magnitude();
// Stretch is difference between current distance and rest length
let stretch = d - self.len;
// Calculate force according to Hooke's Law
// F = k * stretch
force = force.normalize();
force *= -1.0 * self.k * stretch;
a.apply_force(force);
force *= -1.0;
b.apply_force(force);
}
fn display(&self, draw: &Draw, a: &Bob, b: &Bob) {
draw.line()
.start(a.position)
.end(b.position)
.color(BLACK)
.stroke_weight(2.0);
}
}
struct Bob {
position: Point2,
velocity: Vector2,
acceleration: Vector2,
mass: f32,
damping: f32,
drag_offset: Vector2,
dragging: bool,
}
impl Bob {
fn new(x: f32, y: f32) -> Self {
Bob {
position: pt2(x, y),
velocity: vec2(0.0, 0.0),
acceleration: vec2(0.0, 0.0),
mass: 12.0,
damping: 0.95, // Arbitrary damping to simulate friction / drag
drag_offset: vec2(0.0, 0.0),
dragging: false,
}
}
// Standard Euler integration
fn update(&mut self) {
self.velocity += self.acceleration;
self.velocity *= self.damping;
self.position += self.velocity;
self.acceleration *= 0.0;
}
// Newton's law: F = M * A
fn apply_force(&mut self, force: Vector2) {
let f = force / self.mass;
self.acceleration += f;
}
fn display(&self, draw: &Draw) {
let c = if self.dragging { GREY } else { DARKGREY };
draw.ellipse()
.xy(self.position)
.w_h(self.mass * 2.0, self.mass * 2.0)
.color(c)
.stroke(BLACK)
.stroke_weight(2.0);
}
// The methods below are for mouse interaction
// This checks to see if we clicked on the mover
fn clicked(&mut self, mx: f32, my: f32) {
let d = pt2(mx, my).distance(self.position);
if d < self.mass {
self.dragging = true;
self.drag_offset.x = self.position.x - mx;
self.drag_offset.y = self.position.y - my;
}
}
fn stop_dragging(&mut self) {
self.dragging = false;
}
fn drag(&mut self, mx: f32, my: f32) {
if self.dragging {
self.position.x = mx + self.drag_offset.x;
self.position.y = my - self.drag_offset.y;
}
}
}
struct Model {
b1: Bob,
b2: Bob,
b3: Bob,
s1: Spring,
s2: Spring,
s3: Spring,
}
fn model(app: &App) -> Model {
app.new_window()
.size(640, 360)
.view(view)
.mouse_pressed(mouse_pressed)
.mouse_released(mouse_released)
.build()
.unwrap();
// Create objects at starting position
// Note third argument in Spring constructor is "rest length"
let win = app.window_rect();
Model {
b1: Bob::new(0.0, win.top() - 100.0),
b2: Bob::new(0.0, win.top() - 200.0),
b3: Bob::new(0.0, win.top() - 300.0),
s1: Spring::new(100.0),
s2: Spring::new(100.0),
s3: Spring::new(100.0),
}
}
fn update(app: &App, m: &mut Model, _update: Update) {
m.s1.update(&mut m.b1, &mut m.b2);
m.s2.update(&mut m.b2, &mut m.b3);
m.s3.update(&mut m.b1, &mut m.b3);
m.b1.update();
m.b2.update();
m.b3.update();
m.b1.drag(app.mouse.x, app.mouse.y);
}
fn view(app: &App, m: &Model, frame: Frame) {
// Begin drawing
let draw = app.draw();
draw.background().color(WHITE);
m.s1.display(&draw, &m.b1, &m.b2);
m.s2.display(&draw, &m.b2, &m.b3);
m.s3.display(&draw, &m.b1, &m.b3);
m.b1.display(&draw);
m.b2.display(&draw);
m.b3.display(&draw);
// Write the result of our drawing to the window's frame.
draw.to_frame(app, &frame).unwrap();
}
fn mouse_pressed(app: &App, m: &mut Model, _button: MouseButton) {
m.b1.clicked(app.mouse.x, app.mouse.y);
}
fn mouse_released(_app: &App, m: &mut Model, _button: MouseButton) {
m.b1.stop_dragging();
}
|
//
|
random_line_split
|
3_16_exercise_springs.rs
|
// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com
//
// Example 3-16: Exercise Springs
use nannou::prelude::*;
fn main() {
nannou::app(model).update(update).run();
}
// Spring Type describes an anchor point that can connect to "Bob" objects via a spring
// Thank you: http://www.myphysicslab.com/spring2d.html
struct Spring {
// Rest length and spring constant
len: f32,
k: f32,
}
impl Spring {
fn new(l: f32) -> Self {
Spring { len: l, k: 0.2 }
}
// Calculate spring force
fn update(&self, a: &mut Bob, b: &mut Bob) {
// Vector pointing from anchor to bob position
let mut force = a.position - b.position;
// What is the distance
let d = force.magnitude();
// Stretch is difference between current distance and rest length
let stretch = d - self.len;
// Calculate force according to Hooke's Law
// F = k * stretch
force = force.normalize();
force *= -1.0 * self.k * stretch;
a.apply_force(force);
force *= -1.0;
b.apply_force(force);
}
fn display(&self, draw: &Draw, a: &Bob, b: &Bob) {
draw.line()
.start(a.position)
.end(b.position)
.color(BLACK)
.stroke_weight(2.0);
}
}
struct Bob {
position: Point2,
velocity: Vector2,
acceleration: Vector2,
mass: f32,
damping: f32,
drag_offset: Vector2,
dragging: bool,
}
impl Bob {
fn new(x: f32, y: f32) -> Self {
Bob {
position: pt2(x, y),
velocity: vec2(0.0, 0.0),
acceleration: vec2(0.0, 0.0),
mass: 12.0,
damping: 0.95, // Arbitrary damping to simulate friction / drag
drag_offset: vec2(0.0, 0.0),
dragging: false,
}
}
// Standard Euler integration
fn update(&mut self) {
self.velocity += self.acceleration;
self.velocity *= self.damping;
self.position += self.velocity;
self.acceleration *= 0.0;
}
// Newton's law: F = M * A
fn apply_force(&mut self, force: Vector2) {
let f = force / self.mass;
self.acceleration += f;
}
fn display(&self, draw: &Draw) {
let c = if self.dragging { GREY } else { DARKGREY };
draw.ellipse()
.xy(self.position)
.w_h(self.mass * 2.0, self.mass * 2.0)
.color(c)
.stroke(BLACK)
.stroke_weight(2.0);
}
// The methods below are for mouse interaction
// This checks to see if we clicked on the mover
fn clicked(&mut self, mx: f32, my: f32) {
let d = pt2(mx, my).distance(self.position);
if d < self.mass
|
}
fn stop_dragging(&mut self) {
self.dragging = false;
}
fn drag(&mut self, mx: f32, my: f32) {
if self.dragging {
self.position.x = mx + self.drag_offset.x;
self.position.y = my - self.drag_offset.y;
}
}
}
struct Model {
b1: Bob,
b2: Bob,
b3: Bob,
s1: Spring,
s2: Spring,
s3: Spring,
}
fn model(app: &App) -> Model {
app.new_window()
.size(640, 360)
.view(view)
.mouse_pressed(mouse_pressed)
.mouse_released(mouse_released)
.build()
.unwrap();
// Create objects at starting position
// Note third argument in Spring constructor is "rest length"
let win = app.window_rect();
Model {
b1: Bob::new(0.0, win.top() - 100.0),
b2: Bob::new(0.0, win.top() - 200.0),
b3: Bob::new(0.0, win.top() - 300.0),
s1: Spring::new(100.0),
s2: Spring::new(100.0),
s3: Spring::new(100.0),
}
}
fn update(app: &App, m: &mut Model, _update: Update) {
m.s1.update(&mut m.b1, &mut m.b2);
m.s2.update(&mut m.b2, &mut m.b3);
m.s3.update(&mut m.b1, &mut m.b3);
m.b1.update();
m.b2.update();
m.b3.update();
m.b1.drag(app.mouse.x, app.mouse.y);
}
fn view(app: &App, m: &Model, frame: Frame) {
// Begin drawing
let draw = app.draw();
draw.background().color(WHITE);
m.s1.display(&draw, &m.b1, &m.b2);
m.s2.display(&draw, &m.b2, &m.b3);
m.s3.display(&draw, &m.b1, &m.b3);
m.b1.display(&draw);
m.b2.display(&draw);
m.b3.display(&draw);
// Write the result of our drawing to the window's frame.
draw.to_frame(app, &frame).unwrap();
}
fn mouse_pressed(app: &App, m: &mut Model, _button: MouseButton) {
m.b1.clicked(app.mouse.x, app.mouse.y);
}
fn mouse_released(_app: &App, m: &mut Model, _button: MouseButton) {
m.b1.stop_dragging();
}
|
{
self.dragging = true;
self.drag_offset.x = self.position.x - mx;
self.drag_offset.y = self.position.y - my;
}
|
conditional_block
|
auth.rs
|
use std::os;
pub enum Credentials {
BasicCredentials(String, String)
}
impl<'r> Credentials {
pub fn aws_access_key_id(&'r self) -> &'r str {
match *self {
BasicCredentials(ref key, _) => key.as_slice()
}
}
pub fn aws_secret_access_key(&'r self) -> &'r str {
match *self {
BasicCredentials(_, ref secret) => secret.as_slice()
}
}
}
pub trait CredentialsProvider {
fn get_credentials(&mut self) -> Result<Credentials,String>;
}
pub struct DefaultCredentialsProvider;
impl CredentialsProvider for DefaultCredentialsProvider {
fn get_credentials(&mut self) -> Result<Credentials,String>
|
}
|
{
match (os::getenv("AWS_ACCESS_KEY_ID"), os::getenv("AWS_SECRET_ACCESS_KEY")) {
(Some(key), Some(secret)) => Ok(BasicCredentials(key, secret)),
_ => Err("Could not find AWS credentials".to_string())
}
}
|
identifier_body
|
auth.rs
|
use std::os;
|
impl<'r> Credentials {
pub fn aws_access_key_id(&'r self) -> &'r str {
match *self {
BasicCredentials(ref key, _) => key.as_slice()
}
}
pub fn aws_secret_access_key(&'r self) -> &'r str {
match *self {
BasicCredentials(_, ref secret) => secret.as_slice()
}
}
}
pub trait CredentialsProvider {
fn get_credentials(&mut self) -> Result<Credentials,String>;
}
pub struct DefaultCredentialsProvider;
impl CredentialsProvider for DefaultCredentialsProvider {
fn get_credentials(&mut self) -> Result<Credentials,String> {
match (os::getenv("AWS_ACCESS_KEY_ID"), os::getenv("AWS_SECRET_ACCESS_KEY")) {
(Some(key), Some(secret)) => Ok(BasicCredentials(key, secret)),
_ => Err("Could not find AWS credentials".to_string())
}
}
}
|
pub enum Credentials {
BasicCredentials(String, String)
}
|
random_line_split
|
auth.rs
|
use std::os;
pub enum Credentials {
BasicCredentials(String, String)
}
impl<'r> Credentials {
pub fn aws_access_key_id(&'r self) -> &'r str {
match *self {
BasicCredentials(ref key, _) => key.as_slice()
}
}
pub fn
|
(&'r self) -> &'r str {
match *self {
BasicCredentials(_, ref secret) => secret.as_slice()
}
}
}
pub trait CredentialsProvider {
fn get_credentials(&mut self) -> Result<Credentials,String>;
}
pub struct DefaultCredentialsProvider;
impl CredentialsProvider for DefaultCredentialsProvider {
fn get_credentials(&mut self) -> Result<Credentials,String> {
match (os::getenv("AWS_ACCESS_KEY_ID"), os::getenv("AWS_SECRET_ACCESS_KEY")) {
(Some(key), Some(secret)) => Ok(BasicCredentials(key, secret)),
_ => Err("Could not find AWS credentials".to_string())
}
}
}
|
aws_secret_access_key
|
identifier_name
|
checkerboard.rs
|
use crate::noise_fns::NoiseFn;
/// Noise function that outputs a checkerboard pattern.
///
/// This noise function can take one input, size, and outputs 2<sup>size</sup>-sized
/// blocks of alternating values. The values of these blocks alternate between
/// -1.0 and 1.0.
///
/// This noise function is not very useful by itself, but it can be used for
/// debugging purposes.
#[derive(Clone, Copy, Debug)]
pub struct Checkerboard {
/// Controls the size of the block in 2^(size).
size: usize,
}
impl Checkerboard {
const DEFAULT_SIZE: usize = 0;
pub fn new(size: usize) -> Self {
Self { size: 1 << size }
}
pub fn set_size(self, size: usize) -> Self {
Self { size: 1 << size }
}
pub fn size(self) -> usize {
self.size
}
}
impl Default for Checkerboard {
fn
|
() -> Self {
Self {
size: 1 << Checkerboard::DEFAULT_SIZE,
}
}
}
// These impl's should be made generic over Point, but there is no higher Point
// type. Keep the code the same anyway.
impl NoiseFn<[f64; 2]> for Checkerboard {
fn get(&self, point: [f64; 2]) -> f64 {
calculate_checkerboard(&point, self.size)
}
}
impl NoiseFn<[f64; 3]> for Checkerboard {
fn get(&self, point: [f64; 3]) -> f64 {
calculate_checkerboard(&point, self.size)
}
}
impl NoiseFn<[f64; 4]> for Checkerboard {
fn get(&self, point: [f64; 4]) -> f64 {
calculate_checkerboard(&point, self.size)
}
}
fn calculate_checkerboard(point: &[f64], size: usize) -> f64 {
let result = point
.iter()
.map(|&a| a.floor() as usize)
.fold(0, |a, b| (a & size) ^ (b & size));
if result > 0 {
-1.0
} else {
1.0
}
}
|
default
|
identifier_name
|
checkerboard.rs
|
use crate::noise_fns::NoiseFn;
/// Noise function that outputs a checkerboard pattern.
///
/// This noise function can take one input, size, and outputs 2<sup>size</sup>-sized
/// blocks of alternating values. The values of these blocks alternate between
/// -1.0 and 1.0.
///
/// This noise function is not very useful by itself, but it can be used for
/// debugging purposes.
#[derive(Clone, Copy, Debug)]
pub struct Checkerboard {
/// Controls the size of the block in 2^(size).
size: usize,
}
impl Checkerboard {
const DEFAULT_SIZE: usize = 0;
pub fn new(size: usize) -> Self {
Self { size: 1 << size }
}
pub fn set_size(self, size: usize) -> Self {
Self { size: 1 << size }
}
pub fn size(self) -> usize {
self.size
}
}
impl Default for Checkerboard {
fn default() -> Self {
Self {
size: 1 << Checkerboard::DEFAULT_SIZE,
}
}
}
// These impl's should be made generic over Point, but there is no higher Point
// type. Keep the code the same anyway.
impl NoiseFn<[f64; 2]> for Checkerboard {
fn get(&self, point: [f64; 2]) -> f64 {
calculate_checkerboard(&point, self.size)
}
}
impl NoiseFn<[f64; 3]> for Checkerboard {
fn get(&self, point: [f64; 3]) -> f64 {
calculate_checkerboard(&point, self.size)
}
}
impl NoiseFn<[f64; 4]> for Checkerboard {
fn get(&self, point: [f64; 4]) -> f64 {
calculate_checkerboard(&point, self.size)
}
}
fn calculate_checkerboard(point: &[f64], size: usize) -> f64 {
let result = point
.iter()
.map(|&a| a.floor() as usize)
.fold(0, |a, b| (a & size) ^ (b & size));
if result > 0 {
-1.0
} else
|
}
|
{
1.0
}
|
conditional_block
|
checkerboard.rs
|
use crate::noise_fns::NoiseFn;
/// Noise function that outputs a checkerboard pattern.
///
/// This noise function can take one input, size, and outputs 2<sup>size</sup>-sized
/// blocks of alternating values. The values of these blocks alternate between
/// -1.0 and 1.0.
///
/// This noise function is not very useful by itself, but it can be used for
/// debugging purposes.
#[derive(Clone, Copy, Debug)]
pub struct Checkerboard {
/// Controls the size of the block in 2^(size).
size: usize,
}
impl Checkerboard {
const DEFAULT_SIZE: usize = 0;
pub fn new(size: usize) -> Self {
Self { size: 1 << size }
}
pub fn set_size(self, size: usize) -> Self {
Self { size: 1 << size }
}
pub fn size(self) -> usize {
self.size
}
}
impl Default for Checkerboard {
|
}
}
}
// These impl's should be made generic over Point, but there is no higher Point
// type. Keep the code the same anyway.
impl NoiseFn<[f64; 2]> for Checkerboard {
fn get(&self, point: [f64; 2]) -> f64 {
calculate_checkerboard(&point, self.size)
}
}
impl NoiseFn<[f64; 3]> for Checkerboard {
fn get(&self, point: [f64; 3]) -> f64 {
calculate_checkerboard(&point, self.size)
}
}
impl NoiseFn<[f64; 4]> for Checkerboard {
fn get(&self, point: [f64; 4]) -> f64 {
calculate_checkerboard(&point, self.size)
}
}
fn calculate_checkerboard(point: &[f64], size: usize) -> f64 {
let result = point
.iter()
.map(|&a| a.floor() as usize)
.fold(0, |a, b| (a & size) ^ (b & size));
if result > 0 {
-1.0
} else {
1.0
}
}
|
fn default() -> Self {
Self {
size: 1 << Checkerboard::DEFAULT_SIZE,
|
random_line_split
|
checkerboard.rs
|
use crate::noise_fns::NoiseFn;
/// Noise function that outputs a checkerboard pattern.
///
/// This noise function can take one input, size, and outputs 2<sup>size</sup>-sized
/// blocks of alternating values. The values of these blocks alternate between
/// -1.0 and 1.0.
///
/// This noise function is not very useful by itself, but it can be used for
/// debugging purposes.
#[derive(Clone, Copy, Debug)]
pub struct Checkerboard {
/// Controls the size of the block in 2^(size).
size: usize,
}
impl Checkerboard {
const DEFAULT_SIZE: usize = 0;
pub fn new(size: usize) -> Self {
Self { size: 1 << size }
}
pub fn set_size(self, size: usize) -> Self {
Self { size: 1 << size }
}
pub fn size(self) -> usize {
self.size
}
}
impl Default for Checkerboard {
fn default() -> Self {
Self {
size: 1 << Checkerboard::DEFAULT_SIZE,
}
}
}
// These impl's should be made generic over Point, but there is no higher Point
// type. Keep the code the same anyway.
impl NoiseFn<[f64; 2]> for Checkerboard {
fn get(&self, point: [f64; 2]) -> f64 {
calculate_checkerboard(&point, self.size)
}
}
impl NoiseFn<[f64; 3]> for Checkerboard {
fn get(&self, point: [f64; 3]) -> f64 {
calculate_checkerboard(&point, self.size)
}
}
impl NoiseFn<[f64; 4]> for Checkerboard {
fn get(&self, point: [f64; 4]) -> f64 {
calculate_checkerboard(&point, self.size)
}
}
fn calculate_checkerboard(point: &[f64], size: usize) -> f64
|
{
let result = point
.iter()
.map(|&a| a.floor() as usize)
.fold(0, |a, b| (a & size) ^ (b & size));
if result > 0 {
-1.0
} else {
1.0
}
}
|
identifier_body
|
|
tests.py
|
from __future__ import unicode_literals
from operator import attrgetter
from django.db import models
from django.test import TestCase
from .models import Answer, Dimension, Entity, Post, Question
class OrderWithRespectToTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.q1 = Question.objects.create(text="Which Beatle starts with the letter 'R'?")
Answer.objects.create(text="John", question=cls.q1)
Answer.objects.create(text="Paul", question=cls.q1)
Answer.objects.create(text="George", question=cls.q1)
Answer.objects.create(text="Ringo", question=cls.q1)
def test_default_to_insertion_order(self):
# Answers will always be ordered in the order they were inserted.
self.assertQuerysetEqual(
self.q1.answer_set.all(), [
"John", "Paul", "George", "Ringo",
],
attrgetter("text"),
)
def test_previous_and_next_in_order(self):
# We can retrieve the answers related to a particular object, in the
# order they were created, once we have a particular object.
a1 = Answer.objects.filter(question=self.q1)[0]
self.assertEqual(a1.text, "John")
self.assertEqual(a1.get_next_in_order().text, "Paul")
a2 = list(Answer.objects.filter(question=self.q1))[-1]
self.assertEqual(a2.text, "Ringo")
self.assertEqual(a2.get_previous_in_order().text, "George")
def test_item_ordering(self):
# We can retrieve the ordering of the queryset from a particular item.
a1 = Answer.objects.filter(question=self.q1)[1]
id_list = [o.pk for o in self.q1.answer_set.all()]
self.assertEqual(a1.question.get_answer_order(), id_list)
# It doesn't matter which answer we use to check the order, it will
# always be the same.
a2 = Answer.objects.create(text="Number five", question=self.q1)
self.assertEqual(
a1.question.get_answer_order(), a2.question.get_answer_order()
)
def test_change_ordering(self):
# The ordering can be altered
a = Answer.objects.create(text="Number five", question=self.q1)
# Swap the last two items in the order list
id_list = [o.pk for o in self.q1.answer_set.all()]
x = id_list.pop()
id_list.insert(-1, x)
# By default, the ordering is different from the swapped version
self.assertNotEqual(a.question.get_answer_order(), id_list)
# Change the ordering to the swapped version -
# this changes the ordering of the queryset.
a.question.set_answer_order(id_list)
self.assertQuerysetEqual(
self.q1.answer_set.all(), [
"John", "Paul", "George", "Number five", "Ringo"
],
attrgetter("text")
)
class OrderWithRespectToTests2(TestCase):
|
class TestOrderWithRespectToOneToOnePK(TestCase):
def test_set_order(self):
e = Entity.objects.create()
d = Dimension.objects.create(entity=e)
c1 = d.component_set.create()
c2 = d.component_set.create()
d.set_component_order([c1.id, c2.id])
self.assertQuerysetEqual(d.component_set.all(), [c1.id, c2.id], attrgetter('pk'))
|
def test_recursive_ordering(self):
p1 = Post.objects.create(title='1')
p2 = Post.objects.create(title='2')
p1_1 = Post.objects.create(title="1.1", parent=p1)
p1_2 = Post.objects.create(title="1.2", parent=p1)
Post.objects.create(title="2.1", parent=p2)
p1_3 = Post.objects.create(title="1.3", parent=p1)
self.assertEqual(p1.get_post_order(), [p1_1.pk, p1_2.pk, p1_3.pk])
def test_duplicate_order_field(self):
class Bar(models.Model):
pass
class Foo(models.Model):
bar = models.ForeignKey(Bar)
order = models.OrderWrt()
class Meta:
order_with_respect_to = 'bar'
count = 0
for field in Foo._meta.local_fields:
if isinstance(field, models.OrderWrt):
count += 1
self.assertEqual(count, 1)
|
identifier_body
|
tests.py
|
from __future__ import unicode_literals
from operator import attrgetter
from django.db import models
from django.test import TestCase
from .models import Answer, Dimension, Entity, Post, Question
class OrderWithRespectToTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.q1 = Question.objects.create(text="Which Beatle starts with the letter 'R'?")
Answer.objects.create(text="John", question=cls.q1)
Answer.objects.create(text="Paul", question=cls.q1)
Answer.objects.create(text="George", question=cls.q1)
Answer.objects.create(text="Ringo", question=cls.q1)
def test_default_to_insertion_order(self):
# Answers will always be ordered in the order they were inserted.
self.assertQuerysetEqual(
self.q1.answer_set.all(), [
"John", "Paul", "George", "Ringo",
],
attrgetter("text"),
)
def test_previous_and_next_in_order(self):
# We can retrieve the answers related to a particular object, in the
# order they were created, once we have a particular object.
a1 = Answer.objects.filter(question=self.q1)[0]
self.assertEqual(a1.text, "John")
self.assertEqual(a1.get_next_in_order().text, "Paul")
a2 = list(Answer.objects.filter(question=self.q1))[-1]
self.assertEqual(a2.text, "Ringo")
self.assertEqual(a2.get_previous_in_order().text, "George")
def test_item_ordering(self):
# We can retrieve the ordering of the queryset from a particular item.
a1 = Answer.objects.filter(question=self.q1)[1]
id_list = [o.pk for o in self.q1.answer_set.all()]
self.assertEqual(a1.question.get_answer_order(), id_list)
# It doesn't matter which answer we use to check the order, it will
# always be the same.
a2 = Answer.objects.create(text="Number five", question=self.q1)
self.assertEqual(
a1.question.get_answer_order(), a2.question.get_answer_order()
)
def test_change_ordering(self):
# The ordering can be altered
a = Answer.objects.create(text="Number five", question=self.q1)
# Swap the last two items in the order list
id_list = [o.pk for o in self.q1.answer_set.all()]
x = id_list.pop()
id_list.insert(-1, x)
# By default, the ordering is different from the swapped version
self.assertNotEqual(a.question.get_answer_order(), id_list)
# Change the ordering to the swapped version -
# this changes the ordering of the queryset.
a.question.set_answer_order(id_list)
self.assertQuerysetEqual(
self.q1.answer_set.all(), [
"John", "Paul", "George", "Number five", "Ringo"
],
attrgetter("text")
)
class OrderWithRespectToTests2(TestCase):
def test_recursive_ordering(self):
p1 = Post.objects.create(title='1')
p2 = Post.objects.create(title='2')
p1_1 = Post.objects.create(title="1.1", parent=p1)
p1_2 = Post.objects.create(title="1.2", parent=p1)
Post.objects.create(title="2.1", parent=p2)
p1_3 = Post.objects.create(title="1.3", parent=p1)
self.assertEqual(p1.get_post_order(), [p1_1.pk, p1_2.pk, p1_3.pk])
def test_duplicate_order_field(self):
class Bar(models.Model):
pass
class Foo(models.Model):
bar = models.ForeignKey(Bar)
order = models.OrderWrt()
class Meta:
order_with_respect_to = 'bar'
count = 0
for field in Foo._meta.local_fields:
if isinstance(field, models.OrderWrt):
|
self.assertEqual(count, 1)
class TestOrderWithRespectToOneToOnePK(TestCase):
def test_set_order(self):
e = Entity.objects.create()
d = Dimension.objects.create(entity=e)
c1 = d.component_set.create()
c2 = d.component_set.create()
d.set_component_order([c1.id, c2.id])
self.assertQuerysetEqual(d.component_set.all(), [c1.id, c2.id], attrgetter('pk'))
|
count += 1
|
conditional_block
|
tests.py
|
from __future__ import unicode_literals
from operator import attrgetter
from django.db import models
from django.test import TestCase
from .models import Answer, Dimension, Entity, Post, Question
class OrderWithRespectToTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.q1 = Question.objects.create(text="Which Beatle starts with the letter 'R'?")
Answer.objects.create(text="John", question=cls.q1)
Answer.objects.create(text="Paul", question=cls.q1)
Answer.objects.create(text="George", question=cls.q1)
Answer.objects.create(text="Ringo", question=cls.q1)
def test_default_to_insertion_order(self):
# Answers will always be ordered in the order they were inserted.
self.assertQuerysetEqual(
self.q1.answer_set.all(), [
"John", "Paul", "George", "Ringo",
],
attrgetter("text"),
)
def test_previous_and_next_in_order(self):
# We can retrieve the answers related to a particular object, in the
# order they were created, once we have a particular object.
a1 = Answer.objects.filter(question=self.q1)[0]
self.assertEqual(a1.text, "John")
self.assertEqual(a1.get_next_in_order().text, "Paul")
a2 = list(Answer.objects.filter(question=self.q1))[-1]
self.assertEqual(a2.text, "Ringo")
self.assertEqual(a2.get_previous_in_order().text, "George")
def test_item_ordering(self):
# We can retrieve the ordering of the queryset from a particular item.
a1 = Answer.objects.filter(question=self.q1)[1]
id_list = [o.pk for o in self.q1.answer_set.all()]
self.assertEqual(a1.question.get_answer_order(), id_list)
# It doesn't matter which answer we use to check the order, it will
# always be the same.
a2 = Answer.objects.create(text="Number five", question=self.q1)
self.assertEqual(
a1.question.get_answer_order(), a2.question.get_answer_order()
)
def test_change_ordering(self):
# The ordering can be altered
a = Answer.objects.create(text="Number five", question=self.q1)
# Swap the last two items in the order list
id_list = [o.pk for o in self.q1.answer_set.all()]
x = id_list.pop()
id_list.insert(-1, x)
# By default, the ordering is different from the swapped version
self.assertNotEqual(a.question.get_answer_order(), id_list)
# Change the ordering to the swapped version -
# this changes the ordering of the queryset.
a.question.set_answer_order(id_list)
self.assertQuerysetEqual(
self.q1.answer_set.all(), [
"John", "Paul", "George", "Number five", "Ringo"
|
attrgetter("text")
)
class OrderWithRespectToTests2(TestCase):
def test_recursive_ordering(self):
p1 = Post.objects.create(title='1')
p2 = Post.objects.create(title='2')
p1_1 = Post.objects.create(title="1.1", parent=p1)
p1_2 = Post.objects.create(title="1.2", parent=p1)
Post.objects.create(title="2.1", parent=p2)
p1_3 = Post.objects.create(title="1.3", parent=p1)
self.assertEqual(p1.get_post_order(), [p1_1.pk, p1_2.pk, p1_3.pk])
def test_duplicate_order_field(self):
class Bar(models.Model):
pass
class Foo(models.Model):
bar = models.ForeignKey(Bar)
order = models.OrderWrt()
class Meta:
order_with_respect_to = 'bar'
count = 0
for field in Foo._meta.local_fields:
if isinstance(field, models.OrderWrt):
count += 1
self.assertEqual(count, 1)
class TestOrderWithRespectToOneToOnePK(TestCase):
def test_set_order(self):
e = Entity.objects.create()
d = Dimension.objects.create(entity=e)
c1 = d.component_set.create()
c2 = d.component_set.create()
d.set_component_order([c1.id, c2.id])
self.assertQuerysetEqual(d.component_set.all(), [c1.id, c2.id], attrgetter('pk'))
|
],
|
random_line_split
|
tests.py
|
from __future__ import unicode_literals
from operator import attrgetter
from django.db import models
from django.test import TestCase
from .models import Answer, Dimension, Entity, Post, Question
class OrderWithRespectToTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.q1 = Question.objects.create(text="Which Beatle starts with the letter 'R'?")
Answer.objects.create(text="John", question=cls.q1)
Answer.objects.create(text="Paul", question=cls.q1)
Answer.objects.create(text="George", question=cls.q1)
Answer.objects.create(text="Ringo", question=cls.q1)
def test_default_to_insertion_order(self):
# Answers will always be ordered in the order they were inserted.
self.assertQuerysetEqual(
self.q1.answer_set.all(), [
"John", "Paul", "George", "Ringo",
],
attrgetter("text"),
)
def test_previous_and_next_in_order(self):
# We can retrieve the answers related to a particular object, in the
# order they were created, once we have a particular object.
a1 = Answer.objects.filter(question=self.q1)[0]
self.assertEqual(a1.text, "John")
self.assertEqual(a1.get_next_in_order().text, "Paul")
a2 = list(Answer.objects.filter(question=self.q1))[-1]
self.assertEqual(a2.text, "Ringo")
self.assertEqual(a2.get_previous_in_order().text, "George")
def test_item_ordering(self):
# We can retrieve the ordering of the queryset from a particular item.
a1 = Answer.objects.filter(question=self.q1)[1]
id_list = [o.pk for o in self.q1.answer_set.all()]
self.assertEqual(a1.question.get_answer_order(), id_list)
# It doesn't matter which answer we use to check the order, it will
# always be the same.
a2 = Answer.objects.create(text="Number five", question=self.q1)
self.assertEqual(
a1.question.get_answer_order(), a2.question.get_answer_order()
)
def test_change_ordering(self):
# The ordering can be altered
a = Answer.objects.create(text="Number five", question=self.q1)
# Swap the last two items in the order list
id_list = [o.pk for o in self.q1.answer_set.all()]
x = id_list.pop()
id_list.insert(-1, x)
# By default, the ordering is different from the swapped version
self.assertNotEqual(a.question.get_answer_order(), id_list)
# Change the ordering to the swapped version -
# this changes the ordering of the queryset.
a.question.set_answer_order(id_list)
self.assertQuerysetEqual(
self.q1.answer_set.all(), [
"John", "Paul", "George", "Number five", "Ringo"
],
attrgetter("text")
)
class OrderWithRespectToTests2(TestCase):
def test_recursive_ordering(self):
p1 = Post.objects.create(title='1')
p2 = Post.objects.create(title='2')
p1_1 = Post.objects.create(title="1.1", parent=p1)
p1_2 = Post.objects.create(title="1.2", parent=p1)
Post.objects.create(title="2.1", parent=p2)
p1_3 = Post.objects.create(title="1.3", parent=p1)
self.assertEqual(p1.get_post_order(), [p1_1.pk, p1_2.pk, p1_3.pk])
def
|
(self):
class Bar(models.Model):
pass
class Foo(models.Model):
bar = models.ForeignKey(Bar)
order = models.OrderWrt()
class Meta:
order_with_respect_to = 'bar'
count = 0
for field in Foo._meta.local_fields:
if isinstance(field, models.OrderWrt):
count += 1
self.assertEqual(count, 1)
class TestOrderWithRespectToOneToOnePK(TestCase):
def test_set_order(self):
e = Entity.objects.create()
d = Dimension.objects.create(entity=e)
c1 = d.component_set.create()
c2 = d.component_set.create()
d.set_component_order([c1.id, c2.id])
self.assertQuerysetEqual(d.component_set.all(), [c1.id, c2.id], attrgetter('pk'))
|
test_duplicate_order_field
|
identifier_name
|
currencyConversion.js
|
//currency conversion class for handling all currency conversion operations
var CurrencyConverter = (function () {
function CurrencyConverter()
|
CurrencyConverter.prototype.CurrencyConverter = function () {
};
//sets the currencies
CurrencyConverter.prototype.setCurrencies = function (currencyFrom, currencyTo) {
if (this.checkCurrencies(currencyFrom, currencyTo)) {
this.currencyFrom = currencyFrom;
this.currencyTo = currencyTo;
return true;
}
else {
return false;
}
};
//does a check to see if the currencies entered are valid
CurrencyConverter.prototype.checkCurrencies = function (currencyFrom, currencyTo) {
var currencyFromValid;
var currencyToValid;
var currencies = ["AUD", "BGN", "BRL", "CAD",
"CHF", "CNY", "CZK", "DKK",
"EUR", "GBP", "HKD", "HRK",
"HUF", "IDR", "ILS", "INR",
"JPY", "KRW", "MXN", "MYR",
"NOK", "NZD", "PHP", "PLN",
"RON", "RUB", "SEK", "SGD",
"THB", "TRY", "USD", "ZAR"];
if (currencies.indexOf(currencyFrom) != -1) {
currencyFromValid = true;
}
else {
currencyFromValid = false;
}
if (currencies.indexOf(currencyTo) != -1) {
currencyToValid = true;
}
else {
currencyToValid = false;
}
return currencyFromValid && currencyToValid;
};
//sets the amount of currency to be converted
CurrencyConverter.prototype.setAmount = function (amount) {
this.currencyAmount = amount;
};
//Performs asynchronous api call to fixxer, with a dynamic call based on the currencies entered by the user
CurrencyConverter.prototype.getRates = function (callback) {
var settings = {
async: true,
crossDomain: true,
url: "http://api.fixer.io/latest?symbols={1}%2C{2}".replace("{1}", this.currencyFrom).replace("{2}", this.currencyTo),
method: "GET"
};
$.ajax(settings).done(function (response) {
callback(response);
}).fail(function (response) {
this.failMessage();
});
};
//performs the conversion calculation
CurrencyConverter.prototype.calculate = function (data) {
if (this.currencyFrom == "EUR") {
this.currencyFromValue = 1;
this.currencyToValue = Number(data["rates"][this.currencyTo]);
this.currencyRatio = this.currencyToValue / this.currencyFromValue;
this.finalResult = String((Number(this.currencyAmount) * this.currencyRatio).toFixed(2));
return;
}
if (this.currencyTo == "EUR") {
this.currencyFromValue = Number(data["rates"][this.currencyFrom]);
this.currencyToValue = 1;
this.currencyRatio = this.currencyToValue / this.currencyFromValue;
this.finalResult = String((Number(this.currencyAmount) * this.currencyRatio).toFixed(2));
return;
}
if (!this.giveError) {
this.currencyFromValue = Number(data["rates"][this.currencyFrom]);
this.currencyToValue = Number(data["rates"][this.currencyTo]);
this.currencyRatio = this.currencyToValue / this.currencyFromValue;
this.finalResult = String((Number(this.currencyAmount) * this.currencyRatio).toFixed(2));
}
};
//updates the dom with the result
CurrencyConverter.prototype.returnResult = function () {
var message;
message = "{0} {1} in {2} is {3} at a rate of {4}"
.replace("{0}", this.currencyAmount)
.replace("{1}", this.currencyFrom)
.replace("{2}", this.currencyTo)
.replace("{3}", this.finalResult)
.replace("{4}", String(this.currencyRatio.toFixed(2)));
$("#resultBtn").text(message);
};
//if something is wrong, will update the dom with the error
CurrencyConverter.prototype.failMessage = function () {
var message;
message = "One or more of the currency Codes is Incorrect";
$("#resultBtn").text(message);
};
return CurrencyConverter;
}());
//eventlistener function which chains all of the calls and calculations together
function convertCurrency() {
//Get the dom elements
var currencyFrom = $("#currencyFrom").val().toUpperCase();
var currencyTo = $("#currencyTo").val().toUpperCase();
var currencyAmount = $("#currencyAmount").val();
//create currency converter object
var currencyConverter = new CurrencyConverter();
//performs api calls, if false. then error occured
var incorrectCurrencies = currencyConverter.setCurrencies(currencyFrom, currencyTo);
if (!incorrectCurrencies) {
currencyConverter.failMessage();
return;
}
currencyConverter.setAmount(currencyAmount);
currencyConverter.getRates(function (data) {
currencyConverter.calculate(data);
currencyConverter.returnResult();
});
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//sweet alert messages
function showCurrencies() {
swal({
title: "Available currency codes:",
text: "AUD: Australian Dollar\nBGN: Bulgarian Vel\nBRL: Brazilian Real\nCAD: Canadian Dollar\nCHF: Swiss Franc\nCNY: Chinese Yuan\nCZK: Czech Koruna\nDKK: Danish Krone\nGBP: British Pound\nHKD: Hong Kong Dollar\nHRK: Croatian Kuna\nHUF: Hungarian Forint\nIDR: Indonesian Rupiah\nILS: Israeli New Sheqel\nINR: Indian Rupee\nJPY: Japanese Yen\nKRW: South Korean Won\nMXN: Mexican Peso\nMYR: Malaysian Ringgit\nNOK: Norwegian Krone\nNZD: New Zealand Dollar\nPHP: Philippine Peso\nPLN: Polish Zloty\nRON: Romanian Leu\nRUB: Russian Ruble\nSEK: Swedish Krone\nSGD: Singapore Dollar\nTHB: Thai Baht\nTRY: Turkish Lira\nUSD: United States Dollar\nZAR: South African Rand",
type: "info",
confirmButtonText: "Return" });
}
function showAuthor() {
swal({
title: "About the Author",
text: "Author: Stanislav Pankrashin\nA student at the University of Auckland who is studying computer science\n",
type: "info",
confirmButtonText: "Return"
});
}
function showInfo() {
swal({
title: "About the Website",
text: "Powered by Fixxer.io\nThis website was made for the purposes of the microsoft student accelorator\nit is not intended to be monetised or used for monetary gain\n",
type: "info",
confirmButtonText: "Return"
});
}
|
{
this.giveError = false;
}
|
identifier_body
|
currencyConversion.js
|
//currency conversion class for handling all currency conversion operations
var CurrencyConverter = (function () {
function
|
() {
this.giveError = false;
}
CurrencyConverter.prototype.CurrencyConverter = function () {
};
//sets the currencies
CurrencyConverter.prototype.setCurrencies = function (currencyFrom, currencyTo) {
if (this.checkCurrencies(currencyFrom, currencyTo)) {
this.currencyFrom = currencyFrom;
this.currencyTo = currencyTo;
return true;
}
else {
return false;
}
};
//does a check to see if the currencies entered are valid
CurrencyConverter.prototype.checkCurrencies = function (currencyFrom, currencyTo) {
var currencyFromValid;
var currencyToValid;
var currencies = ["AUD", "BGN", "BRL", "CAD",
"CHF", "CNY", "CZK", "DKK",
"EUR", "GBP", "HKD", "HRK",
"HUF", "IDR", "ILS", "INR",
"JPY", "KRW", "MXN", "MYR",
"NOK", "NZD", "PHP", "PLN",
"RON", "RUB", "SEK", "SGD",
"THB", "TRY", "USD", "ZAR"];
if (currencies.indexOf(currencyFrom) != -1) {
currencyFromValid = true;
}
else {
currencyFromValid = false;
}
if (currencies.indexOf(currencyTo) != -1) {
currencyToValid = true;
}
else {
currencyToValid = false;
}
return currencyFromValid && currencyToValid;
};
//sets the amount of currency to be converted
CurrencyConverter.prototype.setAmount = function (amount) {
this.currencyAmount = amount;
};
//Performs asynchronous api call to fixxer, with a dynamic call based on the currencies entered by the user
CurrencyConverter.prototype.getRates = function (callback) {
var settings = {
async: true,
crossDomain: true,
url: "http://api.fixer.io/latest?symbols={1}%2C{2}".replace("{1}", this.currencyFrom).replace("{2}", this.currencyTo),
method: "GET"
};
$.ajax(settings).done(function (response) {
callback(response);
}).fail(function (response) {
this.failMessage();
});
};
//performs the conversion calculation
CurrencyConverter.prototype.calculate = function (data) {
if (this.currencyFrom == "EUR") {
this.currencyFromValue = 1;
this.currencyToValue = Number(data["rates"][this.currencyTo]);
this.currencyRatio = this.currencyToValue / this.currencyFromValue;
this.finalResult = String((Number(this.currencyAmount) * this.currencyRatio).toFixed(2));
return;
}
if (this.currencyTo == "EUR") {
this.currencyFromValue = Number(data["rates"][this.currencyFrom]);
this.currencyToValue = 1;
this.currencyRatio = this.currencyToValue / this.currencyFromValue;
this.finalResult = String((Number(this.currencyAmount) * this.currencyRatio).toFixed(2));
return;
}
if (!this.giveError) {
this.currencyFromValue = Number(data["rates"][this.currencyFrom]);
this.currencyToValue = Number(data["rates"][this.currencyTo]);
this.currencyRatio = this.currencyToValue / this.currencyFromValue;
this.finalResult = String((Number(this.currencyAmount) * this.currencyRatio).toFixed(2));
}
};
//updates the dom with the result
CurrencyConverter.prototype.returnResult = function () {
var message;
message = "{0} {1} in {2} is {3} at a rate of {4}"
.replace("{0}", this.currencyAmount)
.replace("{1}", this.currencyFrom)
.replace("{2}", this.currencyTo)
.replace("{3}", this.finalResult)
.replace("{4}", String(this.currencyRatio.toFixed(2)));
$("#resultBtn").text(message);
};
//if something is wrong, will update the dom with the error
CurrencyConverter.prototype.failMessage = function () {
var message;
message = "One or more of the currency Codes is Incorrect";
$("#resultBtn").text(message);
};
return CurrencyConverter;
}());
//eventlistener function which chains all of the calls and calculations together
function convertCurrency() {
//Get the dom elements
var currencyFrom = $("#currencyFrom").val().toUpperCase();
var currencyTo = $("#currencyTo").val().toUpperCase();
var currencyAmount = $("#currencyAmount").val();
//create currency converter object
var currencyConverter = new CurrencyConverter();
//performs api calls, if false. then error occured
var incorrectCurrencies = currencyConverter.setCurrencies(currencyFrom, currencyTo);
if (!incorrectCurrencies) {
currencyConverter.failMessage();
return;
}
currencyConverter.setAmount(currencyAmount);
currencyConverter.getRates(function (data) {
currencyConverter.calculate(data);
currencyConverter.returnResult();
});
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//sweet alert messages
function showCurrencies() {
swal({
title: "Available currency codes:",
text: "AUD: Australian Dollar\nBGN: Bulgarian Vel\nBRL: Brazilian Real\nCAD: Canadian Dollar\nCHF: Swiss Franc\nCNY: Chinese Yuan\nCZK: Czech Koruna\nDKK: Danish Krone\nGBP: British Pound\nHKD: Hong Kong Dollar\nHRK: Croatian Kuna\nHUF: Hungarian Forint\nIDR: Indonesian Rupiah\nILS: Israeli New Sheqel\nINR: Indian Rupee\nJPY: Japanese Yen\nKRW: South Korean Won\nMXN: Mexican Peso\nMYR: Malaysian Ringgit\nNOK: Norwegian Krone\nNZD: New Zealand Dollar\nPHP: Philippine Peso\nPLN: Polish Zloty\nRON: Romanian Leu\nRUB: Russian Ruble\nSEK: Swedish Krone\nSGD: Singapore Dollar\nTHB: Thai Baht\nTRY: Turkish Lira\nUSD: United States Dollar\nZAR: South African Rand",
type: "info",
confirmButtonText: "Return" });
}
function showAuthor() {
swal({
title: "About the Author",
text: "Author: Stanislav Pankrashin\nA student at the University of Auckland who is studying computer science\n",
type: "info",
confirmButtonText: "Return"
});
}
function showInfo() {
swal({
title: "About the Website",
text: "Powered by Fixxer.io\nThis website was made for the purposes of the microsoft student accelorator\nit is not intended to be monetised or used for monetary gain\n",
type: "info",
confirmButtonText: "Return"
});
}
|
CurrencyConverter
|
identifier_name
|
currencyConversion.js
|
//currency conversion class for handling all currency conversion operations
var CurrencyConverter = (function () {
function CurrencyConverter() {
this.giveError = false;
}
CurrencyConverter.prototype.CurrencyConverter = function () {
};
//sets the currencies
CurrencyConverter.prototype.setCurrencies = function (currencyFrom, currencyTo) {
if (this.checkCurrencies(currencyFrom, currencyTo)) {
this.currencyFrom = currencyFrom;
this.currencyTo = currencyTo;
return true;
}
else {
return false;
}
};
//does a check to see if the currencies entered are valid
CurrencyConverter.prototype.checkCurrencies = function (currencyFrom, currencyTo) {
var currencyFromValid;
var currencyToValid;
var currencies = ["AUD", "BGN", "BRL", "CAD",
"CHF", "CNY", "CZK", "DKK",
"EUR", "GBP", "HKD", "HRK",
"HUF", "IDR", "ILS", "INR",
"JPY", "KRW", "MXN", "MYR",
"NOK", "NZD", "PHP", "PLN",
"RON", "RUB", "SEK", "SGD",
"THB", "TRY", "USD", "ZAR"];
if (currencies.indexOf(currencyFrom) != -1) {
currencyFromValid = true;
}
else
|
if (currencies.indexOf(currencyTo) != -1) {
currencyToValid = true;
}
else {
currencyToValid = false;
}
return currencyFromValid && currencyToValid;
};
//sets the amount of currency to be converted
CurrencyConverter.prototype.setAmount = function (amount) {
this.currencyAmount = amount;
};
//Performs asynchronous api call to fixxer, with a dynamic call based on the currencies entered by the user
CurrencyConverter.prototype.getRates = function (callback) {
var settings = {
async: true,
crossDomain: true,
url: "http://api.fixer.io/latest?symbols={1}%2C{2}".replace("{1}", this.currencyFrom).replace("{2}", this.currencyTo),
method: "GET"
};
$.ajax(settings).done(function (response) {
callback(response);
}).fail(function (response) {
this.failMessage();
});
};
//performs the conversion calculation
CurrencyConverter.prototype.calculate = function (data) {
if (this.currencyFrom == "EUR") {
this.currencyFromValue = 1;
this.currencyToValue = Number(data["rates"][this.currencyTo]);
this.currencyRatio = this.currencyToValue / this.currencyFromValue;
this.finalResult = String((Number(this.currencyAmount) * this.currencyRatio).toFixed(2));
return;
}
if (this.currencyTo == "EUR") {
this.currencyFromValue = Number(data["rates"][this.currencyFrom]);
this.currencyToValue = 1;
this.currencyRatio = this.currencyToValue / this.currencyFromValue;
this.finalResult = String((Number(this.currencyAmount) * this.currencyRatio).toFixed(2));
return;
}
if (!this.giveError) {
this.currencyFromValue = Number(data["rates"][this.currencyFrom]);
this.currencyToValue = Number(data["rates"][this.currencyTo]);
this.currencyRatio = this.currencyToValue / this.currencyFromValue;
this.finalResult = String((Number(this.currencyAmount) * this.currencyRatio).toFixed(2));
}
};
//updates the dom with the result
CurrencyConverter.prototype.returnResult = function () {
var message;
message = "{0} {1} in {2} is {3} at a rate of {4}"
.replace("{0}", this.currencyAmount)
.replace("{1}", this.currencyFrom)
.replace("{2}", this.currencyTo)
.replace("{3}", this.finalResult)
.replace("{4}", String(this.currencyRatio.toFixed(2)));
$("#resultBtn").text(message);
};
//if something is wrong, will update the dom with the error
CurrencyConverter.prototype.failMessage = function () {
var message;
message = "One or more of the currency Codes is Incorrect";
$("#resultBtn").text(message);
};
return CurrencyConverter;
}());
//eventlistener function which chains all of the calls and calculations together
function convertCurrency() {
//Get the dom elements
var currencyFrom = $("#currencyFrom").val().toUpperCase();
var currencyTo = $("#currencyTo").val().toUpperCase();
var currencyAmount = $("#currencyAmount").val();
//create currency converter object
var currencyConverter = new CurrencyConverter();
//performs api calls, if false. then error occured
var incorrectCurrencies = currencyConverter.setCurrencies(currencyFrom, currencyTo);
if (!incorrectCurrencies) {
currencyConverter.failMessage();
return;
}
currencyConverter.setAmount(currencyAmount);
currencyConverter.getRates(function (data) {
currencyConverter.calculate(data);
currencyConverter.returnResult();
});
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//sweet alert messages
function showCurrencies() {
swal({
title: "Available currency codes:",
text: "AUD: Australian Dollar\nBGN: Bulgarian Vel\nBRL: Brazilian Real\nCAD: Canadian Dollar\nCHF: Swiss Franc\nCNY: Chinese Yuan\nCZK: Czech Koruna\nDKK: Danish Krone\nGBP: British Pound\nHKD: Hong Kong Dollar\nHRK: Croatian Kuna\nHUF: Hungarian Forint\nIDR: Indonesian Rupiah\nILS: Israeli New Sheqel\nINR: Indian Rupee\nJPY: Japanese Yen\nKRW: South Korean Won\nMXN: Mexican Peso\nMYR: Malaysian Ringgit\nNOK: Norwegian Krone\nNZD: New Zealand Dollar\nPHP: Philippine Peso\nPLN: Polish Zloty\nRON: Romanian Leu\nRUB: Russian Ruble\nSEK: Swedish Krone\nSGD: Singapore Dollar\nTHB: Thai Baht\nTRY: Turkish Lira\nUSD: United States Dollar\nZAR: South African Rand",
type: "info",
confirmButtonText: "Return" });
}
function showAuthor() {
swal({
title: "About the Author",
text: "Author: Stanislav Pankrashin\nA student at the University of Auckland who is studying computer science\n",
type: "info",
confirmButtonText: "Return"
});
}
function showInfo() {
swal({
title: "About the Website",
text: "Powered by Fixxer.io\nThis website was made for the purposes of the microsoft student accelorator\nit is not intended to be monetised or used for monetary gain\n",
type: "info",
confirmButtonText: "Return"
});
}
|
{
currencyFromValid = false;
}
|
conditional_block
|
currencyConversion.js
|
//currency conversion class for handling all currency conversion operations
var CurrencyConverter = (function () {
function CurrencyConverter() {
this.giveError = false;
}
CurrencyConverter.prototype.CurrencyConverter = function () {
};
//sets the currencies
CurrencyConverter.prototype.setCurrencies = function (currencyFrom, currencyTo) {
if (this.checkCurrencies(currencyFrom, currencyTo)) {
this.currencyFrom = currencyFrom;
this.currencyTo = currencyTo;
return true;
}
else {
return false;
}
};
//does a check to see if the currencies entered are valid
CurrencyConverter.prototype.checkCurrencies = function (currencyFrom, currencyTo) {
var currencyFromValid;
var currencyToValid;
var currencies = ["AUD", "BGN", "BRL", "CAD",
"CHF", "CNY", "CZK", "DKK",
"EUR", "GBP", "HKD", "HRK",
"HUF", "IDR", "ILS", "INR",
"JPY", "KRW", "MXN", "MYR",
"NOK", "NZD", "PHP", "PLN",
"RON", "RUB", "SEK", "SGD",
"THB", "TRY", "USD", "ZAR"];
if (currencies.indexOf(currencyFrom) != -1) {
currencyFromValid = true;
}
else {
currencyFromValid = false;
}
if (currencies.indexOf(currencyTo) != -1) {
currencyToValid = true;
}
else {
currencyToValid = false;
}
return currencyFromValid && currencyToValid;
};
//sets the amount of currency to be converted
CurrencyConverter.prototype.setAmount = function (amount) {
this.currencyAmount = amount;
};
//Performs asynchronous api call to fixxer, with a dynamic call based on the currencies entered by the user
CurrencyConverter.prototype.getRates = function (callback) {
var settings = {
async: true,
crossDomain: true,
url: "http://api.fixer.io/latest?symbols={1}%2C{2}".replace("{1}", this.currencyFrom).replace("{2}", this.currencyTo),
method: "GET"
};
$.ajax(settings).done(function (response) {
callback(response);
}).fail(function (response) {
this.failMessage();
});
};
//performs the conversion calculation
CurrencyConverter.prototype.calculate = function (data) {
if (this.currencyFrom == "EUR") {
this.currencyFromValue = 1;
this.currencyToValue = Number(data["rates"][this.currencyTo]);
this.currencyRatio = this.currencyToValue / this.currencyFromValue;
this.finalResult = String((Number(this.currencyAmount) * this.currencyRatio).toFixed(2));
return;
}
if (this.currencyTo == "EUR") {
this.currencyFromValue = Number(data["rates"][this.currencyFrom]);
this.currencyToValue = 1;
this.currencyRatio = this.currencyToValue / this.currencyFromValue;
this.finalResult = String((Number(this.currencyAmount) * this.currencyRatio).toFixed(2));
|
this.currencyFromValue = Number(data["rates"][this.currencyFrom]);
this.currencyToValue = Number(data["rates"][this.currencyTo]);
this.currencyRatio = this.currencyToValue / this.currencyFromValue;
this.finalResult = String((Number(this.currencyAmount) * this.currencyRatio).toFixed(2));
}
};
//updates the dom with the result
CurrencyConverter.prototype.returnResult = function () {
var message;
message = "{0} {1} in {2} is {3} at a rate of {4}"
.replace("{0}", this.currencyAmount)
.replace("{1}", this.currencyFrom)
.replace("{2}", this.currencyTo)
.replace("{3}", this.finalResult)
.replace("{4}", String(this.currencyRatio.toFixed(2)));
$("#resultBtn").text(message);
};
//if something is wrong, will update the dom with the error
CurrencyConverter.prototype.failMessage = function () {
var message;
message = "One or more of the currency Codes is Incorrect";
$("#resultBtn").text(message);
};
return CurrencyConverter;
}());
//eventlistener function which chains all of the calls and calculations together
function convertCurrency() {
//Get the dom elements
var currencyFrom = $("#currencyFrom").val().toUpperCase();
var currencyTo = $("#currencyTo").val().toUpperCase();
var currencyAmount = $("#currencyAmount").val();
//create currency converter object
var currencyConverter = new CurrencyConverter();
//performs api calls, if false. then error occured
var incorrectCurrencies = currencyConverter.setCurrencies(currencyFrom, currencyTo);
if (!incorrectCurrencies) {
currencyConverter.failMessage();
return;
}
currencyConverter.setAmount(currencyAmount);
currencyConverter.getRates(function (data) {
currencyConverter.calculate(data);
currencyConverter.returnResult();
});
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//sweet alert messages
function showCurrencies() {
swal({
title: "Available currency codes:",
text: "AUD: Australian Dollar\nBGN: Bulgarian Vel\nBRL: Brazilian Real\nCAD: Canadian Dollar\nCHF: Swiss Franc\nCNY: Chinese Yuan\nCZK: Czech Koruna\nDKK: Danish Krone\nGBP: British Pound\nHKD: Hong Kong Dollar\nHRK: Croatian Kuna\nHUF: Hungarian Forint\nIDR: Indonesian Rupiah\nILS: Israeli New Sheqel\nINR: Indian Rupee\nJPY: Japanese Yen\nKRW: South Korean Won\nMXN: Mexican Peso\nMYR: Malaysian Ringgit\nNOK: Norwegian Krone\nNZD: New Zealand Dollar\nPHP: Philippine Peso\nPLN: Polish Zloty\nRON: Romanian Leu\nRUB: Russian Ruble\nSEK: Swedish Krone\nSGD: Singapore Dollar\nTHB: Thai Baht\nTRY: Turkish Lira\nUSD: United States Dollar\nZAR: South African Rand",
type: "info",
confirmButtonText: "Return" });
}
function showAuthor() {
swal({
title: "About the Author",
text: "Author: Stanislav Pankrashin\nA student at the University of Auckland who is studying computer science\n",
type: "info",
confirmButtonText: "Return"
});
}
function showInfo() {
swal({
title: "About the Website",
text: "Powered by Fixxer.io\nThis website was made for the purposes of the microsoft student accelorator\nit is not intended to be monetised or used for monetary gain\n",
type: "info",
confirmButtonText: "Return"
});
}
|
return;
}
if (!this.giveError) {
|
random_line_split
|
previewContentProvider.ts
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
import { Logger } from '../logger';
import { MarkdownEngine } from '../markdownEngine';
import { MarkdownContributionProvider } from '../markdownExtensions';
import { ContentSecurityPolicyArbiter, MarkdownPreviewSecurityLevel } from '../security';
import { basename, dirname, isAbsolute, join } from '../util/path';
import { WebviewResourceProvider } from '../util/resources';
import { MarkdownPreviewConfiguration, MarkdownPreviewConfigurationManager } from './previewConfig';
const localize = nls.loadMessageBundle();
/**
* Strings used inside the markdown preview.
*
* Stored here and then injected in the preview so that they
* can be localized using our normal localization process.
*/
const previewStrings = {
cspAlertMessageText: localize(
'preview.securityMessage.text',
'Some content has been disabled in this document'),
cspAlertMessageTitle: localize(
'preview.securityMessage.title',
'Potentially unsafe or insecure content has been disabled in the Markdown preview. Change the Markdown preview security setting to allow insecure content or enable scripts'),
cspAlertMessageLabel: localize(
'preview.securityMessage.label',
'Content Disabled Security Warning')
};
function escapeAttribute(value: string | vscode.Uri): string {
return value.toString().replace(/"/g, '"');
}
export interface MarkdownContentProviderOutput {
html: string;
containingImages: { src: string }[];
}
export class MarkdownContentProvider {
constructor(
private readonly engine: MarkdownEngine,
private readonly context: vscode.ExtensionContext,
private readonly cspArbiter: ContentSecurityPolicyArbiter,
private readonly contributionProvider: MarkdownContributionProvider,
private readonly logger: Logger
) { }
public async provideTextDocumentContent(
markdownDocument: vscode.TextDocument,
resourceProvider: WebviewResourceProvider,
previewConfigurations: MarkdownPreviewConfigurationManager,
initialLine: number | undefined = undefined,
state?: any
): Promise<MarkdownContentProviderOutput> {
const sourceUri = markdownDocument.uri;
const config = previewConfigurations.loadAndCacheConfiguration(sourceUri);
const initialData = {
source: sourceUri.toString(),
fragment: state?.fragment || markdownDocument.uri.fragment || undefined,
line: initialLine,
lineCount: markdownDocument.lineCount,
scrollPreviewWithEditor: config.scrollPreviewWithEditor,
scrollEditorWithPreview: config.scrollEditorWithPreview,
doubleClickToSwitchToEditor: config.doubleClickToSwitchToEditor,
disableSecurityWarnings: this.cspArbiter.shouldDisableSecurityWarnings(),
webviewResourceRoot: resourceProvider.asWebviewUri(markdownDocument.uri).toString(),
};
this.logger.log('provideTextDocumentContent', initialData);
// Content Security Policy
const nonce = getNonce();
const csp = this.getCsp(resourceProvider, sourceUri, nonce);
const body = await this.engine.render(markdownDocument, resourceProvider);
const html = `<!DOCTYPE html>
<html style="${escapeAttribute(this.getSettingsOverrideStyles(config))}">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
${csp}
<meta id="vscode-markdown-preview-data"
data-settings="${escapeAttribute(JSON.stringify(initialData))}"
data-strings="${escapeAttribute(JSON.stringify(previewStrings))}"
data-state="${escapeAttribute(JSON.stringify(state || {}))}">
<script src="${this.extensionResourcePath(resourceProvider, 'pre.js')}" nonce="${nonce}"></script>
${this.getStyles(resourceProvider, sourceUri, config, state)}
<base href="${resourceProvider.asWebviewUri(markdownDocument.uri)}">
</head>
<body class="vscode-body ${config.scrollBeyondLastLine ? 'scrollBeyondLastLine' : ''} ${config.wordWrap ? 'wordWrap' : ''} ${config.markEditorSelection ? 'showEditorSelection' : ''}">
${body.html}
<div class="code-line" data-line="${markdownDocument.lineCount}"></div>
${this.getScripts(resourceProvider, nonce)}
</body>
</html>`;
return {
html,
containingImages: body.containingImages,
};
}
public provideFileNotFoundContent(
resource: vscode.Uri,
): string {
const resourcePath = basename(resource.fsPath);
const body = localize('preview.notFound', '{0} cannot be found', resourcePath);
return `<!DOCTYPE html>
<html>
<body class="vscode-body">
${body}
</body>
</html>`;
}
private extensionResourcePath(resourceProvider: WebviewResourceProvider, mediaFile: string): string {
const webviewResource = resourceProvider.asWebviewUri(
vscode.Uri.joinPath(this.context.extensionUri, 'media', mediaFile));
return webviewResource.toString();
}
private fixHref(resourceProvider: WebviewResourceProvider, resource: vscode.Uri, href: string): string {
if (!href) {
return href;
}
if (href.startsWith('http:') || href.startsWith('https:') || href.startsWith('file:')) {
return href;
}
// Assume it must be a local file
if (isAbsolute(href)) {
return resourceProvider.asWebviewUri(vscode.Uri.file(href)).toString();
}
// Use a workspace relative path if there is a workspace
const root = vscode.workspace.getWorkspaceFolder(resource);
if (root) {
return resourceProvider.asWebviewUri(vscode.Uri.joinPath(root.uri, href)).toString();
}
// Otherwise look relative to the markdown file
return resourceProvider.asWebviewUri(vscode.Uri.file(join(dirname(resource.fsPath), href))).toString();
}
private computeCustomStyleSheetIncludes(resourceProvider: WebviewResourceProvider, resource: vscode.Uri, config: MarkdownPreviewConfiguration): string {
if (!Array.isArray(config.styles)) {
return '';
}
const out: string[] = [];
for (const style of config.styles) {
out.push(`<link rel="stylesheet" class="code-user-style" data-source="${escapeAttribute(style)}" href="${escapeAttribute(this.fixHref(resourceProvider, resource, style))}" type="text/css" media="screen">`);
}
return out.join('\n');
}
private getSettingsOverrideStyles(config: MarkdownPreviewConfiguration): string {
return [
config.fontFamily ? `--markdown-font-family: ${config.fontFamily};` : '',
isNaN(config.fontSize) ? '' : `--markdown-font-size: ${config.fontSize}px;`,
isNaN(config.lineHeight) ? '' : `--markdown-line-height: ${config.lineHeight};`,
].join(' ');
}
private getImageStabilizerStyles(state?: any) {
let ret = '<style>\n';
if (state && state.imageInfo) {
state.imageInfo.forEach((imgInfo: any) => {
ret += `#${imgInfo.id}.loading {
height: ${imgInfo.height}px;
width: ${imgInfo.width}px;
}\n`;
});
}
ret += '</style>\n';
return ret;
}
private getStyles(resourceProvider: WebviewResourceProvider, resource: vscode.Uri, config: MarkdownPreviewConfiguration, state?: any): string {
const baseStyles: string[] = [];
for (const resource of this.contributionProvider.contributions.previewStyles) {
baseStyles.push(`<link rel="stylesheet" type="text/css" href="${escapeAttribute(resourceProvider.asWebviewUri(resource))}">`);
}
return `${baseStyles.join('\n')}
${this.computeCustomStyleSheetIncludes(resourceProvider, resource, config)}
${this.getImageStabilizerStyles(state)}`;
}
private getScripts(resourceProvider: WebviewResourceProvider, nonce: string): string {
const out: string[] = [];
for (const resource of this.contributionProvider.contributions.previewScripts) {
out.push(`<script async
src="${escapeAttribute(resourceProvider.asWebviewUri(resource))}"
nonce="${nonce}"
charset="UTF-8"></script>`);
}
return out.join('\n');
}
private
|
(
provider: WebviewResourceProvider,
resource: vscode.Uri,
nonce: string
): string {
const rule = provider.cspSource;
switch (this.cspArbiter.getSecurityLevelForResource(resource)) {
case MarkdownPreviewSecurityLevel.AllowInsecureContent:
return `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' ${rule} http: https: data:; media-src 'self' ${rule} http: https: data:; script-src 'nonce-${nonce}'; style-src 'self' ${rule} 'unsafe-inline' http: https: data:; font-src 'self' ${rule} http: https: data:;">`;
case MarkdownPreviewSecurityLevel.AllowInsecureLocalContent:
return `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' ${rule} https: data: http://localhost:* http://127.0.0.1:*; media-src 'self' ${rule} https: data: http://localhost:* http://127.0.0.1:*; script-src 'nonce-${nonce}'; style-src 'self' ${rule} 'unsafe-inline' https: data: http://localhost:* http://127.0.0.1:*; font-src 'self' ${rule} https: data: http://localhost:* http://127.0.0.1:*;">`;
case MarkdownPreviewSecurityLevel.AllowScriptsAndAllContent:
return '<meta http-equiv="Content-Security-Policy" content="">';
case MarkdownPreviewSecurityLevel.Strict:
default:
return `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' ${rule} https: data:; media-src 'self' ${rule} https: data:; script-src 'nonce-${nonce}'; style-src 'self' ${rule} 'unsafe-inline' https: data:; font-src 'self' ${rule} https: data:;">`;
}
}
}
function getNonce() {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 64; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
|
getCsp
|
identifier_name
|
previewContentProvider.ts
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
import { Logger } from '../logger';
import { MarkdownEngine } from '../markdownEngine';
import { MarkdownContributionProvider } from '../markdownExtensions';
import { ContentSecurityPolicyArbiter, MarkdownPreviewSecurityLevel } from '../security';
import { basename, dirname, isAbsolute, join } from '../util/path';
import { WebviewResourceProvider } from '../util/resources';
import { MarkdownPreviewConfiguration, MarkdownPreviewConfigurationManager } from './previewConfig';
const localize = nls.loadMessageBundle();
/**
* Strings used inside the markdown preview.
*
* Stored here and then injected in the preview so that they
* can be localized using our normal localization process.
*/
const previewStrings = {
cspAlertMessageText: localize(
'preview.securityMessage.text',
'Some content has been disabled in this document'),
cspAlertMessageTitle: localize(
'preview.securityMessage.title',
'Potentially unsafe or insecure content has been disabled in the Markdown preview. Change the Markdown preview security setting to allow insecure content or enable scripts'),
cspAlertMessageLabel: localize(
'preview.securityMessage.label',
'Content Disabled Security Warning')
};
function escapeAttribute(value: string | vscode.Uri): string {
return value.toString().replace(/"/g, '"');
}
export interface MarkdownContentProviderOutput {
html: string;
containingImages: { src: string }[];
}
export class MarkdownContentProvider {
constructor(
private readonly engine: MarkdownEngine,
private readonly context: vscode.ExtensionContext,
private readonly cspArbiter: ContentSecurityPolicyArbiter,
private readonly contributionProvider: MarkdownContributionProvider,
private readonly logger: Logger
) { }
public async provideTextDocumentContent(
markdownDocument: vscode.TextDocument,
resourceProvider: WebviewResourceProvider,
previewConfigurations: MarkdownPreviewConfigurationManager,
initialLine: number | undefined = undefined,
state?: any
): Promise<MarkdownContentProviderOutput> {
const sourceUri = markdownDocument.uri;
const config = previewConfigurations.loadAndCacheConfiguration(sourceUri);
const initialData = {
source: sourceUri.toString(),
fragment: state?.fragment || markdownDocument.uri.fragment || undefined,
line: initialLine,
lineCount: markdownDocument.lineCount,
scrollPreviewWithEditor: config.scrollPreviewWithEditor,
scrollEditorWithPreview: config.scrollEditorWithPreview,
doubleClickToSwitchToEditor: config.doubleClickToSwitchToEditor,
disableSecurityWarnings: this.cspArbiter.shouldDisableSecurityWarnings(),
webviewResourceRoot: resourceProvider.asWebviewUri(markdownDocument.uri).toString(),
};
this.logger.log('provideTextDocumentContent', initialData);
// Content Security Policy
const nonce = getNonce();
const csp = this.getCsp(resourceProvider, sourceUri, nonce);
const body = await this.engine.render(markdownDocument, resourceProvider);
const html = `<!DOCTYPE html>
<html style="${escapeAttribute(this.getSettingsOverrideStyles(config))}">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
${csp}
<meta id="vscode-markdown-preview-data"
data-settings="${escapeAttribute(JSON.stringify(initialData))}"
data-strings="${escapeAttribute(JSON.stringify(previewStrings))}"
data-state="${escapeAttribute(JSON.stringify(state || {}))}">
<script src="${this.extensionResourcePath(resourceProvider, 'pre.js')}" nonce="${nonce}"></script>
${this.getStyles(resourceProvider, sourceUri, config, state)}
<base href="${resourceProvider.asWebviewUri(markdownDocument.uri)}">
</head>
<body class="vscode-body ${config.scrollBeyondLastLine ? 'scrollBeyondLastLine' : ''} ${config.wordWrap ? 'wordWrap' : ''} ${config.markEditorSelection ? 'showEditorSelection' : ''}">
${body.html}
<div class="code-line" data-line="${markdownDocument.lineCount}"></div>
${this.getScripts(resourceProvider, nonce)}
</body>
</html>`;
return {
html,
containingImages: body.containingImages,
};
}
public provideFileNotFoundContent(
resource: vscode.Uri,
): string {
const resourcePath = basename(resource.fsPath);
const body = localize('preview.notFound', '{0} cannot be found', resourcePath);
return `<!DOCTYPE html>
<html>
<body class="vscode-body">
${body}
</body>
</html>`;
}
private extensionResourcePath(resourceProvider: WebviewResourceProvider, mediaFile: string): string {
const webviewResource = resourceProvider.asWebviewUri(
vscode.Uri.joinPath(this.context.extensionUri, 'media', mediaFile));
return webviewResource.toString();
}
private fixHref(resourceProvider: WebviewResourceProvider, resource: vscode.Uri, href: string): string {
if (!href) {
return href;
}
if (href.startsWith('http:') || href.startsWith('https:') || href.startsWith('file:')) {
return href;
}
// Assume it must be a local file
if (isAbsolute(href)) {
return resourceProvider.asWebviewUri(vscode.Uri.file(href)).toString();
}
// Use a workspace relative path if there is a workspace
const root = vscode.workspace.getWorkspaceFolder(resource);
if (root) {
return resourceProvider.asWebviewUri(vscode.Uri.joinPath(root.uri, href)).toString();
}
// Otherwise look relative to the markdown file
return resourceProvider.asWebviewUri(vscode.Uri.file(join(dirname(resource.fsPath), href))).toString();
}
private computeCustomStyleSheetIncludes(resourceProvider: WebviewResourceProvider, resource: vscode.Uri, config: MarkdownPreviewConfiguration): string {
if (!Array.isArray(config.styles)) {
return '';
}
const out: string[] = [];
for (const style of config.styles) {
out.push(`<link rel="stylesheet" class="code-user-style" data-source="${escapeAttribute(style)}" href="${escapeAttribute(this.fixHref(resourceProvider, resource, style))}" type="text/css" media="screen">`);
}
return out.join('\n');
}
private getSettingsOverrideStyles(config: MarkdownPreviewConfiguration): string {
return [
config.fontFamily ? `--markdown-font-family: ${config.fontFamily};` : '',
isNaN(config.fontSize) ? '' : `--markdown-font-size: ${config.fontSize}px;`,
isNaN(config.lineHeight) ? '' : `--markdown-line-height: ${config.lineHeight};`,
].join(' ');
}
private getImageStabilizerStyles(state?: any) {
let ret = '<style>\n';
if (state && state.imageInfo) {
state.imageInfo.forEach((imgInfo: any) => {
ret += `#${imgInfo.id}.loading {
height: ${imgInfo.height}px;
width: ${imgInfo.width}px;
}\n`;
});
}
ret += '</style>\n';
return ret;
}
private getStyles(resourceProvider: WebviewResourceProvider, resource: vscode.Uri, config: MarkdownPreviewConfiguration, state?: any): string
|
private getScripts(resourceProvider: WebviewResourceProvider, nonce: string): string {
const out: string[] = [];
for (const resource of this.contributionProvider.contributions.previewScripts) {
out.push(`<script async
src="${escapeAttribute(resourceProvider.asWebviewUri(resource))}"
nonce="${nonce}"
charset="UTF-8"></script>`);
}
return out.join('\n');
}
private getCsp(
provider: WebviewResourceProvider,
resource: vscode.Uri,
nonce: string
): string {
const rule = provider.cspSource;
switch (this.cspArbiter.getSecurityLevelForResource(resource)) {
case MarkdownPreviewSecurityLevel.AllowInsecureContent:
return `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' ${rule} http: https: data:; media-src 'self' ${rule} http: https: data:; script-src 'nonce-${nonce}'; style-src 'self' ${rule} 'unsafe-inline' http: https: data:; font-src 'self' ${rule} http: https: data:;">`;
case MarkdownPreviewSecurityLevel.AllowInsecureLocalContent:
return `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' ${rule} https: data: http://localhost:* http://127.0.0.1:*; media-src 'self' ${rule} https: data: http://localhost:* http://127.0.0.1:*; script-src 'nonce-${nonce}'; style-src 'self' ${rule} 'unsafe-inline' https: data: http://localhost:* http://127.0.0.1:*; font-src 'self' ${rule} https: data: http://localhost:* http://127.0.0.1:*;">`;
case MarkdownPreviewSecurityLevel.AllowScriptsAndAllContent:
return '<meta http-equiv="Content-Security-Policy" content="">';
case MarkdownPreviewSecurityLevel.Strict:
default:
return `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' ${rule} https: data:; media-src 'self' ${rule} https: data:; script-src 'nonce-${nonce}'; style-src 'self' ${rule} 'unsafe-inline' https: data:; font-src 'self' ${rule} https: data:;">`;
}
}
}
function getNonce() {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 64; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
|
{
const baseStyles: string[] = [];
for (const resource of this.contributionProvider.contributions.previewStyles) {
baseStyles.push(`<link rel="stylesheet" type="text/css" href="${escapeAttribute(resourceProvider.asWebviewUri(resource))}">`);
}
return `${baseStyles.join('\n')}
${this.computeCustomStyleSheetIncludes(resourceProvider, resource, config)}
${this.getImageStabilizerStyles(state)}`;
}
|
identifier_body
|
previewContentProvider.ts
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
import { Logger } from '../logger';
import { MarkdownEngine } from '../markdownEngine';
import { MarkdownContributionProvider } from '../markdownExtensions';
import { ContentSecurityPolicyArbiter, MarkdownPreviewSecurityLevel } from '../security';
import { basename, dirname, isAbsolute, join } from '../util/path';
import { WebviewResourceProvider } from '../util/resources';
import { MarkdownPreviewConfiguration, MarkdownPreviewConfigurationManager } from './previewConfig';
const localize = nls.loadMessageBundle();
/**
* Strings used inside the markdown preview.
*
* Stored here and then injected in the preview so that they
* can be localized using our normal localization process.
*/
const previewStrings = {
cspAlertMessageText: localize(
'preview.securityMessage.text',
'Some content has been disabled in this document'),
cspAlertMessageTitle: localize(
'preview.securityMessage.title',
'Potentially unsafe or insecure content has been disabled in the Markdown preview. Change the Markdown preview security setting to allow insecure content or enable scripts'),
cspAlertMessageLabel: localize(
'preview.securityMessage.label',
'Content Disabled Security Warning')
};
function escapeAttribute(value: string | vscode.Uri): string {
return value.toString().replace(/"/g, '"');
}
export interface MarkdownContentProviderOutput {
html: string;
containingImages: { src: string }[];
}
export class MarkdownContentProvider {
constructor(
private readonly engine: MarkdownEngine,
private readonly context: vscode.ExtensionContext,
private readonly cspArbiter: ContentSecurityPolicyArbiter,
private readonly contributionProvider: MarkdownContributionProvider,
private readonly logger: Logger
) { }
public async provideTextDocumentContent(
markdownDocument: vscode.TextDocument,
resourceProvider: WebviewResourceProvider,
previewConfigurations: MarkdownPreviewConfigurationManager,
initialLine: number | undefined = undefined,
state?: any
): Promise<MarkdownContentProviderOutput> {
const sourceUri = markdownDocument.uri;
const config = previewConfigurations.loadAndCacheConfiguration(sourceUri);
const initialData = {
source: sourceUri.toString(),
fragment: state?.fragment || markdownDocument.uri.fragment || undefined,
line: initialLine,
lineCount: markdownDocument.lineCount,
scrollPreviewWithEditor: config.scrollPreviewWithEditor,
scrollEditorWithPreview: config.scrollEditorWithPreview,
doubleClickToSwitchToEditor: config.doubleClickToSwitchToEditor,
disableSecurityWarnings: this.cspArbiter.shouldDisableSecurityWarnings(),
webviewResourceRoot: resourceProvider.asWebviewUri(markdownDocument.uri).toString(),
};
this.logger.log('provideTextDocumentContent', initialData);
// Content Security Policy
const nonce = getNonce();
const csp = this.getCsp(resourceProvider, sourceUri, nonce);
const body = await this.engine.render(markdownDocument, resourceProvider);
const html = `<!DOCTYPE html>
<html style="${escapeAttribute(this.getSettingsOverrideStyles(config))}">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
${csp}
<meta id="vscode-markdown-preview-data"
data-settings="${escapeAttribute(JSON.stringify(initialData))}"
data-strings="${escapeAttribute(JSON.stringify(previewStrings))}"
data-state="${escapeAttribute(JSON.stringify(state || {}))}">
<script src="${this.extensionResourcePath(resourceProvider, 'pre.js')}" nonce="${nonce}"></script>
${this.getStyles(resourceProvider, sourceUri, config, state)}
<base href="${resourceProvider.asWebviewUri(markdownDocument.uri)}">
</head>
<body class="vscode-body ${config.scrollBeyondLastLine ? 'scrollBeyondLastLine' : ''} ${config.wordWrap ? 'wordWrap' : ''} ${config.markEditorSelection ? 'showEditorSelection' : ''}">
${body.html}
<div class="code-line" data-line="${markdownDocument.lineCount}"></div>
${this.getScripts(resourceProvider, nonce)}
</body>
</html>`;
return {
html,
containingImages: body.containingImages,
};
}
public provideFileNotFoundContent(
resource: vscode.Uri,
): string {
const resourcePath = basename(resource.fsPath);
const body = localize('preview.notFound', '{0} cannot be found', resourcePath);
return `<!DOCTYPE html>
<html>
<body class="vscode-body">
${body}
</body>
</html>`;
}
private extensionResourcePath(resourceProvider: WebviewResourceProvider, mediaFile: string): string {
const webviewResource = resourceProvider.asWebviewUri(
vscode.Uri.joinPath(this.context.extensionUri, 'media', mediaFile));
return webviewResource.toString();
}
private fixHref(resourceProvider: WebviewResourceProvider, resource: vscode.Uri, href: string): string {
if (!href) {
return href;
}
if (href.startsWith('http:') || href.startsWith('https:') || href.startsWith('file:')) {
return href;
}
// Assume it must be a local file
if (isAbsolute(href)) {
return resourceProvider.asWebviewUri(vscode.Uri.file(href)).toString();
}
// Use a workspace relative path if there is a workspace
const root = vscode.workspace.getWorkspaceFolder(resource);
if (root) {
return resourceProvider.asWebviewUri(vscode.Uri.joinPath(root.uri, href)).toString();
}
// Otherwise look relative to the markdown file
return resourceProvider.asWebviewUri(vscode.Uri.file(join(dirname(resource.fsPath), href))).toString();
}
private computeCustomStyleSheetIncludes(resourceProvider: WebviewResourceProvider, resource: vscode.Uri, config: MarkdownPreviewConfiguration): string {
if (!Array.isArray(config.styles)) {
return '';
}
const out: string[] = [];
for (const style of config.styles) {
out.push(`<link rel="stylesheet" class="code-user-style" data-source="${escapeAttribute(style)}" href="${escapeAttribute(this.fixHref(resourceProvider, resource, style))}" type="text/css" media="screen">`);
}
return out.join('\n');
}
private getSettingsOverrideStyles(config: MarkdownPreviewConfiguration): string {
return [
config.fontFamily ? `--markdown-font-family: ${config.fontFamily};` : '',
isNaN(config.fontSize) ? '' : `--markdown-font-size: ${config.fontSize}px;`,
isNaN(config.lineHeight) ? '' : `--markdown-line-height: ${config.lineHeight};`,
].join(' ');
}
private getImageStabilizerStyles(state?: any) {
let ret = '<style>\n';
if (state && state.imageInfo) {
state.imageInfo.forEach((imgInfo: any) => {
ret += `#${imgInfo.id}.loading {
height: ${imgInfo.height}px;
width: ${imgInfo.width}px;
}\n`;
});
}
ret += '</style>\n';
return ret;
}
private getStyles(resourceProvider: WebviewResourceProvider, resource: vscode.Uri, config: MarkdownPreviewConfiguration, state?: any): string {
const baseStyles: string[] = [];
for (const resource of this.contributionProvider.contributions.previewStyles) {
baseStyles.push(`<link rel="stylesheet" type="text/css" href="${escapeAttribute(resourceProvider.asWebviewUri(resource))}">`);
}
return `${baseStyles.join('\n')}
${this.computeCustomStyleSheetIncludes(resourceProvider, resource, config)}
${this.getImageStabilizerStyles(state)}`;
}
private getScripts(resourceProvider: WebviewResourceProvider, nonce: string): string {
const out: string[] = [];
for (const resource of this.contributionProvider.contributions.previewScripts) {
out.push(`<script async
src="${escapeAttribute(resourceProvider.asWebviewUri(resource))}"
nonce="${nonce}"
charset="UTF-8"></script>`);
}
return out.join('\n');
}
private getCsp(
provider: WebviewResourceProvider,
resource: vscode.Uri,
nonce: string
): string {
const rule = provider.cspSource;
switch (this.cspArbiter.getSecurityLevelForResource(resource)) {
case MarkdownPreviewSecurityLevel.AllowInsecureContent:
return `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' ${rule} http: https: data:; media-src 'self' ${rule} http: https: data:; script-src 'nonce-${nonce}'; style-src 'self' ${rule} 'unsafe-inline' http: https: data:; font-src 'self' ${rule} http: https: data:;">`;
case MarkdownPreviewSecurityLevel.AllowInsecureLocalContent:
return `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' ${rule} https: data: http://localhost:* http://127.0.0.1:*; media-src 'self' ${rule} https: data: http://localhost:* http://127.0.0.1:*; script-src 'nonce-${nonce}'; style-src 'self' ${rule} 'unsafe-inline' https: data: http://localhost:* http://127.0.0.1:*; font-src 'self' ${rule} https: data: http://localhost:* http://127.0.0.1:*;">`;
case MarkdownPreviewSecurityLevel.AllowScriptsAndAllContent:
return '<meta http-equiv="Content-Security-Policy" content="">';
case MarkdownPreviewSecurityLevel.Strict:
default:
return `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' ${rule} https: data:; media-src 'self' ${rule} https: data:; script-src 'nonce-${nonce}'; style-src 'self' ${rule} 'unsafe-inline' https: data:; font-src 'self' ${rule} https: data:;">`;
}
}
}
function getNonce() {
|
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 64; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
|
let text = '';
|
random_line_split
|
previewContentProvider.ts
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
import { Logger } from '../logger';
import { MarkdownEngine } from '../markdownEngine';
import { MarkdownContributionProvider } from '../markdownExtensions';
import { ContentSecurityPolicyArbiter, MarkdownPreviewSecurityLevel } from '../security';
import { basename, dirname, isAbsolute, join } from '../util/path';
import { WebviewResourceProvider } from '../util/resources';
import { MarkdownPreviewConfiguration, MarkdownPreviewConfigurationManager } from './previewConfig';
const localize = nls.loadMessageBundle();
/**
* Strings used inside the markdown preview.
*
* Stored here and then injected in the preview so that they
* can be localized using our normal localization process.
*/
const previewStrings = {
cspAlertMessageText: localize(
'preview.securityMessage.text',
'Some content has been disabled in this document'),
cspAlertMessageTitle: localize(
'preview.securityMessage.title',
'Potentially unsafe or insecure content has been disabled in the Markdown preview. Change the Markdown preview security setting to allow insecure content or enable scripts'),
cspAlertMessageLabel: localize(
'preview.securityMessage.label',
'Content Disabled Security Warning')
};
function escapeAttribute(value: string | vscode.Uri): string {
return value.toString().replace(/"/g, '"');
}
export interface MarkdownContentProviderOutput {
html: string;
containingImages: { src: string }[];
}
export class MarkdownContentProvider {
constructor(
private readonly engine: MarkdownEngine,
private readonly context: vscode.ExtensionContext,
private readonly cspArbiter: ContentSecurityPolicyArbiter,
private readonly contributionProvider: MarkdownContributionProvider,
private readonly logger: Logger
) { }
public async provideTextDocumentContent(
markdownDocument: vscode.TextDocument,
resourceProvider: WebviewResourceProvider,
previewConfigurations: MarkdownPreviewConfigurationManager,
initialLine: number | undefined = undefined,
state?: any
): Promise<MarkdownContentProviderOutput> {
const sourceUri = markdownDocument.uri;
const config = previewConfigurations.loadAndCacheConfiguration(sourceUri);
const initialData = {
source: sourceUri.toString(),
fragment: state?.fragment || markdownDocument.uri.fragment || undefined,
line: initialLine,
lineCount: markdownDocument.lineCount,
scrollPreviewWithEditor: config.scrollPreviewWithEditor,
scrollEditorWithPreview: config.scrollEditorWithPreview,
doubleClickToSwitchToEditor: config.doubleClickToSwitchToEditor,
disableSecurityWarnings: this.cspArbiter.shouldDisableSecurityWarnings(),
webviewResourceRoot: resourceProvider.asWebviewUri(markdownDocument.uri).toString(),
};
this.logger.log('provideTextDocumentContent', initialData);
// Content Security Policy
const nonce = getNonce();
const csp = this.getCsp(resourceProvider, sourceUri, nonce);
const body = await this.engine.render(markdownDocument, resourceProvider);
const html = `<!DOCTYPE html>
<html style="${escapeAttribute(this.getSettingsOverrideStyles(config))}">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
${csp}
<meta id="vscode-markdown-preview-data"
data-settings="${escapeAttribute(JSON.stringify(initialData))}"
data-strings="${escapeAttribute(JSON.stringify(previewStrings))}"
data-state="${escapeAttribute(JSON.stringify(state || {}))}">
<script src="${this.extensionResourcePath(resourceProvider, 'pre.js')}" nonce="${nonce}"></script>
${this.getStyles(resourceProvider, sourceUri, config, state)}
<base href="${resourceProvider.asWebviewUri(markdownDocument.uri)}">
</head>
<body class="vscode-body ${config.scrollBeyondLastLine ? 'scrollBeyondLastLine' : ''} ${config.wordWrap ? 'wordWrap' : ''} ${config.markEditorSelection ? 'showEditorSelection' : ''}">
${body.html}
<div class="code-line" data-line="${markdownDocument.lineCount}"></div>
${this.getScripts(resourceProvider, nonce)}
</body>
</html>`;
return {
html,
containingImages: body.containingImages,
};
}
public provideFileNotFoundContent(
resource: vscode.Uri,
): string {
const resourcePath = basename(resource.fsPath);
const body = localize('preview.notFound', '{0} cannot be found', resourcePath);
return `<!DOCTYPE html>
<html>
<body class="vscode-body">
${body}
</body>
</html>`;
}
private extensionResourcePath(resourceProvider: WebviewResourceProvider, mediaFile: string): string {
const webviewResource = resourceProvider.asWebviewUri(
vscode.Uri.joinPath(this.context.extensionUri, 'media', mediaFile));
return webviewResource.toString();
}
private fixHref(resourceProvider: WebviewResourceProvider, resource: vscode.Uri, href: string): string {
if (!href) {
return href;
}
if (href.startsWith('http:') || href.startsWith('https:') || href.startsWith('file:')) {
return href;
}
// Assume it must be a local file
if (isAbsolute(href))
|
// Use a workspace relative path if there is a workspace
const root = vscode.workspace.getWorkspaceFolder(resource);
if (root) {
return resourceProvider.asWebviewUri(vscode.Uri.joinPath(root.uri, href)).toString();
}
// Otherwise look relative to the markdown file
return resourceProvider.asWebviewUri(vscode.Uri.file(join(dirname(resource.fsPath), href))).toString();
}
private computeCustomStyleSheetIncludes(resourceProvider: WebviewResourceProvider, resource: vscode.Uri, config: MarkdownPreviewConfiguration): string {
if (!Array.isArray(config.styles)) {
return '';
}
const out: string[] = [];
for (const style of config.styles) {
out.push(`<link rel="stylesheet" class="code-user-style" data-source="${escapeAttribute(style)}" href="${escapeAttribute(this.fixHref(resourceProvider, resource, style))}" type="text/css" media="screen">`);
}
return out.join('\n');
}
private getSettingsOverrideStyles(config: MarkdownPreviewConfiguration): string {
return [
config.fontFamily ? `--markdown-font-family: ${config.fontFamily};` : '',
isNaN(config.fontSize) ? '' : `--markdown-font-size: ${config.fontSize}px;`,
isNaN(config.lineHeight) ? '' : `--markdown-line-height: ${config.lineHeight};`,
].join(' ');
}
private getImageStabilizerStyles(state?: any) {
let ret = '<style>\n';
if (state && state.imageInfo) {
state.imageInfo.forEach((imgInfo: any) => {
ret += `#${imgInfo.id}.loading {
height: ${imgInfo.height}px;
width: ${imgInfo.width}px;
}\n`;
});
}
ret += '</style>\n';
return ret;
}
private getStyles(resourceProvider: WebviewResourceProvider, resource: vscode.Uri, config: MarkdownPreviewConfiguration, state?: any): string {
const baseStyles: string[] = [];
for (const resource of this.contributionProvider.contributions.previewStyles) {
baseStyles.push(`<link rel="stylesheet" type="text/css" href="${escapeAttribute(resourceProvider.asWebviewUri(resource))}">`);
}
return `${baseStyles.join('\n')}
${this.computeCustomStyleSheetIncludes(resourceProvider, resource, config)}
${this.getImageStabilizerStyles(state)}`;
}
private getScripts(resourceProvider: WebviewResourceProvider, nonce: string): string {
const out: string[] = [];
for (const resource of this.contributionProvider.contributions.previewScripts) {
out.push(`<script async
src="${escapeAttribute(resourceProvider.asWebviewUri(resource))}"
nonce="${nonce}"
charset="UTF-8"></script>`);
}
return out.join('\n');
}
private getCsp(
provider: WebviewResourceProvider,
resource: vscode.Uri,
nonce: string
): string {
const rule = provider.cspSource;
switch (this.cspArbiter.getSecurityLevelForResource(resource)) {
case MarkdownPreviewSecurityLevel.AllowInsecureContent:
return `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' ${rule} http: https: data:; media-src 'self' ${rule} http: https: data:; script-src 'nonce-${nonce}'; style-src 'self' ${rule} 'unsafe-inline' http: https: data:; font-src 'self' ${rule} http: https: data:;">`;
case MarkdownPreviewSecurityLevel.AllowInsecureLocalContent:
return `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' ${rule} https: data: http://localhost:* http://127.0.0.1:*; media-src 'self' ${rule} https: data: http://localhost:* http://127.0.0.1:*; script-src 'nonce-${nonce}'; style-src 'self' ${rule} 'unsafe-inline' https: data: http://localhost:* http://127.0.0.1:*; font-src 'self' ${rule} https: data: http://localhost:* http://127.0.0.1:*;">`;
case MarkdownPreviewSecurityLevel.AllowScriptsAndAllContent:
return '<meta http-equiv="Content-Security-Policy" content="">';
case MarkdownPreviewSecurityLevel.Strict:
default:
return `<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src 'self' ${rule} https: data:; media-src 'self' ${rule} https: data:; script-src 'nonce-${nonce}'; style-src 'self' ${rule} 'unsafe-inline' https: data:; font-src 'self' ${rule} https: data:;">`;
}
}
}
function getNonce() {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 64; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
|
{
return resourceProvider.asWebviewUri(vscode.Uri.file(href)).toString();
}
|
conditional_block
|
expr-match-struct.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests for match as expressions resulting in struct types
struct R { i: int }
fn test_rec() {
let rs = match true { true => R {i: 100}, _ => panic!() };
assert_eq!(rs.i, 100);
}
#[deriving(Show)]
enum mood { happy, sad, }
impl PartialEq for mood {
fn
|
(&self, other: &mood) -> bool {
((*self) as uint) == ((*other) as uint)
}
fn ne(&self, other: &mood) -> bool { !(*self).eq(other) }
}
fn test_tag() {
let rs = match true { true => { mood::happy } false => { mood::sad } };
assert_eq!(rs, mood::happy);
}
pub fn main() { test_rec(); test_tag(); }
|
eq
|
identifier_name
|
expr-match-struct.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests for match as expressions resulting in struct types
struct R { i: int }
fn test_rec() {
let rs = match true { true => R {i: 100}, _ => panic!() };
assert_eq!(rs.i, 100);
}
#[deriving(Show)]
enum mood { happy, sad, }
impl PartialEq for mood {
fn eq(&self, other: &mood) -> bool {
((*self) as uint) == ((*other) as uint)
}
fn ne(&self, other: &mood) -> bool { !(*self).eq(other) }
}
fn test_tag()
|
pub fn main() { test_rec(); test_tag(); }
|
{
let rs = match true { true => { mood::happy } false => { mood::sad } };
assert_eq!(rs, mood::happy);
}
|
identifier_body
|
expr-match-struct.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Tests for match as expressions resulting in struct types
struct R { i: int }
fn test_rec() {
let rs = match true { true => R {i: 100}, _ => panic!() };
|
#[deriving(Show)]
enum mood { happy, sad, }
impl PartialEq for mood {
fn eq(&self, other: &mood) -> bool {
((*self) as uint) == ((*other) as uint)
}
fn ne(&self, other: &mood) -> bool { !(*self).eq(other) }
}
fn test_tag() {
let rs = match true { true => { mood::happy } false => { mood::sad } };
assert_eq!(rs, mood::happy);
}
pub fn main() { test_rec(); test_tag(); }
|
assert_eq!(rs.i, 100);
}
|
random_line_split
|
git-host-info.js
|
'use strict'
var gitHosts = module.exports = {
github: {
// First two are insecure and generally shouldn't be used any more, but
// they are still supported.
'protocols': [ 'git', 'http', 'git+ssh', 'git+https', 'ssh', 'https' ],
'domain': 'github.com',
'treepath': 'tree',
'filetemplate': 'https://{auth@}raw.githubusercontent.com/{user}/{project}/{committish}/{path}',
'bugstemplate': 'https://{domain}/{user}/{project}/issues',
'gittemplate': 'git://{auth@}{domain}/{user}/{project}.git{#committish}',
'tarballtemplate': 'https://codeload.{domain}/{user}/{project}/tar.gz/{committish}'
},
bitbucket: {
'protocols': [ 'git+ssh', 'git+https', 'ssh', 'https' ],
'domain': 'bitbucket.org',
'treepath': 'src',
'tarballtemplate': 'https://{domain}/{user}/{project}/get/{committish}.tar.gz'
},
gitlab: {
'protocols': [ 'git+ssh', 'git+https', 'ssh', 'https' ],
'domain': 'gitlab.com',
'treepath': 'tree',
'bugstemplate': 'https://{domain}/{user}/{project}/issues',
'httpstemplate': 'git+https://{auth@}{domain}/{user}/{projectPath}.git{#committish}',
'tarballtemplate': 'https://{domain}/{user}/{project}/repository/archive.tar.gz?ref={committish}',
'pathmatch': /^[/]([^/]+)[/](.+?)(?:[.]git|[/])?$/
},
gist: {
'protocols': [ 'git', 'git+ssh', 'git+https', 'ssh', 'https' ],
'domain': 'gist.github.com',
'pathmatch': /^[/](?:([^/]+)[/])?([a-z0-9]{32,})(?:[.]git)?$/,
'filetemplate': 'https://gist.githubusercontent.com/{user}/{project}/raw{/committish}/{path}',
'bugstemplate': 'https://{domain}/{project}',
'gittemplate': 'git://{domain}/{project}.git{#committish}',
'sshtemplate': 'git@{domain}:/{project}.git{#committish}',
'sshurltemplate': 'git+ssh://git@{domain}/{project}.git{#committish}',
'browsetemplate': 'https://{domain}/{project}{/committish}',
'browsefiletemplate': 'https://{domain}/{project}{/committish}{#path}',
'docstemplate': 'https://{domain}/{project}{/committish}',
'httpstemplate': 'git+https://{domain}/{project}.git{#committish}',
'shortcuttemplate': '{type}:{project}{#committish}',
'pathtemplate': '{project}{#committish}',
'tarballtemplate': 'https://codeload.github.com/gist/{project}/tar.gz/{committish}',
'hashformat': function (fragment) {
return 'file-' + formatHashFragment(fragment)
}
}
}
var gitHostDefaults = {
'sshtemplate': 'git@{domain}:{user}/{project}.git{#committish}',
'sshurltemplate': 'git+ssh://git@{domain}/{user}/{project}.git{#committish}',
'browsetemplate': 'https://{domain}/{user}/{project}{/tree/committish}',
'browsefiletemplate': 'https://{domain}/{user}/{project}/{treepath}/{committish}/{path}{#fragment}',
'docstemplate': 'https://{domain}/{user}/{project}{/tree/committish}#readme',
'httpstemplate': 'git+https://{auth@}{domain}/{user}/{project}.git{#committish}',
'filetemplate': 'https://{domain}/{user}/{project}/raw/{committish}/{path}',
'shortcuttemplate': '{type}:{user}/{project}{#committish}',
'pathtemplate': '{user}/{project}{#committish}',
'pathmatch': /^[/]([^/]+)[/]([^/]+?)(?:[.]git|[/])?$/,
'hashformat': formatHashFragment
}
|
gitHosts[name][key] = gitHostDefaults[key]
})
gitHosts[name].protocols_re = RegExp('^(' +
gitHosts[name].protocols.map(function (protocol) {
return protocol.replace(/([\\+*{}()[\]$^|])/g, '\\$1')
}).join('|') + '):$')
})
function formatHashFragment (fragment) {
return fragment.toLowerCase().replace(/^\W+|\/|\W+$/g, '').replace(/\W+/g, '-')
}
|
Object.keys(gitHosts).forEach(function (name) {
Object.keys(gitHostDefaults).forEach(function (key) {
if (gitHosts[name][key]) return
|
random_line_split
|
git-host-info.js
|
'use strict'
var gitHosts = module.exports = {
github: {
// First two are insecure and generally shouldn't be used any more, but
// they are still supported.
'protocols': [ 'git', 'http', 'git+ssh', 'git+https', 'ssh', 'https' ],
'domain': 'github.com',
'treepath': 'tree',
'filetemplate': 'https://{auth@}raw.githubusercontent.com/{user}/{project}/{committish}/{path}',
'bugstemplate': 'https://{domain}/{user}/{project}/issues',
'gittemplate': 'git://{auth@}{domain}/{user}/{project}.git{#committish}',
'tarballtemplate': 'https://codeload.{domain}/{user}/{project}/tar.gz/{committish}'
},
bitbucket: {
'protocols': [ 'git+ssh', 'git+https', 'ssh', 'https' ],
'domain': 'bitbucket.org',
'treepath': 'src',
'tarballtemplate': 'https://{domain}/{user}/{project}/get/{committish}.tar.gz'
},
gitlab: {
'protocols': [ 'git+ssh', 'git+https', 'ssh', 'https' ],
'domain': 'gitlab.com',
'treepath': 'tree',
'bugstemplate': 'https://{domain}/{user}/{project}/issues',
'httpstemplate': 'git+https://{auth@}{domain}/{user}/{projectPath}.git{#committish}',
'tarballtemplate': 'https://{domain}/{user}/{project}/repository/archive.tar.gz?ref={committish}',
'pathmatch': /^[/]([^/]+)[/](.+?)(?:[.]git|[/])?$/
},
gist: {
'protocols': [ 'git', 'git+ssh', 'git+https', 'ssh', 'https' ],
'domain': 'gist.github.com',
'pathmatch': /^[/](?:([^/]+)[/])?([a-z0-9]{32,})(?:[.]git)?$/,
'filetemplate': 'https://gist.githubusercontent.com/{user}/{project}/raw{/committish}/{path}',
'bugstemplate': 'https://{domain}/{project}',
'gittemplate': 'git://{domain}/{project}.git{#committish}',
'sshtemplate': 'git@{domain}:/{project}.git{#committish}',
'sshurltemplate': 'git+ssh://git@{domain}/{project}.git{#committish}',
'browsetemplate': 'https://{domain}/{project}{/committish}',
'browsefiletemplate': 'https://{domain}/{project}{/committish}{#path}',
'docstemplate': 'https://{domain}/{project}{/committish}',
'httpstemplate': 'git+https://{domain}/{project}.git{#committish}',
'shortcuttemplate': '{type}:{project}{#committish}',
'pathtemplate': '{project}{#committish}',
'tarballtemplate': 'https://codeload.github.com/gist/{project}/tar.gz/{committish}',
'hashformat': function (fragment) {
return 'file-' + formatHashFragment(fragment)
}
}
}
var gitHostDefaults = {
'sshtemplate': 'git@{domain}:{user}/{project}.git{#committish}',
'sshurltemplate': 'git+ssh://git@{domain}/{user}/{project}.git{#committish}',
'browsetemplate': 'https://{domain}/{user}/{project}{/tree/committish}',
'browsefiletemplate': 'https://{domain}/{user}/{project}/{treepath}/{committish}/{path}{#fragment}',
'docstemplate': 'https://{domain}/{user}/{project}{/tree/committish}#readme',
'httpstemplate': 'git+https://{auth@}{domain}/{user}/{project}.git{#committish}',
'filetemplate': 'https://{domain}/{user}/{project}/raw/{committish}/{path}',
'shortcuttemplate': '{type}:{user}/{project}{#committish}',
'pathtemplate': '{user}/{project}{#committish}',
'pathmatch': /^[/]([^/]+)[/]([^/]+?)(?:[.]git|[/])?$/,
'hashformat': formatHashFragment
}
Object.keys(gitHosts).forEach(function (name) {
Object.keys(gitHostDefaults).forEach(function (key) {
if (gitHosts[name][key]) return
gitHosts[name][key] = gitHostDefaults[key]
})
gitHosts[name].protocols_re = RegExp('^(' +
gitHosts[name].protocols.map(function (protocol) {
return protocol.replace(/([\\+*{}()[\]$^|])/g, '\\$1')
}).join('|') + '):$')
})
function
|
(fragment) {
return fragment.toLowerCase().replace(/^\W+|\/|\W+$/g, '').replace(/\W+/g, '-')
}
|
formatHashFragment
|
identifier_name
|
git-host-info.js
|
'use strict'
var gitHosts = module.exports = {
github: {
// First two are insecure and generally shouldn't be used any more, but
// they are still supported.
'protocols': [ 'git', 'http', 'git+ssh', 'git+https', 'ssh', 'https' ],
'domain': 'github.com',
'treepath': 'tree',
'filetemplate': 'https://{auth@}raw.githubusercontent.com/{user}/{project}/{committish}/{path}',
'bugstemplate': 'https://{domain}/{user}/{project}/issues',
'gittemplate': 'git://{auth@}{domain}/{user}/{project}.git{#committish}',
'tarballtemplate': 'https://codeload.{domain}/{user}/{project}/tar.gz/{committish}'
},
bitbucket: {
'protocols': [ 'git+ssh', 'git+https', 'ssh', 'https' ],
'domain': 'bitbucket.org',
'treepath': 'src',
'tarballtemplate': 'https://{domain}/{user}/{project}/get/{committish}.tar.gz'
},
gitlab: {
'protocols': [ 'git+ssh', 'git+https', 'ssh', 'https' ],
'domain': 'gitlab.com',
'treepath': 'tree',
'bugstemplate': 'https://{domain}/{user}/{project}/issues',
'httpstemplate': 'git+https://{auth@}{domain}/{user}/{projectPath}.git{#committish}',
'tarballtemplate': 'https://{domain}/{user}/{project}/repository/archive.tar.gz?ref={committish}',
'pathmatch': /^[/]([^/]+)[/](.+?)(?:[.]git|[/])?$/
},
gist: {
'protocols': [ 'git', 'git+ssh', 'git+https', 'ssh', 'https' ],
'domain': 'gist.github.com',
'pathmatch': /^[/](?:([^/]+)[/])?([a-z0-9]{32,})(?:[.]git)?$/,
'filetemplate': 'https://gist.githubusercontent.com/{user}/{project}/raw{/committish}/{path}',
'bugstemplate': 'https://{domain}/{project}',
'gittemplate': 'git://{domain}/{project}.git{#committish}',
'sshtemplate': 'git@{domain}:/{project}.git{#committish}',
'sshurltemplate': 'git+ssh://git@{domain}/{project}.git{#committish}',
'browsetemplate': 'https://{domain}/{project}{/committish}',
'browsefiletemplate': 'https://{domain}/{project}{/committish}{#path}',
'docstemplate': 'https://{domain}/{project}{/committish}',
'httpstemplate': 'git+https://{domain}/{project}.git{#committish}',
'shortcuttemplate': '{type}:{project}{#committish}',
'pathtemplate': '{project}{#committish}',
'tarballtemplate': 'https://codeload.github.com/gist/{project}/tar.gz/{committish}',
'hashformat': function (fragment) {
return 'file-' + formatHashFragment(fragment)
}
}
}
var gitHostDefaults = {
'sshtemplate': 'git@{domain}:{user}/{project}.git{#committish}',
'sshurltemplate': 'git+ssh://git@{domain}/{user}/{project}.git{#committish}',
'browsetemplate': 'https://{domain}/{user}/{project}{/tree/committish}',
'browsefiletemplate': 'https://{domain}/{user}/{project}/{treepath}/{committish}/{path}{#fragment}',
'docstemplate': 'https://{domain}/{user}/{project}{/tree/committish}#readme',
'httpstemplate': 'git+https://{auth@}{domain}/{user}/{project}.git{#committish}',
'filetemplate': 'https://{domain}/{user}/{project}/raw/{committish}/{path}',
'shortcuttemplate': '{type}:{user}/{project}{#committish}',
'pathtemplate': '{user}/{project}{#committish}',
'pathmatch': /^[/]([^/]+)[/]([^/]+?)(?:[.]git|[/])?$/,
'hashformat': formatHashFragment
}
Object.keys(gitHosts).forEach(function (name) {
Object.keys(gitHostDefaults).forEach(function (key) {
if (gitHosts[name][key]) return
gitHosts[name][key] = gitHostDefaults[key]
})
gitHosts[name].protocols_re = RegExp('^(' +
gitHosts[name].protocols.map(function (protocol) {
return protocol.replace(/([\\+*{}()[\]$^|])/g, '\\$1')
}).join('|') + '):$')
})
function formatHashFragment (fragment)
|
{
return fragment.toLowerCase().replace(/^\W+|\/|\W+$/g, '').replace(/\W+/g, '-')
}
|
identifier_body
|
|
threads.rs
|
//! Threading code.
use std::mem;
use remacs_macros::lisp_fn;
use remacs_sys::{current_thread, thread_state};
use buffers::LispBufferRef;
use lisp::{ExternalPtr, LispObject};
use lisp::defsubr;
pub type ThreadStateRef = ExternalPtr<thread_state>;
pub struct ThreadState {}
impl ThreadState {
pub fn current_buffer() -> LispBufferRef {
unsafe { mem::transmute((*current_thread).m_current_buffer) }
}
}
impl ThreadStateRef {
#[inline]
pub fn name(self) -> LispObject {
LispObject::from_raw(self.name)
}
#[inline]
pub fn is_alive(self) -> bool {
!self.m_specpdl.is_null()
}
}
/// Return the name of the THREAD.
/// The name is the same object that was passed to `make-thread'.
#[lisp_fn]
pub fn thread_name(thread: ThreadStateRef) -> LispObject
|
/// Return t if THREAD is alive, or nil if it has exited.
#[lisp_fn]
pub fn thread_alive_p(thread: ThreadStateRef) -> bool {
thread.is_alive()
}
include!(concat!(env!("OUT_DIR"), "/threads_exports.rs"));
|
{
thread.name()
}
|
identifier_body
|
threads.rs
|
//! Threading code.
use std::mem;
use remacs_macros::lisp_fn;
use remacs_sys::{current_thread, thread_state};
use buffers::LispBufferRef;
use lisp::{ExternalPtr, LispObject};
use lisp::defsubr;
pub type ThreadStateRef = ExternalPtr<thread_state>;
pub struct ThreadState {}
impl ThreadState {
pub fn current_buffer() -> LispBufferRef {
unsafe { mem::transmute((*current_thread).m_current_buffer) }
}
}
impl ThreadStateRef {
#[inline]
pub fn name(self) -> LispObject {
LispObject::from_raw(self.name)
}
#[inline]
pub fn is_alive(self) -> bool {
!self.m_specpdl.is_null()
}
}
/// Return the name of the THREAD.
/// The name is the same object that was passed to `make-thread'.
#[lisp_fn]
pub fn thread_name(thread: ThreadStateRef) -> LispObject {
thread.name()
}
/// Return t if THREAD is alive, or nil if it has exited.
#[lisp_fn]
pub fn
|
(thread: ThreadStateRef) -> bool {
thread.is_alive()
}
include!(concat!(env!("OUT_DIR"), "/threads_exports.rs"));
|
thread_alive_p
|
identifier_name
|
threads.rs
|
//! Threading code.
use std::mem;
use remacs_macros::lisp_fn;
use remacs_sys::{current_thread, thread_state};
use buffers::LispBufferRef;
use lisp::{ExternalPtr, LispObject};
use lisp::defsubr;
pub type ThreadStateRef = ExternalPtr<thread_state>;
pub struct ThreadState {}
impl ThreadState {
pub fn current_buffer() -> LispBufferRef {
unsafe { mem::transmute((*current_thread).m_current_buffer) }
}
}
impl ThreadStateRef {
#[inline]
pub fn name(self) -> LispObject {
LispObject::from_raw(self.name)
}
#[inline]
pub fn is_alive(self) -> bool {
!self.m_specpdl.is_null()
}
|
#[lisp_fn]
pub fn thread_name(thread: ThreadStateRef) -> LispObject {
thread.name()
}
/// Return t if THREAD is alive, or nil if it has exited.
#[lisp_fn]
pub fn thread_alive_p(thread: ThreadStateRef) -> bool {
thread.is_alive()
}
include!(concat!(env!("OUT_DIR"), "/threads_exports.rs"));
|
}
/// Return the name of the THREAD.
/// The name is the same object that was passed to `make-thread'.
|
random_line_split
|
bad-lit-suffixes.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags: -Z parse-only
extern
"C"suffix //~ ERROR ABI spec with a suffix is invalid
fn
|
() {}
extern
"C"suffix //~ ERROR ABI spec with a suffix is invalid
{}
fn main() {
""suffix; //~ ERROR str literal with a suffix is invalid
b""suffix; //~ ERROR binary str literal with a suffix is invalid
r#""#suffix; //~ ERROR str literal with a suffix is invalid
br#""#suffix; //~ ERROR binary str literal with a suffix is invalid
'a'suffix; //~ ERROR char literal with a suffix is invalid
b'a'suffix; //~ ERROR byte literal with a suffix is invalid
1234u1024; //~ ERROR invalid width `1024` for integer literal
1234i1024; //~ ERROR invalid width `1024` for integer literal
1234f1024; //~ ERROR invalid width `1024` for float literal
1234.5f1024; //~ ERROR invalid width `1024` for float literal
1234suffix; //~ ERROR invalid suffix `suffix` for numeric literal
0b101suffix; //~ ERROR invalid suffix `suffix` for numeric literal
1.0suffix; //~ ERROR invalid suffix `suffix` for float literal
1.0e10suffix; //~ ERROR invalid suffix `suffix` for float literal
}
|
foo
|
identifier_name
|
bad-lit-suffixes.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags: -Z parse-only
extern
"C"suffix //~ ERROR ABI spec with a suffix is invalid
fn foo() {}
extern
"C"suffix //~ ERROR ABI spec with a suffix is invalid
{}
fn main() {
""suffix; //~ ERROR str literal with a suffix is invalid
b""suffix; //~ ERROR binary str literal with a suffix is invalid
r#""#suffix; //~ ERROR str literal with a suffix is invalid
br#""#suffix; //~ ERROR binary str literal with a suffix is invalid
'a'suffix; //~ ERROR char literal with a suffix is invalid
b'a'suffix; //~ ERROR byte literal with a suffix is invalid
|
1234i1024; //~ ERROR invalid width `1024` for integer literal
1234f1024; //~ ERROR invalid width `1024` for float literal
1234.5f1024; //~ ERROR invalid width `1024` for float literal
1234suffix; //~ ERROR invalid suffix `suffix` for numeric literal
0b101suffix; //~ ERROR invalid suffix `suffix` for numeric literal
1.0suffix; //~ ERROR invalid suffix `suffix` for float literal
1.0e10suffix; //~ ERROR invalid suffix `suffix` for float literal
}
|
1234u1024; //~ ERROR invalid width `1024` for integer literal
|
random_line_split
|
bad-lit-suffixes.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags: -Z parse-only
extern
"C"suffix //~ ERROR ABI spec with a suffix is invalid
fn foo()
|
extern
"C"suffix //~ ERROR ABI spec with a suffix is invalid
{}
fn main() {
""suffix; //~ ERROR str literal with a suffix is invalid
b""suffix; //~ ERROR binary str literal with a suffix is invalid
r#""#suffix; //~ ERROR str literal with a suffix is invalid
br#""#suffix; //~ ERROR binary str literal with a suffix is invalid
'a'suffix; //~ ERROR char literal with a suffix is invalid
b'a'suffix; //~ ERROR byte literal with a suffix is invalid
1234u1024; //~ ERROR invalid width `1024` for integer literal
1234i1024; //~ ERROR invalid width `1024` for integer literal
1234f1024; //~ ERROR invalid width `1024` for float literal
1234.5f1024; //~ ERROR invalid width `1024` for float literal
1234suffix; //~ ERROR invalid suffix `suffix` for numeric literal
0b101suffix; //~ ERROR invalid suffix `suffix` for numeric literal
1.0suffix; //~ ERROR invalid suffix `suffix` for float literal
1.0e10suffix; //~ ERROR invalid suffix `suffix` for float literal
}
|
{}
|
identifier_body
|
generic-fn.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// -*- rust -*-
fn id<T:Copy>(x: T) -> T { return x; }
struct Triple {x: int, y: int, z: int}
|
pub fn main() {
let mut x = 62;
let mut y = 63;
let a = 'a';
let mut b = 'b';
let p: Triple = Triple {x: 65, y: 66, z: 67};
let mut q: Triple = Triple {x: 68, y: 69, z: 70};
y = id::<int>(x);
debug!(y);
assert!((x == y));
b = id::<char>(a);
debug!(b);
assert!((a == b));
q = id::<Triple>(p);
x = p.z;
y = q.z;
debug!(y);
assert!((x == y));
}
|
random_line_split
|
|
generic-fn.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// -*- rust -*-
fn id<T:Copy>(x: T) -> T { return x; }
struct Triple {x: int, y: int, z: int}
pub fn main()
|
{
let mut x = 62;
let mut y = 63;
let a = 'a';
let mut b = 'b';
let p: Triple = Triple {x: 65, y: 66, z: 67};
let mut q: Triple = Triple {x: 68, y: 69, z: 70};
y = id::<int>(x);
debug!(y);
assert!((x == y));
b = id::<char>(a);
debug!(b);
assert!((a == b));
q = id::<Triple>(p);
x = p.z;
y = q.z;
debug!(y);
assert!((x == y));
}
|
identifier_body
|
|
generic-fn.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// -*- rust -*-
fn id<T:Copy>(x: T) -> T { return x; }
struct Triple {x: int, y: int, z: int}
pub fn
|
() {
let mut x = 62;
let mut y = 63;
let a = 'a';
let mut b = 'b';
let p: Triple = Triple {x: 65, y: 66, z: 67};
let mut q: Triple = Triple {x: 68, y: 69, z: 70};
y = id::<int>(x);
debug!(y);
assert!((x == y));
b = id::<char>(a);
debug!(b);
assert!((a == b));
q = id::<Triple>(p);
x = p.z;
y = q.z;
debug!(y);
assert!((x == y));
}
|
main
|
identifier_name
|
istanbul-reports-tests.ts
|
create('clover');
create('clover', { file: 'foo', projectRoot: 'bar' });
create('cobertura');
create('cobertura', { file: 'foo', projectRoot: 'bar' });
create('html-spa');
create('html-spa', { skipEmpty: true, metricsToShow: ['branches', 'lines', 'statements'] });
create('html-spa', {
linkMapper: {
getPath: () => 'foo',
relativePath: () => 'foo',
assetPath: () => 'foo',
},
subdir: 'foo',
});
create('html');
create('html', { verbose: false, subdir: 'foo' });
create('html', { skipEmpty: true });
create('html', {
linkMapper: {
getPath: () => 'foo',
relativePath: () => 'foo',
assetPath: () => 'foo',
},
});
create('json');
create('json', { file: 'foo' });
create('json-summary');
create('json-summary', { file: 'foo' });
create('lcov');
create('lcov', { file: 'foo', projectRoot: 'bar' });
create('lcovonly');
create('lcovonly', { file: 'foo' });
create('lcovonly', { projectRoot: 'bar' });
create('none');
create('teamcity');
create('teamcity', { file: 'foo' });
create('teamcity', { file: 'foo', blockName: 'bar' });
create('text');
create('text', { file: 'foo' });
create('text', { file: 'foo', maxCols: 3 });
create('text', { file: 'foo', maxCols: 3, skipFull: true, skipEmpty: true });
create('text-lcov');
create('text-lcov', { projectRoot: 'foo' });
create('text-summary');
create('text-summary', { file: 'foo' });
|
import { create } from 'istanbul-reports';
|
random_line_split
|
|
filterScopeIdsCollector.ts
|
/*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/// <reference path="../../_references.ts"/>
module powerbi.data {
export interface FilterValueScopeIdsContainer {
isNot: boolean;
scopeIds: DataViewScopeIdentity[];
}
export module SQExprConverter {
export function asScopeIdsContainer(filter: SemanticFilter, fieldSQExprs: SQExpr[]): FilterValueScopeIdsContainer {
debug.assertValue(filter, 'filter');
debug.assertValue(fieldSQExprs, 'fieldSQExprs');
debug.assert(fieldSQExprs.length > 0, 'There should be at least 1 field expression.');
let filterItems = filter.conditions();
debug.assert(filterItems.length === 1, 'There should be exactly 1 filter expression.');
let filterItem = filterItems[0];
if (filterItem) {
let visitor = new FilterScopeIdsCollectorVisitor(fieldSQExprs);
if (filterItem.accept(visitor))
return visitor.getResult();
}
}
/** Gets a comparand value from the given DataViewScopeIdentity. */
export function getFirstComparandValue(identity: DataViewScopeIdentity): any {
debug.assertValue(identity, 'identity');
let comparandExpr = identity.expr.accept(new FindComparandVisitor());
if (comparandExpr)
return comparandExpr.value;
}
}
/** Collect filter values from simple semantic filter that is similar to 'is any of' or 'is not any of', getResult() returns a collection of scopeIds.**/
class FilterScopeIdsCollectorVisitor extends DefaultSQExprVisitor<boolean>{
private isRoot: boolean;
private isNot: boolean;
private keyExprsCount: number;
private valueExprs: SQExpr[];
private fieldExprs: SQExpr[];
constructor(fieldSQExprs:SQExpr[]) {
super();
this.isRoot = true;
this.isNot = false;
this.keyExprsCount = null;
this.valueExprs = [];
// Need to drop the entitylet before create the scopeIdentity. The ScopeIdentity created on the client is used to
// compare the ScopeIdentity came from the server. But server doesn't have the entity variable concept, so we will
// need to drop it in order to use JsonComparer.
this.fieldExprs = [];
for (let field of fieldSQExprs) {
this.fieldExprs.push(SQExprBuilder.removeEntityVariables(field));
}
}
public getResult(): FilterValueScopeIdsContainer {
debug.assert(this.fieldExprs.length > 0, 'fieldExprs has at least one fieldExpr');
let valueExprs = this.valueExprs,
scopeIds: DataViewScopeIdentity[] = [];
let valueCount: number = this.keyExprsCount || 1;
for (let startIndex = 0, endIndex = valueCount, len = valueExprs.length; startIndex < len && endIndex <= len;) {
let values = valueExprs.slice(startIndex, endIndex);
scopeIds.push(FilterScopeIdsCollectorVisitor.getScopeIdentity(this.fieldExprs, values));
startIndex += valueCount;
endIndex += valueCount;
}
return {
isNot: this.isNot,
scopeIds: scopeIds,
};
}
private static getScopeIdentity(fieldExprs: SQExpr[], valueExprs: SQExpr[]): DataViewScopeIdentity {
debug.assert(valueExprs.length > 0, 'valueExprs has at least one valueExpr');
debug.assert(valueExprs.length === fieldExprs.length, 'fieldExpr and valueExpr count should match');
let compoundSQExpr: SQExpr;
for (let i = 0, len = fieldExprs.length; i < len; i++) {
let equalsExpr = SQExprBuilder.equal(fieldExprs[i], valueExprs[i]);
if (!compoundSQExpr)
compoundSQExpr = equalsExpr;
else
compoundSQExpr = SQExprBuilder.and(compoundSQExpr, equalsExpr);
}
return createDataViewScopeIdentity(compoundSQExpr);
}
public visitOr(expr: SQOrExpr): boolean {
if (this.keyExprsCount !== null)
return this.unsupportedSQExpr();
this.isRoot = false;
return expr.left.accept(this) && expr.right.accept(this);
}
public visitNot(expr: SQNotExpr): boolean {
if (!this.isRoot)
return this.unsupportedSQExpr();
this.isNot = true;
return expr.arg.accept(this);
}
public visitConstant(expr: SQConstantExpr): boolean {
if (this.isRoot && expr.type.primitiveType === PrimitiveType.Null)
return this.unsupportedSQExpr();
this.valueExprs.push(expr);
return true;
}
public visitCompare(expr: SQCompareExpr): boolean {
if (this.keyExprsCount !== null)
return this.unsupportedSQExpr();
this.isRoot = false;
if (expr.kind !== QueryComparisonKind.Equal)
return this.unsupportedSQExpr();
return expr.left.accept(this) && expr.right.accept(this);
}
public visitIn(expr: SQInExpr): boolean {
this.keyExprsCount = 0;
let result: boolean;
this.isRoot = false;
for (let arg of expr.args) {
result = arg.accept(this);
if (!result)
return this.unsupportedSQExpr();
this.keyExprsCount++;
}
|
let jlen = valueTuple.length;
debug.assert(jlen === this.keyExprsCount, "keys count and values count should match");
for (let value of valueTuple) {
result = value.accept(this);
if (!result)
return this.unsupportedSQExpr();
}
}
return result;
}
public visitColumnRef(expr: SQColumnRefExpr): boolean {
if (this.isRoot)
return this.unsupportedSQExpr();
let fixedExpr = SQExprBuilder.removeEntityVariables(expr);
if (this.keyExprsCount !== null)
return SQExpr.equals(this.fieldExprs[this.keyExprsCount], fixedExpr);
return SQExpr.equals(this.fieldExprs[0], fixedExpr);
}
public visitDefaultValue(expr: SQDefaultValueExpr): boolean {
if (this.isRoot || this.keyExprsCount !== null)
return this.unsupportedSQExpr();
this.valueExprs.push(expr);
return true;
}
public visitAnyValue(expr: SQAnyValueExpr): boolean {
if (this.isRoot || this.keyExprsCount !== null)
return this.unsupportedSQExpr();
this.valueExprs.push(expr);
return true;
}
public visitDefault(expr: SQExpr): boolean {
return this.unsupportedSQExpr();
}
private unsupportedSQExpr(): boolean {
return false;
}
}
class FindComparandVisitor extends DefaultSQExprVisitor<SQConstantExpr> {
public visitAnd(expr: SQAndExpr): SQConstantExpr {
return expr.left.accept(this) || expr.right.accept(this);
}
public visitCompare(expr: SQCompareExpr): SQConstantExpr {
if (expr.kind === QueryComparisonKind.Equal) {
if (expr.right instanceof SQConstantExpr)
return <SQConstantExpr>expr.right;
if (expr.left instanceof SQConstantExpr)
return <SQConstantExpr>expr.left;
}
}
}
}
|
if (this.keyExprsCount !== this.fieldExprs.length)
return this.unsupportedSQExpr();
let values = expr.values;
for (let valueTuple of values) {
|
random_line_split
|
filterScopeIdsCollector.ts
|
/*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/// <reference path="../../_references.ts"/>
module powerbi.data {
export interface FilterValueScopeIdsContainer {
isNot: boolean;
scopeIds: DataViewScopeIdentity[];
}
export module SQExprConverter {
export function asScopeIdsContainer(filter: SemanticFilter, fieldSQExprs: SQExpr[]): FilterValueScopeIdsContainer {
debug.assertValue(filter, 'filter');
debug.assertValue(fieldSQExprs, 'fieldSQExprs');
debug.assert(fieldSQExprs.length > 0, 'There should be at least 1 field expression.');
let filterItems = filter.conditions();
debug.assert(filterItems.length === 1, 'There should be exactly 1 filter expression.');
let filterItem = filterItems[0];
if (filterItem) {
let visitor = new FilterScopeIdsCollectorVisitor(fieldSQExprs);
if (filterItem.accept(visitor))
return visitor.getResult();
}
}
/** Gets a comparand value from the given DataViewScopeIdentity. */
export function getFirstComparandValue(identity: DataViewScopeIdentity): any {
debug.assertValue(identity, 'identity');
let comparandExpr = identity.expr.accept(new FindComparandVisitor());
if (comparandExpr)
return comparandExpr.value;
}
}
/** Collect filter values from simple semantic filter that is similar to 'is any of' or 'is not any of', getResult() returns a collection of scopeIds.**/
class FilterScopeIdsCollectorVisitor extends DefaultSQExprVisitor<boolean>{
private isRoot: boolean;
private isNot: boolean;
private keyExprsCount: number;
private valueExprs: SQExpr[];
private fieldExprs: SQExpr[];
constructor(fieldSQExprs:SQExpr[]) {
super();
this.isRoot = true;
this.isNot = false;
this.keyExprsCount = null;
this.valueExprs = [];
// Need to drop the entitylet before create the scopeIdentity. The ScopeIdentity created on the client is used to
// compare the ScopeIdentity came from the server. But server doesn't have the entity variable concept, so we will
// need to drop it in order to use JsonComparer.
this.fieldExprs = [];
for (let field of fieldSQExprs) {
this.fieldExprs.push(SQExprBuilder.removeEntityVariables(field));
}
}
public getResult(): FilterValueScopeIdsContainer {
debug.assert(this.fieldExprs.length > 0, 'fieldExprs has at least one fieldExpr');
let valueExprs = this.valueExprs,
scopeIds: DataViewScopeIdentity[] = [];
let valueCount: number = this.keyExprsCount || 1;
for (let startIndex = 0, endIndex = valueCount, len = valueExprs.length; startIndex < len && endIndex <= len;) {
let values = valueExprs.slice(startIndex, endIndex);
scopeIds.push(FilterScopeIdsCollectorVisitor.getScopeIdentity(this.fieldExprs, values));
startIndex += valueCount;
endIndex += valueCount;
}
return {
isNot: this.isNot,
scopeIds: scopeIds,
};
}
private static getScopeIdentity(fieldExprs: SQExpr[], valueExprs: SQExpr[]): DataViewScopeIdentity {
debug.assert(valueExprs.length > 0, 'valueExprs has at least one valueExpr');
debug.assert(valueExprs.length === fieldExprs.length, 'fieldExpr and valueExpr count should match');
let compoundSQExpr: SQExpr;
for (let i = 0, len = fieldExprs.length; i < len; i++) {
|
return createDataViewScopeIdentity(compoundSQExpr);
}
public visitOr(expr: SQOrExpr): boolean {
if (this.keyExprsCount !== null)
return this.unsupportedSQExpr();
this.isRoot = false;
return expr.left.accept(this) && expr.right.accept(this);
}
public visitNot(expr: SQNotExpr): boolean {
if (!this.isRoot)
return this.unsupportedSQExpr();
this.isNot = true;
return expr.arg.accept(this);
}
public visitConstant(expr: SQConstantExpr): boolean {
if (this.isRoot && expr.type.primitiveType === PrimitiveType.Null)
return this.unsupportedSQExpr();
this.valueExprs.push(expr);
return true;
}
public visitCompare(expr: SQCompareExpr): boolean {
if (this.keyExprsCount !== null)
return this.unsupportedSQExpr();
this.isRoot = false;
if (expr.kind !== QueryComparisonKind.Equal)
return this.unsupportedSQExpr();
return expr.left.accept(this) && expr.right.accept(this);
}
public visitIn(expr: SQInExpr): boolean {
this.keyExprsCount = 0;
let result: boolean;
this.isRoot = false;
for (let arg of expr.args) {
result = arg.accept(this);
if (!result)
return this.unsupportedSQExpr();
this.keyExprsCount++;
}
if (this.keyExprsCount !== this.fieldExprs.length)
return this.unsupportedSQExpr();
let values = expr.values;
for (let valueTuple of values) {
let jlen = valueTuple.length;
debug.assert(jlen === this.keyExprsCount, "keys count and values count should match");
for (let value of valueTuple) {
result = value.accept(this);
if (!result)
return this.unsupportedSQExpr();
}
}
return result;
}
public visitColumnRef(expr: SQColumnRefExpr): boolean {
if (this.isRoot)
return this.unsupportedSQExpr();
let fixedExpr = SQExprBuilder.removeEntityVariables(expr);
if (this.keyExprsCount !== null)
return SQExpr.equals(this.fieldExprs[this.keyExprsCount], fixedExpr);
return SQExpr.equals(this.fieldExprs[0], fixedExpr);
}
public visitDefaultValue(expr: SQDefaultValueExpr): boolean {
if (this.isRoot || this.keyExprsCount !== null)
return this.unsupportedSQExpr();
this.valueExprs.push(expr);
return true;
}
public visitAnyValue(expr: SQAnyValueExpr): boolean {
if (this.isRoot || this.keyExprsCount !== null)
return this.unsupportedSQExpr();
this.valueExprs.push(expr);
return true;
}
public visitDefault(expr: SQExpr): boolean {
return this.unsupportedSQExpr();
}
private unsupportedSQExpr(): boolean {
return false;
}
}
class FindComparandVisitor extends DefaultSQExprVisitor<SQConstantExpr> {
public visitAnd(expr: SQAndExpr): SQConstantExpr {
return expr.left.accept(this) || expr.right.accept(this);
}
public visitCompare(expr: SQCompareExpr): SQConstantExpr {
if (expr.kind === QueryComparisonKind.Equal) {
if (expr.right instanceof SQConstantExpr)
return <SQConstantExpr>expr.right;
if (expr.left instanceof SQConstantExpr)
return <SQConstantExpr>expr.left;
}
}
}
}
|
let equalsExpr = SQExprBuilder.equal(fieldExprs[i], valueExprs[i]);
if (!compoundSQExpr)
compoundSQExpr = equalsExpr;
else
compoundSQExpr = SQExprBuilder.and(compoundSQExpr, equalsExpr);
}
|
conditional_block
|
filterScopeIdsCollector.ts
|
/*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/// <reference path="../../_references.ts"/>
module powerbi.data {
export interface FilterValueScopeIdsContainer {
isNot: boolean;
scopeIds: DataViewScopeIdentity[];
}
export module SQExprConverter {
export function asScopeIdsContainer(filter: SemanticFilter, fieldSQExprs: SQExpr[]): FilterValueScopeIdsContainer {
debug.assertValue(filter, 'filter');
debug.assertValue(fieldSQExprs, 'fieldSQExprs');
debug.assert(fieldSQExprs.length > 0, 'There should be at least 1 field expression.');
let filterItems = filter.conditions();
debug.assert(filterItems.length === 1, 'There should be exactly 1 filter expression.');
let filterItem = filterItems[0];
if (filterItem) {
let visitor = new FilterScopeIdsCollectorVisitor(fieldSQExprs);
if (filterItem.accept(visitor))
return visitor.getResult();
}
}
/** Gets a comparand value from the given DataViewScopeIdentity. */
export function getFirstComparandValue(identity: DataViewScopeIdentity): any {
debug.assertValue(identity, 'identity');
let comparandExpr = identity.expr.accept(new FindComparandVisitor());
if (comparandExpr)
return comparandExpr.value;
}
}
/** Collect filter values from simple semantic filter that is similar to 'is any of' or 'is not any of', getResult() returns a collection of scopeIds.**/
class FilterScopeIdsCollectorVisitor extends DefaultSQExprVisitor<boolean>{
private isRoot: boolean;
private isNot: boolean;
private keyExprsCount: number;
private valueExprs: SQExpr[];
private fieldExprs: SQExpr[];
constructor(fieldSQExprs:SQExpr[]) {
super();
this.isRoot = true;
this.isNot = false;
this.keyExprsCount = null;
this.valueExprs = [];
// Need to drop the entitylet before create the scopeIdentity. The ScopeIdentity created on the client is used to
// compare the ScopeIdentity came from the server. But server doesn't have the entity variable concept, so we will
// need to drop it in order to use JsonComparer.
this.fieldExprs = [];
for (let field of fieldSQExprs) {
this.fieldExprs.push(SQExprBuilder.removeEntityVariables(field));
}
}
public getResult(): FilterValueScopeIdsContainer {
debug.assert(this.fieldExprs.length > 0, 'fieldExprs has at least one fieldExpr');
let valueExprs = this.valueExprs,
scopeIds: DataViewScopeIdentity[] = [];
let valueCount: number = this.keyExprsCount || 1;
for (let startIndex = 0, endIndex = valueCount, len = valueExprs.length; startIndex < len && endIndex <= len;) {
let values = valueExprs.slice(startIndex, endIndex);
scopeIds.push(FilterScopeIdsCollectorVisitor.getScopeIdentity(this.fieldExprs, values));
startIndex += valueCount;
endIndex += valueCount;
}
return {
isNot: this.isNot,
scopeIds: scopeIds,
};
}
private static getScopeIdentity(fieldExprs: SQExpr[], valueExprs: SQExpr[]): DataViewScopeIdentity {
debug.assert(valueExprs.length > 0, 'valueExprs has at least one valueExpr');
debug.assert(valueExprs.length === fieldExprs.length, 'fieldExpr and valueExpr count should match');
let compoundSQExpr: SQExpr;
for (let i = 0, len = fieldExprs.length; i < len; i++) {
let equalsExpr = SQExprBuilder.equal(fieldExprs[i], valueExprs[i]);
if (!compoundSQExpr)
compoundSQExpr = equalsExpr;
else
compoundSQExpr = SQExprBuilder.and(compoundSQExpr, equalsExpr);
}
return createDataViewScopeIdentity(compoundSQExpr);
}
public visitOr(expr: SQOrExpr): boolean {
if (this.keyExprsCount !== null)
return this.unsupportedSQExpr();
this.isRoot = false;
return expr.left.accept(this) && expr.right.accept(this);
}
public visitNot(expr: SQNotExpr): boolean {
if (!this.isRoot)
return this.unsupportedSQExpr();
this.isNot = true;
return expr.arg.accept(this);
}
public visitConstant(expr: SQConstantExpr): boolean {
if (this.isRoot && expr.type.primitiveType === PrimitiveType.Null)
return this.unsupportedSQExpr();
this.valueExprs.push(expr);
return true;
}
public visitCompare(expr: SQCompareExpr): boolean {
if (this.keyExprsCount !== null)
return this.unsupportedSQExpr();
this.isRoot = false;
if (expr.kind !== QueryComparisonKind.Equal)
return this.unsupportedSQExpr();
return expr.left.accept(this) && expr.right.accept(this);
}
public visitIn(expr: SQInExpr): boolean {
this.keyExprsCount = 0;
let result: boolean;
this.isRoot = false;
for (let arg of expr.args) {
result = arg.accept(this);
if (!result)
return this.unsupportedSQExpr();
this.keyExprsCount++;
}
if (this.keyExprsCount !== this.fieldExprs.length)
return this.unsupportedSQExpr();
let values = expr.values;
for (let valueTuple of values) {
let jlen = valueTuple.length;
debug.assert(jlen === this.keyExprsCount, "keys count and values count should match");
for (let value of valueTuple) {
result = value.accept(this);
if (!result)
return this.unsupportedSQExpr();
}
}
return result;
}
public visitColumnRef(expr: SQColumnRefExpr): boolean {
if (this.isRoot)
return this.unsupportedSQExpr();
let fixedExpr = SQExprBuilder.removeEntityVariables(expr);
if (this.keyExprsCount !== null)
return SQExpr.equals(this.fieldExprs[this.keyExprsCount], fixedExpr);
return SQExpr.equals(this.fieldExprs[0], fixedExpr);
}
public visitDefaultValue(expr: SQDefaultValueExpr): boolean {
if (this.isRoot || this.keyExprsCount !== null)
return this.unsupportedSQExpr();
this.valueExprs.push(expr);
return true;
}
public visitAnyValue(expr: SQAnyValueExpr): boolean {
if (this.isRoot || this.keyExprsCount !== null)
return this.unsupportedSQExpr();
this.valueExprs.push(expr);
return true;
}
public vi
|
xpr: SQExpr): boolean {
return this.unsupportedSQExpr();
}
private unsupportedSQExpr(): boolean {
return false;
}
}
class FindComparandVisitor extends DefaultSQExprVisitor<SQConstantExpr> {
public visitAnd(expr: SQAndExpr): SQConstantExpr {
return expr.left.accept(this) || expr.right.accept(this);
}
public visitCompare(expr: SQCompareExpr): SQConstantExpr {
if (expr.kind === QueryComparisonKind.Equal) {
if (expr.right instanceof SQConstantExpr)
return <SQConstantExpr>expr.right;
if (expr.left instanceof SQConstantExpr)
return <SQConstantExpr>expr.left;
}
}
}
}
|
sitDefault(e
|
identifier_name
|
Radio.js
|
'use strict';
var _get = require('babel-runtime/helpers/get')['default'];
var _inherits = require('babel-runtime/helpers/inherits')['default'];
var _createClass = require('babel-runtime/helpers/create-class')['default'];
var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];
var _extends = require('babel-runtime/helpers/extends')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _EnhancedSwitch = require('./EnhancedSwitch');
var _EnhancedSwitch2 = _interopRequireDefault(_EnhancedSwitch);
var Radio = (function (_React$Component) {
_inherits(Radio, _React$Component);
function
|
() {
_classCallCheck(this, Radio);
_get(Object.getPrototypeOf(Radio.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(Radio, [{
key: 'getValue',
value: function getValue() {
return this.refs.enhancedSwitch.getValue();
}
}, {
key: 'setChecked',
value: function setChecked(newCheckedValue) {
this.refs.enhancedSwitch.setSwitched(newCheckedValue);
}
}, {
key: 'isChecked',
value: function isChecked() {
return this.refs.enhancedSwitch.isSwitched();
}
}, {
key: 'render',
value: function render() {
var enhancedSwitchProps = {
ref: 'enhancedSwitch',
inputType: 'radio'
};
// labelClassName
return _react2['default'].createElement(_EnhancedSwitch2['default'], _extends({}, this.props, enhancedSwitchProps));
}
}]);
return Radio;
})(_react2['default'].Component);
exports['default'] = Radio;
module.exports = exports['default'];
|
Radio
|
identifier_name
|
Radio.js
|
'use strict';
var _get = require('babel-runtime/helpers/get')['default'];
var _inherits = require('babel-runtime/helpers/inherits')['default'];
var _createClass = require('babel-runtime/helpers/create-class')['default'];
var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];
var _extends = require('babel-runtime/helpers/extends')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _EnhancedSwitch = require('./EnhancedSwitch');
var _EnhancedSwitch2 = _interopRequireDefault(_EnhancedSwitch);
var Radio = (function (_React$Component) {
_inherits(Radio, _React$Component);
function Radio()
|
_createClass(Radio, [{
key: 'getValue',
value: function getValue() {
return this.refs.enhancedSwitch.getValue();
}
}, {
key: 'setChecked',
value: function setChecked(newCheckedValue) {
this.refs.enhancedSwitch.setSwitched(newCheckedValue);
}
}, {
key: 'isChecked',
value: function isChecked() {
return this.refs.enhancedSwitch.isSwitched();
}
}, {
key: 'render',
value: function render() {
var enhancedSwitchProps = {
ref: 'enhancedSwitch',
inputType: 'radio'
};
// labelClassName
return _react2['default'].createElement(_EnhancedSwitch2['default'], _extends({}, this.props, enhancedSwitchProps));
}
}]);
return Radio;
})(_react2['default'].Component);
exports['default'] = Radio;
module.exports = exports['default'];
|
{
_classCallCheck(this, Radio);
_get(Object.getPrototypeOf(Radio.prototype), 'constructor', this).apply(this, arguments);
}
|
identifier_body
|
Radio.js
|
'use strict';
var _get = require('babel-runtime/helpers/get')['default'];
var _inherits = require('babel-runtime/helpers/inherits')['default'];
var _createClass = require('babel-runtime/helpers/create-class')['default'];
var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];
var _extends = require('babel-runtime/helpers/extends')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _EnhancedSwitch = require('./EnhancedSwitch');
var _EnhancedSwitch2 = _interopRequireDefault(_EnhancedSwitch);
var Radio = (function (_React$Component) {
_inherits(Radio, _React$Component);
function Radio() {
_classCallCheck(this, Radio);
_get(Object.getPrototypeOf(Radio.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(Radio, [{
key: 'getValue',
value: function getValue() {
return this.refs.enhancedSwitch.getValue();
}
}, {
key: 'setChecked',
value: function setChecked(newCheckedValue) {
this.refs.enhancedSwitch.setSwitched(newCheckedValue);
}
}, {
key: 'isChecked',
value: function isChecked() {
return this.refs.enhancedSwitch.isSwitched();
}
}, {
key: 'render',
value: function render() {
var enhancedSwitchProps = {
ref: 'enhancedSwitch',
inputType: 'radio'
};
// labelClassName
|
}
}]);
return Radio;
})(_react2['default'].Component);
exports['default'] = Radio;
module.exports = exports['default'];
|
return _react2['default'].createElement(_EnhancedSwitch2['default'], _extends({}, this.props, enhancedSwitchProps));
|
random_line_split
|
getDoc.js
|
import { check } from "meteor/check";
import processDoc from "./processDoc";
/**
* getDoc
* fetch repo profile from github and store in RepoData collection
* @param {Object} doc - mongo style selector for the doc
* @returns {undefined} returns
*/
function
|
(options) {
check(options, Object);
// get repo details
const docRepo = ReDoc.Collections.Repos.findOne({
repo: options.repo
});
// we need to have a repo
if (!docRepo) {
console.log(`redoc/getDocSet: Failed to load repo data for ${options.repo}`);
return false;
}
// TOC item for this doc
const tocItem = ReDoc.Collections.TOC.findOne({
alias: options.alias,
repo: options.repo
});
processDoc({
branch: options.branch,
repo: options.repo,
alias: options.alias,
docRepo,
tocItem
});
}
export default getDoc;
export { flushDocCache };
|
getDoc
|
identifier_name
|
getDoc.js
|
import { check } from "meteor/check";
import processDoc from "./processDoc";
/**
* getDoc
* fetch repo profile from github and store in RepoData collection
* @param {Object} doc - mongo style selector for the doc
* @returns {undefined} returns
*/
function getDoc(options) {
check(options, Object);
// get repo details
const docRepo = ReDoc.Collections.Repos.findOne({
repo: options.repo
});
// we need to have a repo
if (!docRepo)
|
// TOC item for this doc
const tocItem = ReDoc.Collections.TOC.findOne({
alias: options.alias,
repo: options.repo
});
processDoc({
branch: options.branch,
repo: options.repo,
alias: options.alias,
docRepo,
tocItem
});
}
export default getDoc;
export { flushDocCache };
|
{
console.log(`redoc/getDocSet: Failed to load repo data for ${options.repo}`);
return false;
}
|
conditional_block
|
getDoc.js
|
import { check } from "meteor/check";
import processDoc from "./processDoc";
/**
* getDoc
* fetch repo profile from github and store in RepoData collection
* @param {Object} doc - mongo style selector for the doc
* @returns {undefined} returns
*/
function getDoc(options)
|
export default getDoc;
export { flushDocCache };
|
{
check(options, Object);
// get repo details
const docRepo = ReDoc.Collections.Repos.findOne({
repo: options.repo
});
// we need to have a repo
if (!docRepo) {
console.log(`redoc/getDocSet: Failed to load repo data for ${options.repo}`);
return false;
}
// TOC item for this doc
const tocItem = ReDoc.Collections.TOC.findOne({
alias: options.alias,
repo: options.repo
});
processDoc({
branch: options.branch,
repo: options.repo,
alias: options.alias,
docRepo,
tocItem
});
}
|
identifier_body
|
getDoc.js
|
import { check } from "meteor/check";
import processDoc from "./processDoc";
/**
* getDoc
* fetch repo profile from github and store in RepoData collection
* @param {Object} doc - mongo style selector for the doc
* @returns {undefined} returns
*/
function getDoc(options) {
check(options, Object);
// get repo details
const docRepo = ReDoc.Collections.Repos.findOne({
repo: options.repo
});
// we need to have a repo
if (!docRepo) {
console.log(`redoc/getDocSet: Failed to load repo data for ${options.repo}`);
return false;
}
// TOC item for this doc
const tocItem = ReDoc.Collections.TOC.findOne({
alias: options.alias,
repo: options.repo
});
processDoc({
branch: options.branch,
repo: options.repo,
alias: options.alias,
|
}
export default getDoc;
export { flushDocCache };
|
docRepo,
tocItem
});
|
random_line_split
|
stripe.js
|
$('#renseignements').removeClass("disabled");
$('#renseignements').addClass("active");
$('#commande a').append(' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>');
$('#paiement').removeClass("disabled");
$('#paiement').addClass("active");
$('#renseignements a').append(' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>');
//STRIPE
var stripe = Stripe('pk_test_G0WPeLNB9kIYOIeYcOjweQv9');
var elements = stripe.elements();
var commandePrixTotal = '{{commande.commandePrixTotal}}';
var commandeCode = '{{commande.commandeCode}}'
var card = elements.create('card', {
style: {
base: {
iconColor: '#666EE8',
color: '#31325F',
lineHeight: '40px',
fontWeight: 300,
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSize: '15px',
'::placeholder': {
color: '#CFD7E0',
},
},
}
});
card.mount('#card-element');
function setOutcome(result) {
var successElement = document.querySelector('.success');
var errorElement = document.querySelector('.error');
successElement.classList.remove('visible');
errorElement.classList.remove('visible');
if (result.token) {
document.querySelector('.token').value = result.token.id;
successElement.classList.add('visible');
// Submit the form
var form = document.querySelector('form');
form.submit();
} else if (result.error) {
errorElement.textContent = result.error.message;
errorElement.classList.add('visible');
}
}
|
card.on('change', function(event) {
setOutcome(event);
});
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
stripe.createToken(card).then(setOutcome);
});
|
random_line_split
|
|
stripe.js
|
$('#renseignements').removeClass("disabled");
$('#renseignements').addClass("active");
$('#commande a').append(' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>');
$('#paiement').removeClass("disabled");
$('#paiement').addClass("active");
$('#renseignements a').append(' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>');
//STRIPE
var stripe = Stripe('pk_test_G0WPeLNB9kIYOIeYcOjweQv9');
var elements = stripe.elements();
var commandePrixTotal = '{{commande.commandePrixTotal}}';
var commandeCode = '{{commande.commandeCode}}'
var card = elements.create('card', {
style: {
base: {
iconColor: '#666EE8',
color: '#31325F',
lineHeight: '40px',
fontWeight: 300,
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSize: '15px',
'::placeholder': {
color: '#CFD7E0',
},
},
}
});
card.mount('#card-element');
function setOutcome(result) {
var successElement = document.querySelector('.success');
var errorElement = document.querySelector('.error');
successElement.classList.remove('visible');
errorElement.classList.remove('visible');
if (result.token) {
document.querySelector('.token').value = result.token.id;
successElement.classList.add('visible');
// Submit the form
var form = document.querySelector('form');
form.submit();
} else if (result.error)
|
}
card.on('change', function(event) {
setOutcome(event);
});
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
stripe.createToken(card).then(setOutcome);
});
|
{
errorElement.textContent = result.error.message;
errorElement.classList.add('visible');
}
|
conditional_block
|
stripe.js
|
$('#renseignements').removeClass("disabled");
$('#renseignements').addClass("active");
$('#commande a').append(' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>');
$('#paiement').removeClass("disabled");
$('#paiement').addClass("active");
$('#renseignements a').append(' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>');
//STRIPE
var stripe = Stripe('pk_test_G0WPeLNB9kIYOIeYcOjweQv9');
var elements = stripe.elements();
var commandePrixTotal = '{{commande.commandePrixTotal}}';
var commandeCode = '{{commande.commandeCode}}'
var card = elements.create('card', {
style: {
base: {
iconColor: '#666EE8',
color: '#31325F',
lineHeight: '40px',
fontWeight: 300,
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSize: '15px',
'::placeholder': {
color: '#CFD7E0',
},
},
}
});
card.mount('#card-element');
function setOutcome(result)
|
card.on('change', function(event) {
setOutcome(event);
});
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
stripe.createToken(card).then(setOutcome);
});
|
{
var successElement = document.querySelector('.success');
var errorElement = document.querySelector('.error');
successElement.classList.remove('visible');
errorElement.classList.remove('visible');
if (result.token) {
document.querySelector('.token').value = result.token.id;
successElement.classList.add('visible');
// Submit the form
var form = document.querySelector('form');
form.submit();
} else if (result.error) {
errorElement.textContent = result.error.message;
errorElement.classList.add('visible');
}
}
|
identifier_body
|
stripe.js
|
$('#renseignements').removeClass("disabled");
$('#renseignements').addClass("active");
$('#commande a').append(' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>');
$('#paiement').removeClass("disabled");
$('#paiement').addClass("active");
$('#renseignements a').append(' <span class="glyphicon glyphicon-ok" aria-hidden="true"></span>');
//STRIPE
var stripe = Stripe('pk_test_G0WPeLNB9kIYOIeYcOjweQv9');
var elements = stripe.elements();
var commandePrixTotal = '{{commande.commandePrixTotal}}';
var commandeCode = '{{commande.commandeCode}}'
var card = elements.create('card', {
style: {
base: {
iconColor: '#666EE8',
color: '#31325F',
lineHeight: '40px',
fontWeight: 300,
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSize: '15px',
'::placeholder': {
color: '#CFD7E0',
},
},
}
});
card.mount('#card-element');
function
|
(result) {
var successElement = document.querySelector('.success');
var errorElement = document.querySelector('.error');
successElement.classList.remove('visible');
errorElement.classList.remove('visible');
if (result.token) {
document.querySelector('.token').value = result.token.id;
successElement.classList.add('visible');
// Submit the form
var form = document.querySelector('form');
form.submit();
} else if (result.error) {
errorElement.textContent = result.error.message;
errorElement.classList.add('visible');
}
}
card.on('change', function(event) {
setOutcome(event);
});
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
stripe.createToken(card).then(setOutcome);
});
|
setOutcome
|
identifier_name
|
physics.rs
|
//inherited mutability: player is mutable if let is mutable
//todo: Test in ticks
// Implement player acceleration based on ticks between inputs.
// Potentially ticks holding a button and ticks not
// Rotation accel/vel
use game;
use std::cmp::{max, min};
pub use self::collision::collide;
#[deriving(Eq)]
pub enum Direction {
Forward,
Backward,
Still
}
#[deriving(Eq)]
pub enum Rotation {
Left,
Right,
Norot
}
|
p.rotation += PI / 20.0;
}
if p.rot == Right{
p.rotation -= PI / 20.0;
}
}
pub fn accel(p: &mut game::Player){ //mut player:&mut player would allow to play w/ pointer
let (acc, amod) = accel_compute(p.dir, p.accel, p.accel_mod);
if p.velocity >= -0.15 && p.velocity <= 0.15 {
p.velocity += p.accel * 0.0001;
}
if p.velocity < -0.008 {
p.velocity = -0.008;
}
if p.velocity >= 0.008 {
p.velocity = 0.008
}
p.positionx += p.rotation.cos() * p.velocity;
p.positiony += p.rotation.sin() * p.velocity;
p.accel = acc;
p.accel_mod = amod;
}
pub fn accel_compute (dir: Direction, mut accel: f32, mut accel_mod: int) -> (f32, int) {
//this will use accel/accel_mod to compute the rate of increase of acceleration.
if dir == Forward {
let bounds = [
(-85, -75, 25),
(-75, -60, 22),
(-60, -41, 19),
(-40, -15, 17),
(0, 15, 12),
(14, 40, 10),
(40, 60, 8),
(60, 75, 5),
(75, 85, 2)
];
accel_mod = max(accel_mod, -84);
if accel_mod == 0 {
accel_mod = 15;
} else if accel_mod >= -15 && accel_mod < 0 {
accel_mod = 0;
} else {
for &(lower, upper, increment) in bounds.iter() {
if accel_mod >= lower && accel_mod <= upper {
accel_mod += increment;
break
}
}
}
} else if dir == Backward {
let bounds = [
(-85, -75, -10),
(-75, -60, -5),
(-60, -41, -8),
(-40, -15, -10),
(-15, 0, -12),
(15, 40, -17),
(40, 60, -19),
(60, 75, -22),
(75, 85, -25)
];
accel_mod = min(accel_mod, 84);
if accel_mod == 0 {
accel_mod = -15;
} else if accel_mod <= 15 && accel_mod > 0 {
accel_mod = 0;
} else {
for &(lower, upper, increment) in bounds.iter() {
if accel_mod >= lower && accel_mod <= upper {
accel_mod += increment;
break
}
}
}
}
let max = 0.04;
if accel >= -max && accel <= max {
accel += 0.08 * (accel_mod as f32);
} else {
accel = accel.signum() * max;
}
(accel, accel_mod) //returns accel and accel mod
}
mod collision {
use cgmath::angle::Rad;
use cgmath::vector::{Vector, Vector2};
use cgmath::matrix::{Matrix, Matrix2};
use gl::types::GLfloat;
use render::Sprite;
use std::f32::consts::PI;
type V = Vector2<GLfloat>;
fn min(a: GLfloat, b: GLfloat) -> GLfloat {
a.min(b)
}
fn max(a: GLfloat, b: GLfloat) -> GLfloat {
a.max(b)
}
fn slope(a: V, b: V) -> GLfloat {
(a.y - b.y) / (a.x - b.x)
}
fn line_intercept((a1, a2): (V, V), (b1, b2): (V, V)) -> f32 {
let (x1, x2, y1, y2, m1, m2) = (a1.x, b1.x, a1.y, b1.y, slope(a1, a2), slope(b1, b2));
((m1*x1) - (m2*x2) - y1 + y2) / (m1 - m2)
}
fn intersect((a1, a2): (V, V), (b1, b2): (V, V)) -> Option<V> {
debug!("Checking the intersection of the two lines, {} to {} and {} to {}", a1, a2, b1, b2);
let x = line_intercept((a1, a2), (b1, b2));
debug!("The lines, were they infinite, intersect at x = {}", x);
let y = slope(a1, a2)*(x - a1.x) + a1.y;
debug!("The corresponding y is {}", y);
if x >= min(a1.x, a2.x) && x <= max(a1.x, a2.x) {
debug!("It's within the first line's x values");
if x >= min(b1.x, b2.x) && x <= max(b1.x, b2.x) {
debug!("It's within the second line's x values");
if y >= min(a1.y, a2.y) && y <= max(a1.y, a2.y) {
debug!("It's within the first line's y values");
if y >= min(b1.y, b2.y) && y <= max(b1.y, b2.y) {
debug!("It's within the second line's y values");
return Some(Vector2::new(x, y));
}
}
}
}
None
}
#[test]
fn test_intersect() {
let a = Vector2::new(1f32, 1f32);
let b = Vector2::new(-1f32, -1f32);
let c = Vector2::new(-1f32, 1f32);
let d = Vector2::new(1f32, -1f32);
assert_eq!(intersect((a, b), (c, d)), Some(Vector2::new(0f32, 0f32)));
}
/// Determines if two Sprites collide, assuming that they collide iff their
/// (possibly rotated) bounding boxes collide, not using the texture in any
/// way.
pub fn collide(a: &Sprite, b: &Sprite) -> bool {
// make lists of points making up each sprite, transformed with the
// rotation
let mut arot = a.rot;
let mut brot = b.rot;
// make sure their slopes aren't NaN :(
if arot % (PI / 4.0) == 0.0 {
arot += 0.01;
}
if brot % (PI / 4.0) == 0.0 {
brot += 0.01;
}
let amat = Matrix2::from_angle(Rad { s: arot });
let bmat = Matrix2::from_angle(Rad { s: brot });
let pairs = [(0, 1), (1, 2), (2, 3), (3, 0)]; // which indices form lines we care about?
let &Sprite {x, y, width, height, .. } = a;
let apoints = [
amat.mul_v(&Vector2::new(x, y)),
amat.mul_v(&Vector2::new(x + width, y)),
amat.mul_v(&Vector2::new(x + width, y + height)),
amat.mul_v(&Vector2::new(x, y + height))
];
let &Sprite {x, y, width, height, .. } = b;
let bpoints = [
bmat.mul_v(&Vector2::new(x, y)),
bmat.mul_v(&Vector2::new(x + width, y)),
bmat.mul_v(&Vector2::new(x + width, y + height)),
bmat.mul_v(&Vector2::new(x, y + height))
];
for &(a1, a2) in pairs.iter() {
for &(b1, b2) in pairs.iter() {
if intersect((apoints[a1], apoints[a2]), (bpoints[b1], bpoints[b2])) != None {
return true;
}
}
}
false
}
#[test]
fn test_collide() {
use std;
let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
let s2 = Sprite::new(0.5, 0.5, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
assert_eq!(collide(&s1, &s2), true);
unsafe {
// since we're stubbing out the texture
std::cast::forget(s1);
std::cast::forget(s2);
}
let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
let s2 = Sprite::new(1.0, 1.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
assert_eq!(collide(&s1, &s2), true);
unsafe {
// since we're stubbing out the texture
std::cast::forget(s1);
std::cast::forget(s2);
}
let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
let s2 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.5, unsafe { std::mem::uninit() });
assert_eq!(collide(&s1, &s2), true);
unsafe {
// since we're stubbing out the texture
std::cast::forget(s1);
std::cast::forget(s2);
}
}
}
|
pub fn rotate(p: &mut game::Player){
use std::f32::consts::PI;
if p.rot == Left{
|
random_line_split
|
physics.rs
|
//inherited mutability: player is mutable if let is mutable
//todo: Test in ticks
// Implement player acceleration based on ticks between inputs.
// Potentially ticks holding a button and ticks not
// Rotation accel/vel
use game;
use std::cmp::{max, min};
pub use self::collision::collide;
#[deriving(Eq)]
pub enum Direction {
Forward,
Backward,
Still
}
#[deriving(Eq)]
pub enum Rotation {
Left,
Right,
Norot
}
pub fn rotate(p: &mut game::Player){
use std::f32::consts::PI;
if p.rot == Left{
p.rotation += PI / 20.0;
}
if p.rot == Right{
p.rotation -= PI / 20.0;
}
}
pub fn accel(p: &mut game::Player){ //mut player:&mut player would allow to play w/ pointer
let (acc, amod) = accel_compute(p.dir, p.accel, p.accel_mod);
if p.velocity >= -0.15 && p.velocity <= 0.15 {
p.velocity += p.accel * 0.0001;
}
if p.velocity < -0.008 {
p.velocity = -0.008;
}
if p.velocity >= 0.008 {
p.velocity = 0.008
}
p.positionx += p.rotation.cos() * p.velocity;
p.positiony += p.rotation.sin() * p.velocity;
p.accel = acc;
p.accel_mod = amod;
}
pub fn accel_compute (dir: Direction, mut accel: f32, mut accel_mod: int) -> (f32, int) {
//this will use accel/accel_mod to compute the rate of increase of acceleration.
if dir == Forward {
let bounds = [
(-85, -75, 25),
(-75, -60, 22),
(-60, -41, 19),
(-40, -15, 17),
(0, 15, 12),
(14, 40, 10),
(40, 60, 8),
(60, 75, 5),
(75, 85, 2)
];
accel_mod = max(accel_mod, -84);
if accel_mod == 0 {
accel_mod = 15;
} else if accel_mod >= -15 && accel_mod < 0 {
accel_mod = 0;
} else {
for &(lower, upper, increment) in bounds.iter() {
if accel_mod >= lower && accel_mod <= upper {
accel_mod += increment;
break
}
}
}
} else if dir == Backward {
let bounds = [
(-85, -75, -10),
(-75, -60, -5),
(-60, -41, -8),
(-40, -15, -10),
(-15, 0, -12),
(15, 40, -17),
(40, 60, -19),
(60, 75, -22),
(75, 85, -25)
];
accel_mod = min(accel_mod, 84);
if accel_mod == 0 {
accel_mod = -15;
} else if accel_mod <= 15 && accel_mod > 0 {
accel_mod = 0;
} else {
for &(lower, upper, increment) in bounds.iter() {
if accel_mod >= lower && accel_mod <= upper {
accel_mod += increment;
break
}
}
}
}
let max = 0.04;
if accel >= -max && accel <= max {
accel += 0.08 * (accel_mod as f32);
} else {
accel = accel.signum() * max;
}
(accel, accel_mod) //returns accel and accel mod
}
mod collision {
use cgmath::angle::Rad;
use cgmath::vector::{Vector, Vector2};
use cgmath::matrix::{Matrix, Matrix2};
use gl::types::GLfloat;
use render::Sprite;
use std::f32::consts::PI;
type V = Vector2<GLfloat>;
fn min(a: GLfloat, b: GLfloat) -> GLfloat {
a.min(b)
}
fn max(a: GLfloat, b: GLfloat) -> GLfloat {
a.max(b)
}
fn slope(a: V, b: V) -> GLfloat {
(a.y - b.y) / (a.x - b.x)
}
fn line_intercept((a1, a2): (V, V), (b1, b2): (V, V)) -> f32 {
let (x1, x2, y1, y2, m1, m2) = (a1.x, b1.x, a1.y, b1.y, slope(a1, a2), slope(b1, b2));
((m1*x1) - (m2*x2) - y1 + y2) / (m1 - m2)
}
fn intersect((a1, a2): (V, V), (b1, b2): (V, V)) -> Option<V> {
debug!("Checking the intersection of the two lines, {} to {} and {} to {}", a1, a2, b1, b2);
let x = line_intercept((a1, a2), (b1, b2));
debug!("The lines, were they infinite, intersect at x = {}", x);
let y = slope(a1, a2)*(x - a1.x) + a1.y;
debug!("The corresponding y is {}", y);
if x >= min(a1.x, a2.x) && x <= max(a1.x, a2.x) {
debug!("It's within the first line's x values");
if x >= min(b1.x, b2.x) && x <= max(b1.x, b2.x) {
debug!("It's within the second line's x values");
if y >= min(a1.y, a2.y) && y <= max(a1.y, a2.y) {
debug!("It's within the first line's y values");
if y >= min(b1.y, b2.y) && y <= max(b1.y, b2.y) {
debug!("It's within the second line's y values");
return Some(Vector2::new(x, y));
}
}
}
}
None
}
#[test]
fn
|
() {
let a = Vector2::new(1f32, 1f32);
let b = Vector2::new(-1f32, -1f32);
let c = Vector2::new(-1f32, 1f32);
let d = Vector2::new(1f32, -1f32);
assert_eq!(intersect((a, b), (c, d)), Some(Vector2::new(0f32, 0f32)));
}
/// Determines if two Sprites collide, assuming that they collide iff their
/// (possibly rotated) bounding boxes collide, not using the texture in any
/// way.
pub fn collide(a: &Sprite, b: &Sprite) -> bool {
// make lists of points making up each sprite, transformed with the
// rotation
let mut arot = a.rot;
let mut brot = b.rot;
// make sure their slopes aren't NaN :(
if arot % (PI / 4.0) == 0.0 {
arot += 0.01;
}
if brot % (PI / 4.0) == 0.0 {
brot += 0.01;
}
let amat = Matrix2::from_angle(Rad { s: arot });
let bmat = Matrix2::from_angle(Rad { s: brot });
let pairs = [(0, 1), (1, 2), (2, 3), (3, 0)]; // which indices form lines we care about?
let &Sprite {x, y, width, height, .. } = a;
let apoints = [
amat.mul_v(&Vector2::new(x, y)),
amat.mul_v(&Vector2::new(x + width, y)),
amat.mul_v(&Vector2::new(x + width, y + height)),
amat.mul_v(&Vector2::new(x, y + height))
];
let &Sprite {x, y, width, height, .. } = b;
let bpoints = [
bmat.mul_v(&Vector2::new(x, y)),
bmat.mul_v(&Vector2::new(x + width, y)),
bmat.mul_v(&Vector2::new(x + width, y + height)),
bmat.mul_v(&Vector2::new(x, y + height))
];
for &(a1, a2) in pairs.iter() {
for &(b1, b2) in pairs.iter() {
if intersect((apoints[a1], apoints[a2]), (bpoints[b1], bpoints[b2])) != None {
return true;
}
}
}
false
}
#[test]
fn test_collide() {
use std;
let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
let s2 = Sprite::new(0.5, 0.5, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
assert_eq!(collide(&s1, &s2), true);
unsafe {
// since we're stubbing out the texture
std::cast::forget(s1);
std::cast::forget(s2);
}
let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
let s2 = Sprite::new(1.0, 1.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
assert_eq!(collide(&s1, &s2), true);
unsafe {
// since we're stubbing out the texture
std::cast::forget(s1);
std::cast::forget(s2);
}
let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
let s2 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.5, unsafe { std::mem::uninit() });
assert_eq!(collide(&s1, &s2), true);
unsafe {
// since we're stubbing out the texture
std::cast::forget(s1);
std::cast::forget(s2);
}
}
}
|
test_intersect
|
identifier_name
|
physics.rs
|
//inherited mutability: player is mutable if let is mutable
//todo: Test in ticks
// Implement player acceleration based on ticks between inputs.
// Potentially ticks holding a button and ticks not
// Rotation accel/vel
use game;
use std::cmp::{max, min};
pub use self::collision::collide;
#[deriving(Eq)]
pub enum Direction {
Forward,
Backward,
Still
}
#[deriving(Eq)]
pub enum Rotation {
Left,
Right,
Norot
}
pub fn rotate(p: &mut game::Player){
use std::f32::consts::PI;
if p.rot == Left{
p.rotation += PI / 20.0;
}
if p.rot == Right{
p.rotation -= PI / 20.0;
}
}
pub fn accel(p: &mut game::Player){ //mut player:&mut player would allow to play w/ pointer
let (acc, amod) = accel_compute(p.dir, p.accel, p.accel_mod);
if p.velocity >= -0.15 && p.velocity <= 0.15 {
p.velocity += p.accel * 0.0001;
}
if p.velocity < -0.008 {
p.velocity = -0.008;
}
if p.velocity >= 0.008 {
p.velocity = 0.008
}
p.positionx += p.rotation.cos() * p.velocity;
p.positiony += p.rotation.sin() * p.velocity;
p.accel = acc;
p.accel_mod = amod;
}
pub fn accel_compute (dir: Direction, mut accel: f32, mut accel_mod: int) -> (f32, int) {
//this will use accel/accel_mod to compute the rate of increase of acceleration.
if dir == Forward {
let bounds = [
(-85, -75, 25),
(-75, -60, 22),
(-60, -41, 19),
(-40, -15, 17),
(0, 15, 12),
(14, 40, 10),
(40, 60, 8),
(60, 75, 5),
(75, 85, 2)
];
accel_mod = max(accel_mod, -84);
if accel_mod == 0 {
accel_mod = 15;
} else if accel_mod >= -15 && accel_mod < 0 {
accel_mod = 0;
} else {
for &(lower, upper, increment) in bounds.iter() {
if accel_mod >= lower && accel_mod <= upper {
accel_mod += increment;
break
}
}
}
} else if dir == Backward {
let bounds = [
(-85, -75, -10),
(-75, -60, -5),
(-60, -41, -8),
(-40, -15, -10),
(-15, 0, -12),
(15, 40, -17),
(40, 60, -19),
(60, 75, -22),
(75, 85, -25)
];
accel_mod = min(accel_mod, 84);
if accel_mod == 0 {
accel_mod = -15;
} else if accel_mod <= 15 && accel_mod > 0 {
accel_mod = 0;
} else {
for &(lower, upper, increment) in bounds.iter() {
if accel_mod >= lower && accel_mod <= upper {
accel_mod += increment;
break
}
}
}
}
let max = 0.04;
if accel >= -max && accel <= max {
accel += 0.08 * (accel_mod as f32);
} else {
accel = accel.signum() * max;
}
(accel, accel_mod) //returns accel and accel mod
}
mod collision {
use cgmath::angle::Rad;
use cgmath::vector::{Vector, Vector2};
use cgmath::matrix::{Matrix, Matrix2};
use gl::types::GLfloat;
use render::Sprite;
use std::f32::consts::PI;
type V = Vector2<GLfloat>;
fn min(a: GLfloat, b: GLfloat) -> GLfloat {
a.min(b)
}
fn max(a: GLfloat, b: GLfloat) -> GLfloat {
a.max(b)
}
fn slope(a: V, b: V) -> GLfloat {
(a.y - b.y) / (a.x - b.x)
}
fn line_intercept((a1, a2): (V, V), (b1, b2): (V, V)) -> f32 {
let (x1, x2, y1, y2, m1, m2) = (a1.x, b1.x, a1.y, b1.y, slope(a1, a2), slope(b1, b2));
((m1*x1) - (m2*x2) - y1 + y2) / (m1 - m2)
}
fn intersect((a1, a2): (V, V), (b1, b2): (V, V)) -> Option<V> {
debug!("Checking the intersection of the two lines, {} to {} and {} to {}", a1, a2, b1, b2);
let x = line_intercept((a1, a2), (b1, b2));
debug!("The lines, were they infinite, intersect at x = {}", x);
let y = slope(a1, a2)*(x - a1.x) + a1.y;
debug!("The corresponding y is {}", y);
if x >= min(a1.x, a2.x) && x <= max(a1.x, a2.x) {
debug!("It's within the first line's x values");
if x >= min(b1.x, b2.x) && x <= max(b1.x, b2.x) {
debug!("It's within the second line's x values");
if y >= min(a1.y, a2.y) && y <= max(a1.y, a2.y) {
debug!("It's within the first line's y values");
if y >= min(b1.y, b2.y) && y <= max(b1.y, b2.y) {
debug!("It's within the second line's y values");
return Some(Vector2::new(x, y));
}
}
}
}
None
}
#[test]
fn test_intersect() {
let a = Vector2::new(1f32, 1f32);
let b = Vector2::new(-1f32, -1f32);
let c = Vector2::new(-1f32, 1f32);
let d = Vector2::new(1f32, -1f32);
assert_eq!(intersect((a, b), (c, d)), Some(Vector2::new(0f32, 0f32)));
}
/// Determines if two Sprites collide, assuming that they collide iff their
/// (possibly rotated) bounding boxes collide, not using the texture in any
/// way.
pub fn collide(a: &Sprite, b: &Sprite) -> bool
|
#[test]
fn test_collide() {
use std;
let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
let s2 = Sprite::new(0.5, 0.5, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
assert_eq!(collide(&s1, &s2), true);
unsafe {
// since we're stubbing out the texture
std::cast::forget(s1);
std::cast::forget(s2);
}
let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
let s2 = Sprite::new(1.0, 1.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
assert_eq!(collide(&s1, &s2), true);
unsafe {
// since we're stubbing out the texture
std::cast::forget(s1);
std::cast::forget(s2);
}
let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
let s2 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.5, unsafe { std::mem::uninit() });
assert_eq!(collide(&s1, &s2), true);
unsafe {
// since we're stubbing out the texture
std::cast::forget(s1);
std::cast::forget(s2);
}
}
}
|
{
// make lists of points making up each sprite, transformed with the
// rotation
let mut arot = a.rot;
let mut brot = b.rot;
// make sure their slopes aren't NaN :(
if arot % (PI / 4.0) == 0.0 {
arot += 0.01;
}
if brot % (PI / 4.0) == 0.0 {
brot += 0.01;
}
let amat = Matrix2::from_angle(Rad { s: arot });
let bmat = Matrix2::from_angle(Rad { s: brot });
let pairs = [(0, 1), (1, 2), (2, 3), (3, 0)]; // which indices form lines we care about?
let &Sprite {x, y, width, height, .. } = a;
let apoints = [
amat.mul_v(&Vector2::new(x, y)),
amat.mul_v(&Vector2::new(x + width, y)),
amat.mul_v(&Vector2::new(x + width, y + height)),
amat.mul_v(&Vector2::new(x, y + height))
];
let &Sprite {x, y, width, height, .. } = b;
let bpoints = [
bmat.mul_v(&Vector2::new(x, y)),
bmat.mul_v(&Vector2::new(x + width, y)),
bmat.mul_v(&Vector2::new(x + width, y + height)),
bmat.mul_v(&Vector2::new(x, y + height))
];
for &(a1, a2) in pairs.iter() {
for &(b1, b2) in pairs.iter() {
if intersect((apoints[a1], apoints[a2]), (bpoints[b1], bpoints[b2])) != None {
return true;
}
}
}
false
}
|
identifier_body
|
physics.rs
|
//inherited mutability: player is mutable if let is mutable
//todo: Test in ticks
// Implement player acceleration based on ticks between inputs.
// Potentially ticks holding a button and ticks not
// Rotation accel/vel
use game;
use std::cmp::{max, min};
pub use self::collision::collide;
#[deriving(Eq)]
pub enum Direction {
Forward,
Backward,
Still
}
#[deriving(Eq)]
pub enum Rotation {
Left,
Right,
Norot
}
pub fn rotate(p: &mut game::Player){
use std::f32::consts::PI;
if p.rot == Left{
p.rotation += PI / 20.0;
}
if p.rot == Right{
p.rotation -= PI / 20.0;
}
}
pub fn accel(p: &mut game::Player){ //mut player:&mut player would allow to play w/ pointer
let (acc, amod) = accel_compute(p.dir, p.accel, p.accel_mod);
if p.velocity >= -0.15 && p.velocity <= 0.15 {
p.velocity += p.accel * 0.0001;
}
if p.velocity < -0.008 {
p.velocity = -0.008;
}
if p.velocity >= 0.008 {
p.velocity = 0.008
}
p.positionx += p.rotation.cos() * p.velocity;
p.positiony += p.rotation.sin() * p.velocity;
p.accel = acc;
p.accel_mod = amod;
}
pub fn accel_compute (dir: Direction, mut accel: f32, mut accel_mod: int) -> (f32, int) {
//this will use accel/accel_mod to compute the rate of increase of acceleration.
if dir == Forward {
let bounds = [
(-85, -75, 25),
(-75, -60, 22),
(-60, -41, 19),
(-40, -15, 17),
(0, 15, 12),
(14, 40, 10),
(40, 60, 8),
(60, 75, 5),
(75, 85, 2)
];
accel_mod = max(accel_mod, -84);
if accel_mod == 0 {
accel_mod = 15;
} else if accel_mod >= -15 && accel_mod < 0 {
accel_mod = 0;
} else {
for &(lower, upper, increment) in bounds.iter() {
if accel_mod >= lower && accel_mod <= upper {
accel_mod += increment;
break
}
}
}
} else if dir == Backward {
let bounds = [
(-85, -75, -10),
(-75, -60, -5),
(-60, -41, -8),
(-40, -15, -10),
(-15, 0, -12),
(15, 40, -17),
(40, 60, -19),
(60, 75, -22),
(75, 85, -25)
];
accel_mod = min(accel_mod, 84);
if accel_mod == 0 {
accel_mod = -15;
} else if accel_mod <= 15 && accel_mod > 0 {
accel_mod = 0;
} else {
for &(lower, upper, increment) in bounds.iter() {
if accel_mod >= lower && accel_mod <= upper {
accel_mod += increment;
break
}
}
}
}
let max = 0.04;
if accel >= -max && accel <= max {
accel += 0.08 * (accel_mod as f32);
} else {
accel = accel.signum() * max;
}
(accel, accel_mod) //returns accel and accel mod
}
mod collision {
use cgmath::angle::Rad;
use cgmath::vector::{Vector, Vector2};
use cgmath::matrix::{Matrix, Matrix2};
use gl::types::GLfloat;
use render::Sprite;
use std::f32::consts::PI;
type V = Vector2<GLfloat>;
fn min(a: GLfloat, b: GLfloat) -> GLfloat {
a.min(b)
}
fn max(a: GLfloat, b: GLfloat) -> GLfloat {
a.max(b)
}
fn slope(a: V, b: V) -> GLfloat {
(a.y - b.y) / (a.x - b.x)
}
fn line_intercept((a1, a2): (V, V), (b1, b2): (V, V)) -> f32 {
let (x1, x2, y1, y2, m1, m2) = (a1.x, b1.x, a1.y, b1.y, slope(a1, a2), slope(b1, b2));
((m1*x1) - (m2*x2) - y1 + y2) / (m1 - m2)
}
fn intersect((a1, a2): (V, V), (b1, b2): (V, V)) -> Option<V> {
debug!("Checking the intersection of the two lines, {} to {} and {} to {}", a1, a2, b1, b2);
let x = line_intercept((a1, a2), (b1, b2));
debug!("The lines, were they infinite, intersect at x = {}", x);
let y = slope(a1, a2)*(x - a1.x) + a1.y;
debug!("The corresponding y is {}", y);
if x >= min(a1.x, a2.x) && x <= max(a1.x, a2.x) {
debug!("It's within the first line's x values");
if x >= min(b1.x, b2.x) && x <= max(b1.x, b2.x) {
debug!("It's within the second line's x values");
if y >= min(a1.y, a2.y) && y <= max(a1.y, a2.y)
|
}
}
None
}
#[test]
fn test_intersect() {
let a = Vector2::new(1f32, 1f32);
let b = Vector2::new(-1f32, -1f32);
let c = Vector2::new(-1f32, 1f32);
let d = Vector2::new(1f32, -1f32);
assert_eq!(intersect((a, b), (c, d)), Some(Vector2::new(0f32, 0f32)));
}
/// Determines if two Sprites collide, assuming that they collide iff their
/// (possibly rotated) bounding boxes collide, not using the texture in any
/// way.
pub fn collide(a: &Sprite, b: &Sprite) -> bool {
// make lists of points making up each sprite, transformed with the
// rotation
let mut arot = a.rot;
let mut brot = b.rot;
// make sure their slopes aren't NaN :(
if arot % (PI / 4.0) == 0.0 {
arot += 0.01;
}
if brot % (PI / 4.0) == 0.0 {
brot += 0.01;
}
let amat = Matrix2::from_angle(Rad { s: arot });
let bmat = Matrix2::from_angle(Rad { s: brot });
let pairs = [(0, 1), (1, 2), (2, 3), (3, 0)]; // which indices form lines we care about?
let &Sprite {x, y, width, height, .. } = a;
let apoints = [
amat.mul_v(&Vector2::new(x, y)),
amat.mul_v(&Vector2::new(x + width, y)),
amat.mul_v(&Vector2::new(x + width, y + height)),
amat.mul_v(&Vector2::new(x, y + height))
];
let &Sprite {x, y, width, height, .. } = b;
let bpoints = [
bmat.mul_v(&Vector2::new(x, y)),
bmat.mul_v(&Vector2::new(x + width, y)),
bmat.mul_v(&Vector2::new(x + width, y + height)),
bmat.mul_v(&Vector2::new(x, y + height))
];
for &(a1, a2) in pairs.iter() {
for &(b1, b2) in pairs.iter() {
if intersect((apoints[a1], apoints[a2]), (bpoints[b1], bpoints[b2])) != None {
return true;
}
}
}
false
}
#[test]
fn test_collide() {
use std;
let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
let s2 = Sprite::new(0.5, 0.5, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
assert_eq!(collide(&s1, &s2), true);
unsafe {
// since we're stubbing out the texture
std::cast::forget(s1);
std::cast::forget(s2);
}
let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
let s2 = Sprite::new(1.0, 1.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
assert_eq!(collide(&s1, &s2), true);
unsafe {
// since we're stubbing out the texture
std::cast::forget(s1);
std::cast::forget(s2);
}
let s1 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.0, unsafe { std::mem::uninit() });
let s2 = Sprite::new(0.0, 0.0, 1.0, 1.0, 0.5, unsafe { std::mem::uninit() });
assert_eq!(collide(&s1, &s2), true);
unsafe {
// since we're stubbing out the texture
std::cast::forget(s1);
std::cast::forget(s2);
}
}
}
|
{
debug!("It's within the first line's y values");
if y >= min(b1.y, b2.y) && y <= max(b1.y, b2.y) {
debug!("It's within the second line's y values");
return Some(Vector2::new(x, y));
}
}
|
conditional_block
|
login.component.ts
|
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Store } from "@ngrx/store";
import { loginActions } from '../Store/actions';
@Component({
selector: 'cdp-login',
styleUrls: [ './login.styles.css' ],
templateUrl: "login.component.tmpl.html"
})
export class LoginComponent {
public login$: any;
public form = {
userName: {
value: '',
valid: true,
initial: false
},
userPassword: {
value: '',
valid: true,
initial: false
},
valid: false,
loginIsValid: true
};
constructor(
protected router : Router,
protected store: Store<any>
) {
this.login$ = this.store.select('login');
}
ngOnInit() {
this.login$.subscribe(
({logged, name}) => {
if(logged && name !== 'admin') {
this.router.navigate(['/list'])
} else if (logged && name === 'admin') {
this.router.navigate(['/approve'])
}
},
error => console.log(error),
() => this.login$.unsubscribe()
)
}
submitForm($event: any): void {
const {
userName : {value : user},
userPassword : {value : password}
} = this.form;
$event.preventDefault();
this.store.dispatch(new loginActions.fetchLoginAction({user, password}));
}
validateForm(): void {
this.form.valid = this.form.userName.initial &&
this.form.userPassword.initial &&
this.form.userName.valid &&
|
if (!this.form[inputType].initial) {
this.form[inputType].initial = true;
}
this.form[inputType].value ? this.form[inputType].valid = true : this.form[inputType].valid = false;
this.validateForm();
}
}
|
this.form.userPassword.valid;
}
validateInput(inputType: string): void {
|
random_line_split
|
login.component.ts
|
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Store } from "@ngrx/store";
import { loginActions } from '../Store/actions';
@Component({
selector: 'cdp-login',
styleUrls: [ './login.styles.css' ],
templateUrl: "login.component.tmpl.html"
})
export class LoginComponent {
public login$: any;
public form = {
userName: {
value: '',
valid: true,
initial: false
},
userPassword: {
value: '',
valid: true,
initial: false
},
valid: false,
loginIsValid: true
};
constructor(
protected router : Router,
protected store: Store<any>
) {
this.login$ = this.store.select('login');
}
ngOnInit() {
this.login$.subscribe(
({logged, name}) => {
if(logged && name !== 'admin') {
this.router.navigate(['/list'])
} else if (logged && name === 'admin') {
this.router.navigate(['/approve'])
}
},
error => console.log(error),
() => this.login$.unsubscribe()
)
}
|
($event: any): void {
const {
userName : {value : user},
userPassword : {value : password}
} = this.form;
$event.preventDefault();
this.store.dispatch(new loginActions.fetchLoginAction({user, password}));
}
validateForm(): void {
this.form.valid = this.form.userName.initial &&
this.form.userPassword.initial &&
this.form.userName.valid &&
this.form.userPassword.valid;
}
validateInput(inputType: string): void {
if (!this.form[inputType].initial) {
this.form[inputType].initial = true;
}
this.form[inputType].value ? this.form[inputType].valid = true : this.form[inputType].valid = false;
this.validateForm();
}
}
|
submitForm
|
identifier_name
|
login.component.ts
|
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Store } from "@ngrx/store";
import { loginActions } from '../Store/actions';
@Component({
selector: 'cdp-login',
styleUrls: [ './login.styles.css' ],
templateUrl: "login.component.tmpl.html"
})
export class LoginComponent {
public login$: any;
public form = {
userName: {
value: '',
valid: true,
initial: false
},
userPassword: {
value: '',
valid: true,
initial: false
},
valid: false,
loginIsValid: true
};
constructor(
protected router : Router,
protected store: Store<any>
) {
this.login$ = this.store.select('login');
}
ngOnInit() {
this.login$.subscribe(
({logged, name}) => {
if(logged && name !== 'admin') {
this.router.navigate(['/list'])
} else if (logged && name === 'admin') {
this.router.navigate(['/approve'])
}
},
error => console.log(error),
() => this.login$.unsubscribe()
)
}
submitForm($event: any): void {
const {
userName : {value : user},
userPassword : {value : password}
} = this.form;
$event.preventDefault();
this.store.dispatch(new loginActions.fetchLoginAction({user, password}));
}
validateForm(): void {
this.form.valid = this.form.userName.initial &&
this.form.userPassword.initial &&
this.form.userName.valid &&
this.form.userPassword.valid;
}
validateInput(inputType: string): void
|
}
|
{
if (!this.form[inputType].initial) {
this.form[inputType].initial = true;
}
this.form[inputType].value ? this.form[inputType].valid = true : this.form[inputType].valid = false;
this.validateForm();
}
|
identifier_body
|
login.component.ts
|
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Store } from "@ngrx/store";
import { loginActions } from '../Store/actions';
@Component({
selector: 'cdp-login',
styleUrls: [ './login.styles.css' ],
templateUrl: "login.component.tmpl.html"
})
export class LoginComponent {
public login$: any;
public form = {
userName: {
value: '',
valid: true,
initial: false
},
userPassword: {
value: '',
valid: true,
initial: false
},
valid: false,
loginIsValid: true
};
constructor(
protected router : Router,
protected store: Store<any>
) {
this.login$ = this.store.select('login');
}
ngOnInit() {
this.login$.subscribe(
({logged, name}) => {
if(logged && name !== 'admin') {
this.router.navigate(['/list'])
} else if (logged && name === 'admin') {
this.router.navigate(['/approve'])
}
},
error => console.log(error),
() => this.login$.unsubscribe()
)
}
submitForm($event: any): void {
const {
userName : {value : user},
userPassword : {value : password}
} = this.form;
$event.preventDefault();
this.store.dispatch(new loginActions.fetchLoginAction({user, password}));
}
validateForm(): void {
this.form.valid = this.form.userName.initial &&
this.form.userPassword.initial &&
this.form.userName.valid &&
this.form.userPassword.valid;
}
validateInput(inputType: string): void {
if (!this.form[inputType].initial)
|
this.form[inputType].value ? this.form[inputType].valid = true : this.form[inputType].valid = false;
this.validateForm();
}
}
|
{
this.form[inputType].initial = true;
}
|
conditional_block
|
cmp.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
The `Ord` and `Eq` comparison traits
This module contains the definition of both `Ord` and `Eq` which define
the common interfaces for doing comparison. Both are language items
that the compiler uses to implement the comparison operators. Rust code
may implement `Ord` to overload the `<`, `<=`, `>`, and `>=` operators,
and `Eq` to overload the `==` and `!=` operators.
*/
#[allow(missing_doc)];
/**
* Trait for values that can be compared for equality and inequality.
*
* This trait allows partial equality, where types can be unordered instead of strictly equal or
* unequal. For example, with the built-in floating-point types `a == b` and `a != b` will both
* evaluate to false if either `a` or `b` is NaN (cf. IEEE 754-2008 section 5.11).
*
* Eq only requires the `eq` method to be implemented; `ne` is its negation by default.
*
* Eventually, this will be implemented by default for types that implement `TotalEq`.
*/
#[lang="eq"]
pub trait Eq {
fn eq(&self, other: &Self) -> bool;
#[inline]
fn ne(&self, other: &Self) -> bool { !self.eq(other) }
}
/// Trait for equality comparisons where `a == b` and `a != b` are strict inverses.
pub trait TotalEq {
fn equals(&self, other: &Self) -> bool;
}
macro_rules! totaleq_impl(
($t:ty) => {
impl TotalEq for $t {
#[inline]
fn equals(&self, other: &$t) -> bool { *self == *other }
}
}
)
totaleq_impl!(bool)
totaleq_impl!(u8)
totaleq_impl!(u16)
totaleq_impl!(u32)
totaleq_impl!(u64)
totaleq_impl!(i8)
totaleq_impl!(i16)
totaleq_impl!(i32)
totaleq_impl!(i64)
totaleq_impl!(int)
totaleq_impl!(uint)
totaleq_impl!(char)
/// Trait for testing approximate equality
pub trait ApproxEq<Eps> {
fn approx_epsilon() -> Eps;
fn approx_eq(&self, other: &Self) -> bool;
fn approx_eq_eps(&self, other: &Self, approx_epsilon: &Eps) -> bool;
}
#[deriving(Clone, Eq)]
pub enum Ordering { Less = -1, Equal = 0, Greater = 1 }
/// Trait for types that form a total order
pub trait TotalOrd: TotalEq {
fn cmp(&self, other: &Self) -> Ordering;
}
impl TotalEq for Ordering {
#[inline]
fn equals(&self, other: &Ordering) -> bool {
*self == *other
}
}
impl TotalOrd for Ordering {
#[inline]
fn cmp(&self, other: &Ordering) -> Ordering {
(*self as int).cmp(&(*other as int))
}
|
impl Ord for Ordering {
#[inline]
fn lt(&self, other: &Ordering) -> bool { (*self as int) < (*other as int) }
}
macro_rules! totalord_impl(
($t:ty) => {
impl TotalOrd for $t {
#[inline]
fn cmp(&self, other: &$t) -> Ordering {
if *self < *other { Less }
else if *self > *other { Greater }
else { Equal }
}
}
}
)
totalord_impl!(u8)
totalord_impl!(u16)
totalord_impl!(u32)
totalord_impl!(u64)
totalord_impl!(i8)
totalord_impl!(i16)
totalord_impl!(i32)
totalord_impl!(i64)
totalord_impl!(int)
totalord_impl!(uint)
totalord_impl!(char)
/// Compares (a1, b1) against (a2, b2), where the a values are more significant.
pub fn cmp2<A:TotalOrd,B:TotalOrd>(
a1: &A, b1: &B,
a2: &A, b2: &B) -> Ordering
{
match a1.cmp(a2) {
Less => Less,
Greater => Greater,
Equal => b1.cmp(b2)
}
}
/**
Return `o1` if it is not `Equal`, otherwise `o2`. Simulates the
lexical ordering on a type `(int, int)`.
*/
#[inline]
pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering {
match o1 {
Equal => o2,
_ => o1
}
}
/**
* Trait for values that can be compared for a sort-order.
*
* Ord only requires implementation of the `lt` method,
* with the others generated from default implementations.
*
* However it remains possible to implement the others separately,
* for compatibility with floating-point NaN semantics
* (cf. IEEE 754-2008 section 5.11).
*/
#[lang="ord"]
pub trait Ord {
fn lt(&self, other: &Self) -> bool;
#[inline]
fn le(&self, other: &Self) -> bool { !other.lt(self) }
#[inline]
fn gt(&self, other: &Self) -> bool { other.lt(self) }
#[inline]
fn ge(&self, other: &Self) -> bool { !self.lt(other) }
}
/// The equivalence relation. Two values may be equivalent even if they are
/// of different types. The most common use case for this relation is
/// container types; e.g. it is often desirable to be able to use `&str`
/// values to look up entries in a container with `~str` keys.
pub trait Equiv<T> {
fn equiv(&self, other: &T) -> bool;
}
#[inline]
pub fn min<T:Ord>(v1: T, v2: T) -> T {
if v1 < v2 { v1 } else { v2 }
}
#[inline]
pub fn max<T:Ord>(v1: T, v2: T) -> T {
if v1 > v2 { v1 } else { v2 }
}
#[cfg(test)]
mod test {
use super::lexical_ordering;
#[test]
fn test_int_totalord() {
assert_eq!(5.cmp(&10), Less);
assert_eq!(10.cmp(&5), Greater);
assert_eq!(5.cmp(&5), Equal);
assert_eq!((-5).cmp(&12), Less);
assert_eq!(12.cmp(-5), Greater);
}
#[test]
fn test_cmp2() {
assert_eq!(cmp2(1, 2, 3, 4), Less);
assert_eq!(cmp2(3, 2, 3, 4), Less);
assert_eq!(cmp2(5, 2, 3, 4), Greater);
assert_eq!(cmp2(5, 5, 5, 4), Greater);
}
#[test]
fn test_int_totaleq() {
assert!(5.equals(&5));
assert!(!2.equals(&17));
}
#[test]
fn test_ordering_order() {
assert!(Less < Equal);
assert_eq!(Greater.cmp(&Less), Greater);
}
#[test]
fn test_lexical_ordering() {
fn t(o1: Ordering, o2: Ordering, e: Ordering) {
assert_eq!(lexical_ordering(o1, o2), e);
}
let xs = [Less, Equal, Greater];
for &o in xs.iter() {
t(Less, o, Less);
t(Equal, o, o);
t(Greater, o, Greater);
}
}
}
|
}
|
random_line_split
|
cmp.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
The `Ord` and `Eq` comparison traits
This module contains the definition of both `Ord` and `Eq` which define
the common interfaces for doing comparison. Both are language items
that the compiler uses to implement the comparison operators. Rust code
may implement `Ord` to overload the `<`, `<=`, `>`, and `>=` operators,
and `Eq` to overload the `==` and `!=` operators.
*/
#[allow(missing_doc)];
/**
* Trait for values that can be compared for equality and inequality.
*
* This trait allows partial equality, where types can be unordered instead of strictly equal or
* unequal. For example, with the built-in floating-point types `a == b` and `a != b` will both
* evaluate to false if either `a` or `b` is NaN (cf. IEEE 754-2008 section 5.11).
*
* Eq only requires the `eq` method to be implemented; `ne` is its negation by default.
*
* Eventually, this will be implemented by default for types that implement `TotalEq`.
*/
#[lang="eq"]
pub trait Eq {
fn eq(&self, other: &Self) -> bool;
#[inline]
fn ne(&self, other: &Self) -> bool
|
}
/// Trait for equality comparisons where `a == b` and `a != b` are strict inverses.
pub trait TotalEq {
fn equals(&self, other: &Self) -> bool;
}
macro_rules! totaleq_impl(
($t:ty) => {
impl TotalEq for $t {
#[inline]
fn equals(&self, other: &$t) -> bool { *self == *other }
}
}
)
totaleq_impl!(bool)
totaleq_impl!(u8)
totaleq_impl!(u16)
totaleq_impl!(u32)
totaleq_impl!(u64)
totaleq_impl!(i8)
totaleq_impl!(i16)
totaleq_impl!(i32)
totaleq_impl!(i64)
totaleq_impl!(int)
totaleq_impl!(uint)
totaleq_impl!(char)
/// Trait for testing approximate equality
pub trait ApproxEq<Eps> {
fn approx_epsilon() -> Eps;
fn approx_eq(&self, other: &Self) -> bool;
fn approx_eq_eps(&self, other: &Self, approx_epsilon: &Eps) -> bool;
}
#[deriving(Clone, Eq)]
pub enum Ordering { Less = -1, Equal = 0, Greater = 1 }
/// Trait for types that form a total order
pub trait TotalOrd: TotalEq {
fn cmp(&self, other: &Self) -> Ordering;
}
impl TotalEq for Ordering {
#[inline]
fn equals(&self, other: &Ordering) -> bool {
*self == *other
}
}
impl TotalOrd for Ordering {
#[inline]
fn cmp(&self, other: &Ordering) -> Ordering {
(*self as int).cmp(&(*other as int))
}
}
impl Ord for Ordering {
#[inline]
fn lt(&self, other: &Ordering) -> bool { (*self as int) < (*other as int) }
}
macro_rules! totalord_impl(
($t:ty) => {
impl TotalOrd for $t {
#[inline]
fn cmp(&self, other: &$t) -> Ordering {
if *self < *other { Less }
else if *self > *other { Greater }
else { Equal }
}
}
}
)
totalord_impl!(u8)
totalord_impl!(u16)
totalord_impl!(u32)
totalord_impl!(u64)
totalord_impl!(i8)
totalord_impl!(i16)
totalord_impl!(i32)
totalord_impl!(i64)
totalord_impl!(int)
totalord_impl!(uint)
totalord_impl!(char)
/// Compares (a1, b1) against (a2, b2), where the a values are more significant.
pub fn cmp2<A:TotalOrd,B:TotalOrd>(
a1: &A, b1: &B,
a2: &A, b2: &B) -> Ordering
{
match a1.cmp(a2) {
Less => Less,
Greater => Greater,
Equal => b1.cmp(b2)
}
}
/**
Return `o1` if it is not `Equal`, otherwise `o2`. Simulates the
lexical ordering on a type `(int, int)`.
*/
#[inline]
pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering {
match o1 {
Equal => o2,
_ => o1
}
}
/**
* Trait for values that can be compared for a sort-order.
*
* Ord only requires implementation of the `lt` method,
* with the others generated from default implementations.
*
* However it remains possible to implement the others separately,
* for compatibility with floating-point NaN semantics
* (cf. IEEE 754-2008 section 5.11).
*/
#[lang="ord"]
pub trait Ord {
fn lt(&self, other: &Self) -> bool;
#[inline]
fn le(&self, other: &Self) -> bool { !other.lt(self) }
#[inline]
fn gt(&self, other: &Self) -> bool { other.lt(self) }
#[inline]
fn ge(&self, other: &Self) -> bool { !self.lt(other) }
}
/// The equivalence relation. Two values may be equivalent even if they are
/// of different types. The most common use case for this relation is
/// container types; e.g. it is often desirable to be able to use `&str`
/// values to look up entries in a container with `~str` keys.
pub trait Equiv<T> {
fn equiv(&self, other: &T) -> bool;
}
#[inline]
pub fn min<T:Ord>(v1: T, v2: T) -> T {
if v1 < v2 { v1 } else { v2 }
}
#[inline]
pub fn max<T:Ord>(v1: T, v2: T) -> T {
if v1 > v2 { v1 } else { v2 }
}
#[cfg(test)]
mod test {
use super::lexical_ordering;
#[test]
fn test_int_totalord() {
assert_eq!(5.cmp(&10), Less);
assert_eq!(10.cmp(&5), Greater);
assert_eq!(5.cmp(&5), Equal);
assert_eq!((-5).cmp(&12), Less);
assert_eq!(12.cmp(-5), Greater);
}
#[test]
fn test_cmp2() {
assert_eq!(cmp2(1, 2, 3, 4), Less);
assert_eq!(cmp2(3, 2, 3, 4), Less);
assert_eq!(cmp2(5, 2, 3, 4), Greater);
assert_eq!(cmp2(5, 5, 5, 4), Greater);
}
#[test]
fn test_int_totaleq() {
assert!(5.equals(&5));
assert!(!2.equals(&17));
}
#[test]
fn test_ordering_order() {
assert!(Less < Equal);
assert_eq!(Greater.cmp(&Less), Greater);
}
#[test]
fn test_lexical_ordering() {
fn t(o1: Ordering, o2: Ordering, e: Ordering) {
assert_eq!(lexical_ordering(o1, o2), e);
}
let xs = [Less, Equal, Greater];
for &o in xs.iter() {
t(Less, o, Less);
t(Equal, o, o);
t(Greater, o, Greater);
}
}
}
|
{ !self.eq(other) }
|
identifier_body
|
cmp.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
The `Ord` and `Eq` comparison traits
This module contains the definition of both `Ord` and `Eq` which define
the common interfaces for doing comparison. Both are language items
that the compiler uses to implement the comparison operators. Rust code
may implement `Ord` to overload the `<`, `<=`, `>`, and `>=` operators,
and `Eq` to overload the `==` and `!=` operators.
*/
#[allow(missing_doc)];
/**
* Trait for values that can be compared for equality and inequality.
*
* This trait allows partial equality, where types can be unordered instead of strictly equal or
* unequal. For example, with the built-in floating-point types `a == b` and `a != b` will both
* evaluate to false if either `a` or `b` is NaN (cf. IEEE 754-2008 section 5.11).
*
* Eq only requires the `eq` method to be implemented; `ne` is its negation by default.
*
* Eventually, this will be implemented by default for types that implement `TotalEq`.
*/
#[lang="eq"]
pub trait Eq {
fn eq(&self, other: &Self) -> bool;
#[inline]
fn
|
(&self, other: &Self) -> bool { !self.eq(other) }
}
/// Trait for equality comparisons where `a == b` and `a != b` are strict inverses.
pub trait TotalEq {
fn equals(&self, other: &Self) -> bool;
}
macro_rules! totaleq_impl(
($t:ty) => {
impl TotalEq for $t {
#[inline]
fn equals(&self, other: &$t) -> bool { *self == *other }
}
}
)
totaleq_impl!(bool)
totaleq_impl!(u8)
totaleq_impl!(u16)
totaleq_impl!(u32)
totaleq_impl!(u64)
totaleq_impl!(i8)
totaleq_impl!(i16)
totaleq_impl!(i32)
totaleq_impl!(i64)
totaleq_impl!(int)
totaleq_impl!(uint)
totaleq_impl!(char)
/// Trait for testing approximate equality
pub trait ApproxEq<Eps> {
fn approx_epsilon() -> Eps;
fn approx_eq(&self, other: &Self) -> bool;
fn approx_eq_eps(&self, other: &Self, approx_epsilon: &Eps) -> bool;
}
#[deriving(Clone, Eq)]
pub enum Ordering { Less = -1, Equal = 0, Greater = 1 }
/// Trait for types that form a total order
pub trait TotalOrd: TotalEq {
fn cmp(&self, other: &Self) -> Ordering;
}
impl TotalEq for Ordering {
#[inline]
fn equals(&self, other: &Ordering) -> bool {
*self == *other
}
}
impl TotalOrd for Ordering {
#[inline]
fn cmp(&self, other: &Ordering) -> Ordering {
(*self as int).cmp(&(*other as int))
}
}
impl Ord for Ordering {
#[inline]
fn lt(&self, other: &Ordering) -> bool { (*self as int) < (*other as int) }
}
macro_rules! totalord_impl(
($t:ty) => {
impl TotalOrd for $t {
#[inline]
fn cmp(&self, other: &$t) -> Ordering {
if *self < *other { Less }
else if *self > *other { Greater }
else { Equal }
}
}
}
)
totalord_impl!(u8)
totalord_impl!(u16)
totalord_impl!(u32)
totalord_impl!(u64)
totalord_impl!(i8)
totalord_impl!(i16)
totalord_impl!(i32)
totalord_impl!(i64)
totalord_impl!(int)
totalord_impl!(uint)
totalord_impl!(char)
/// Compares (a1, b1) against (a2, b2), where the a values are more significant.
pub fn cmp2<A:TotalOrd,B:TotalOrd>(
a1: &A, b1: &B,
a2: &A, b2: &B) -> Ordering
{
match a1.cmp(a2) {
Less => Less,
Greater => Greater,
Equal => b1.cmp(b2)
}
}
/**
Return `o1` if it is not `Equal`, otherwise `o2`. Simulates the
lexical ordering on a type `(int, int)`.
*/
#[inline]
pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering {
match o1 {
Equal => o2,
_ => o1
}
}
/**
* Trait for values that can be compared for a sort-order.
*
* Ord only requires implementation of the `lt` method,
* with the others generated from default implementations.
*
* However it remains possible to implement the others separately,
* for compatibility with floating-point NaN semantics
* (cf. IEEE 754-2008 section 5.11).
*/
#[lang="ord"]
pub trait Ord {
fn lt(&self, other: &Self) -> bool;
#[inline]
fn le(&self, other: &Self) -> bool { !other.lt(self) }
#[inline]
fn gt(&self, other: &Self) -> bool { other.lt(self) }
#[inline]
fn ge(&self, other: &Self) -> bool { !self.lt(other) }
}
/// The equivalence relation. Two values may be equivalent even if they are
/// of different types. The most common use case for this relation is
/// container types; e.g. it is often desirable to be able to use `&str`
/// values to look up entries in a container with `~str` keys.
pub trait Equiv<T> {
fn equiv(&self, other: &T) -> bool;
}
#[inline]
pub fn min<T:Ord>(v1: T, v2: T) -> T {
if v1 < v2 { v1 } else { v2 }
}
#[inline]
pub fn max<T:Ord>(v1: T, v2: T) -> T {
if v1 > v2 { v1 } else { v2 }
}
#[cfg(test)]
mod test {
use super::lexical_ordering;
#[test]
fn test_int_totalord() {
assert_eq!(5.cmp(&10), Less);
assert_eq!(10.cmp(&5), Greater);
assert_eq!(5.cmp(&5), Equal);
assert_eq!((-5).cmp(&12), Less);
assert_eq!(12.cmp(-5), Greater);
}
#[test]
fn test_cmp2() {
assert_eq!(cmp2(1, 2, 3, 4), Less);
assert_eq!(cmp2(3, 2, 3, 4), Less);
assert_eq!(cmp2(5, 2, 3, 4), Greater);
assert_eq!(cmp2(5, 5, 5, 4), Greater);
}
#[test]
fn test_int_totaleq() {
assert!(5.equals(&5));
assert!(!2.equals(&17));
}
#[test]
fn test_ordering_order() {
assert!(Less < Equal);
assert_eq!(Greater.cmp(&Less), Greater);
}
#[test]
fn test_lexical_ordering() {
fn t(o1: Ordering, o2: Ordering, e: Ordering) {
assert_eq!(lexical_ordering(o1, o2), e);
}
let xs = [Less, Equal, Greater];
for &o in xs.iter() {
t(Less, o, Less);
t(Equal, o, o);
t(Greater, o, Greater);
}
}
}
|
ne
|
identifier_name
|
static-mut-not-pat.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
// except according to those terms.
// Constants (static variables) can be used to match in patterns, but mutable
// statics cannot. This ensures that there's some form of error if this is
// attempted.
static mut a: int = 3;
fn main() {
// If they can't be matched against, then it's possible to capture the same
// name as a variable, hence this should be an unreachable pattern situation
// instead of spitting out a custom error about some identifier collisions
// (we should allow shadowing)
match 4i {
a => {} //~ ERROR mutable static variables cannot be referenced in a pattern
_ => {}
}
}
struct NewBool(bool);
enum Direction {
North,
East,
South,
West
}
static NEW_FALSE: NewBool = NewBool(false);
struct Foo {
bar: Option<Direction>,
baz: NewBool
}
static mut STATIC_MUT_FOO: Foo = Foo { bar: Some(West), baz: NEW_FALSE };
fn mutable_statics() {
match (Foo { bar: Some(North), baz: NewBool(true) }) {
Foo { bar: None, baz: NewBool(true) } => (),
STATIC_MUT_FOO => (),
//~^ ERROR mutable static variables cannot be referenced in a pattern
Foo { bar: Some(South), .. } => (),
Foo { bar: Some(EAST), .. } => (),
Foo { bar: Some(North), baz: NewBool(true) } => (),
Foo { bar: Some(EAST), baz: NewBool(false) } => ()
}
}
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
|
random_line_split
|
static-mut-not-pat.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Constants (static variables) can be used to match in patterns, but mutable
// statics cannot. This ensures that there's some form of error if this is
// attempted.
static mut a: int = 3;
fn
|
() {
// If they can't be matched against, then it's possible to capture the same
// name as a variable, hence this should be an unreachable pattern situation
// instead of spitting out a custom error about some identifier collisions
// (we should allow shadowing)
match 4i {
a => {} //~ ERROR mutable static variables cannot be referenced in a pattern
_ => {}
}
}
struct NewBool(bool);
enum Direction {
North,
East,
South,
West
}
static NEW_FALSE: NewBool = NewBool(false);
struct Foo {
bar: Option<Direction>,
baz: NewBool
}
static mut STATIC_MUT_FOO: Foo = Foo { bar: Some(West), baz: NEW_FALSE };
fn mutable_statics() {
match (Foo { bar: Some(North), baz: NewBool(true) }) {
Foo { bar: None, baz: NewBool(true) } => (),
STATIC_MUT_FOO => (),
//~^ ERROR mutable static variables cannot be referenced in a pattern
Foo { bar: Some(South), .. } => (),
Foo { bar: Some(EAST), .. } => (),
Foo { bar: Some(North), baz: NewBool(true) } => (),
Foo { bar: Some(EAST), baz: NewBool(false) } => ()
}
}
|
main
|
identifier_name
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate gfx_traits;
extern crate ipc_channel;
#[macro_use]
extern crate log;
extern crate malloc_size_of;
#[macro_use]
extern crate malloc_size_of_derive;
extern crate msg;
extern crate profile_traits;
extern crate script_traits;
extern crate servo_config;
extern crate servo_url;
extern crate time;
use gfx_traits::{Epoch, DisplayList};
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use profile_traits::time::{ProfilerChan, ProfilerCategory, send_profile_data};
use profile_traits::time::TimerMetadata;
use script_traits::{ConstellationControlMsg, LayoutMsg, ProgressiveWebMetricType};
use servo_config::opts;
use servo_url::ServoUrl;
use std::cell::{Cell, RefCell};
use std::cmp::Ordering;
use std::collections::HashMap;
use time::precise_time_ns;
pub trait ProfilerMetadataFactory {
fn new_metadata(&self) -> Option<TimerMetadata>;
}
pub trait ProgressiveWebMetric {
fn get_navigation_start(&self) -> Option<u64>;
fn set_navigation_start(&mut self, time: u64);
fn get_time_profiler_chan(&self) -> &ProfilerChan;
fn send_queued_constellation_msg(&self, name: ProgressiveWebMetricType, time: u64);
fn get_url(&self) -> &ServoUrl;
}
/// TODO make this configurable
/// maximum task time is 50ms (in ns)
pub const MAX_TASK_NS: u64 = 50000000;
/// 10 second window (in ns)
const INTERACTIVE_WINDOW_SECONDS_IN_NS: u64 = 10000000000;
pub trait ToMs<T> {
fn to_ms(&self) -> T;
}
impl ToMs<f64> for u64 {
fn to_ms(&self) -> f64 {
*self as f64 / 1000000.
}
}
fn set_metric<U: ProgressiveWebMetric>(
pwm: &U,
metadata: Option<TimerMetadata>,
metric_type: ProgressiveWebMetricType,
category: ProfilerCategory,
attr: &Cell<Option<u64>>,
metric_time: Option<u64>,
url: &ServoUrl,
) {
let navigation_start = match pwm.get_navigation_start() {
Some(time) => time,
None => {
warn!("Trying to set metric before navigation start");
return;
},
};
let now = match metric_time {
Some(time) => time,
None => precise_time_ns(),
};
let time = now - navigation_start;
attr.set(Some(time));
// Queue performance observer notification.
pwm.send_queued_constellation_msg(metric_type, time);
// Send the metric to the time profiler.
send_profile_data(
category,
metadata,
&pwm.get_time_profiler_chan(),
time,
time,
0,
0,
);
// Print the metric to console if the print-pwm option was given.
if opts::get().print_pwm {
println!(
"Navigation start: {}",
pwm.get_navigation_start().unwrap().to_ms()
);
println!("{:?} {:?} {:?}", url, metric_type, time.to_ms());
}
}
// spec: https://github.com/WICG/time-to-interactive
// https://github.com/GoogleChrome/lighthouse/issues/27
// we can look at three different metrics here:
// navigation start -> visually ready (dom content loaded)
// navigation start -> thread ready (main thread available)
// visually ready -> thread ready
#[derive(MallocSizeOf)]
pub struct InteractiveMetrics {
/// when we navigated to the page
navigation_start: Option<u64>,
/// indicates if the page is visually ready
dom_content_loaded: Cell<Option<u64>>,
/// main thread is available -- there's been a 10s window with no tasks longer than 50ms
main_thread_available: Cell<Option<u64>>,
// max(main_thread_available, dom_content_loaded)
time_to_interactive: Cell<Option<u64>>,
#[ignore_malloc_size_of = "can't measure channels"]
time_profiler_chan: ProfilerChan,
url: ServoUrl,
}
#[derive(Clone, Copy, Debug, MallocSizeOf)]
pub struct InteractiveWindow {
start: u64,
}
impl InteractiveWindow {
pub fn new() -> InteractiveWindow {
InteractiveWindow {
start: precise_time_ns(),
}
}
// We need to either start or restart the 10s window
// start: we've added a new document
// restart: there was a task > 50ms
// not all documents are interactive
pub fn start_window(&mut self) {
self.start = precise_time_ns();
}
/// check if 10s has elapsed since start
pub fn needs_check(&self) -> bool {
precise_time_ns() - self.start >= INTERACTIVE_WINDOW_SECONDS_IN_NS
}
pub fn get_start(&self) -> u64 {
self.start
}
}
#[derive(Debug)]
pub enum InteractiveFlag {
DOMContentLoaded,
TimeToInteractive(u64),
}
impl InteractiveMetrics {
pub fn new(time_profiler_chan: ProfilerChan, url: ServoUrl) -> InteractiveMetrics {
InteractiveMetrics {
navigation_start: None,
dom_content_loaded: Cell::new(None),
main_thread_available: Cell::new(None),
time_to_interactive: Cell::new(None),
time_profiler_chan: time_profiler_chan,
url,
}
}
pub fn set_dom_content_loaded(&self) {
if self.dom_content_loaded.get().is_none() {
self.dom_content_loaded.set(Some(precise_time_ns()));
}
}
pub fn set_main_thread_available(&self, time: u64) {
if self.main_thread_available.get().is_none() {
self.main_thread_available.set(Some(time));
}
}
pub fn get_dom_content_loaded(&self) -> Option<u64> {
self.dom_content_loaded.get()
}
pub fn get_main_thread_available(&self) -> Option<u64> {
self.main_thread_available.get()
}
// can set either dlc or tti first, but both must be set to actually calc metric
// when the second is set, set_tti is called with appropriate time
pub fn maybe_set_tti<T>(&self, profiler_metadata_factory: &T, metric: InteractiveFlag)
where
T: ProfilerMetadataFactory,
{
if self.get_tti().is_some() {
return;
}
match metric {
InteractiveFlag::DOMContentLoaded => self.set_dom_content_loaded(),
InteractiveFlag::TimeToInteractive(time) => self.set_main_thread_available(time),
}
let dcl = self.dom_content_loaded.get();
let mta = self.main_thread_available.get();
let (dcl, mta) = match (dcl, mta) {
(Some(dcl), Some(mta)) => (dcl, mta),
_ => return,
};
let metric_time = match dcl.partial_cmp(&mta) {
Some(Ordering::Less) => mta,
Some(_) => dcl,
None => panic!("no ordering possible. something bad happened"),
};
set_metric(
self,
profiler_metadata_factory.new_metadata(),
ProgressiveWebMetricType::TimeToInteractive,
ProfilerCategory::TimeToInteractive,
&self.time_to_interactive,
Some(metric_time),
&self.url,
);
}
pub fn
|
(&self) -> Option<u64> {
self.time_to_interactive.get()
}
pub fn needs_tti(&self) -> bool {
self.get_tti().is_none()
}
}
impl ProgressiveWebMetric for InteractiveMetrics {
fn get_navigation_start(&self) -> Option<u64> {
self.navigation_start
}
fn set_navigation_start(&mut self, time: u64) {
self.navigation_start = Some(time);
}
fn send_queued_constellation_msg(&self, _name: ProgressiveWebMetricType, _time: u64) {}
fn get_time_profiler_chan(&self) -> &ProfilerChan {
&self.time_profiler_chan
}
fn get_url(&self) -> &ServoUrl {
&self.url
}
}
// https://w3c.github.io/paint-timing/
pub struct PaintTimeMetrics {
pending_metrics: RefCell<HashMap<Epoch, (Option<TimerMetadata>, bool)>>,
navigation_start: Option<u64>,
first_paint: Cell<Option<u64>>,
first_contentful_paint: Cell<Option<u64>>,
pipeline_id: PipelineId,
time_profiler_chan: ProfilerChan,
constellation_chan: IpcSender<LayoutMsg>,
script_chan: IpcSender<ConstellationControlMsg>,
url: ServoUrl,
}
impl PaintTimeMetrics {
pub fn new(
pipeline_id: PipelineId,
time_profiler_chan: ProfilerChan,
constellation_chan: IpcSender<LayoutMsg>,
script_chan: IpcSender<ConstellationControlMsg>,
url: ServoUrl,
) -> PaintTimeMetrics {
PaintTimeMetrics {
pending_metrics: RefCell::new(HashMap::new()),
navigation_start: None,
first_paint: Cell::new(None),
first_contentful_paint: Cell::new(None),
pipeline_id,
time_profiler_chan,
constellation_chan,
script_chan,
url,
}
}
pub fn maybe_set_first_paint<T>(&self, profiler_metadata_factory: &T)
where
T: ProfilerMetadataFactory,
{
if self.first_paint.get().is_some() {
return;
}
set_metric(
self,
profiler_metadata_factory.new_metadata(),
ProgressiveWebMetricType::FirstPaint,
ProfilerCategory::TimeToFirstPaint,
&self.first_paint,
None,
&self.url,
);
}
pub fn maybe_observe_paint_time<T>(
&self,
profiler_metadata_factory: &T,
epoch: Epoch,
display_list: &DisplayList,
) where
T: ProfilerMetadataFactory,
{
if self.first_paint.get().is_some() && self.first_contentful_paint.get().is_some() {
// If we already set all paint metrics, we just bail out.
return;
}
self.pending_metrics.borrow_mut().insert(
epoch,
(
profiler_metadata_factory.new_metadata(),
display_list.is_contentful(),
),
);
// Send the pending metric information to the compositor thread.
// The compositor will record the current time after painting the
// frame with the given ID and will send the metric back to us.
let msg = LayoutMsg::PendingPaintMetric(self.pipeline_id, epoch);
if let Err(e) = self.constellation_chan.send(msg) {
warn!("Failed to send PendingPaintMetric {:?}", e);
}
}
pub fn maybe_set_metric(&self, epoch: Epoch, paint_time: u64) {
if self.first_paint.get().is_some() && self.first_contentful_paint.get().is_some() ||
self.navigation_start.is_none()
{
// If we already set all paint metrics or we have not set navigation start yet,
// we just bail out.
return;
}
if let Some(pending_metric) = self.pending_metrics.borrow_mut().remove(&epoch) {
let profiler_metadata = pending_metric.0;
set_metric(
self,
profiler_metadata.clone(),
ProgressiveWebMetricType::FirstPaint,
ProfilerCategory::TimeToFirstPaint,
&self.first_paint,
Some(paint_time),
&self.url,
);
if pending_metric.1 {
set_metric(
self,
profiler_metadata,
ProgressiveWebMetricType::FirstContentfulPaint,
ProfilerCategory::TimeToFirstContentfulPaint,
&self.first_contentful_paint,
Some(paint_time),
&self.url,
);
}
}
}
pub fn get_first_paint(&self) -> Option<u64> {
self.first_paint.get()
}
pub fn get_first_contentful_paint(&self) -> Option<u64> {
self.first_contentful_paint.get()
}
}
impl ProgressiveWebMetric for PaintTimeMetrics {
fn get_navigation_start(&self) -> Option<u64> {
self.navigation_start
}
fn set_navigation_start(&mut self, time: u64) {
self.navigation_start = Some(time);
}
fn send_queued_constellation_msg(&self, name: ProgressiveWebMetricType, time: u64) {
let msg = ConstellationControlMsg::PaintMetric(self.pipeline_id, name, time);
if let Err(e) = self.script_chan.send(msg) {
warn!("Sending metric to script thread failed ({}).", e);
}
}
fn get_time_profiler_chan(&self) -> &ProfilerChan {
&self.time_profiler_chan
}
fn get_url(&self) -> &ServoUrl {
&self.url
}
}
|
get_tti
|
identifier_name
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate gfx_traits;
extern crate ipc_channel;
#[macro_use]
extern crate log;
extern crate malloc_size_of;
#[macro_use]
extern crate malloc_size_of_derive;
extern crate msg;
extern crate profile_traits;
extern crate script_traits;
extern crate servo_config;
extern crate servo_url;
extern crate time;
use gfx_traits::{Epoch, DisplayList};
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use profile_traits::time::{ProfilerChan, ProfilerCategory, send_profile_data};
use profile_traits::time::TimerMetadata;
use script_traits::{ConstellationControlMsg, LayoutMsg, ProgressiveWebMetricType};
use servo_config::opts;
use servo_url::ServoUrl;
use std::cell::{Cell, RefCell};
use std::cmp::Ordering;
use std::collections::HashMap;
use time::precise_time_ns;
pub trait ProfilerMetadataFactory {
fn new_metadata(&self) -> Option<TimerMetadata>;
}
pub trait ProgressiveWebMetric {
fn get_navigation_start(&self) -> Option<u64>;
fn set_navigation_start(&mut self, time: u64);
fn get_time_profiler_chan(&self) -> &ProfilerChan;
fn send_queued_constellation_msg(&self, name: ProgressiveWebMetricType, time: u64);
fn get_url(&self) -> &ServoUrl;
}
/// TODO make this configurable
/// maximum task time is 50ms (in ns)
pub const MAX_TASK_NS: u64 = 50000000;
/// 10 second window (in ns)
const INTERACTIVE_WINDOW_SECONDS_IN_NS: u64 = 10000000000;
pub trait ToMs<T> {
fn to_ms(&self) -> T;
}
impl ToMs<f64> for u64 {
fn to_ms(&self) -> f64
|
}
fn set_metric<U: ProgressiveWebMetric>(
pwm: &U,
metadata: Option<TimerMetadata>,
metric_type: ProgressiveWebMetricType,
category: ProfilerCategory,
attr: &Cell<Option<u64>>,
metric_time: Option<u64>,
url: &ServoUrl,
) {
let navigation_start = match pwm.get_navigation_start() {
Some(time) => time,
None => {
warn!("Trying to set metric before navigation start");
return;
},
};
let now = match metric_time {
Some(time) => time,
None => precise_time_ns(),
};
let time = now - navigation_start;
attr.set(Some(time));
// Queue performance observer notification.
pwm.send_queued_constellation_msg(metric_type, time);
// Send the metric to the time profiler.
send_profile_data(
category,
metadata,
&pwm.get_time_profiler_chan(),
time,
time,
0,
0,
);
// Print the metric to console if the print-pwm option was given.
if opts::get().print_pwm {
println!(
"Navigation start: {}",
pwm.get_navigation_start().unwrap().to_ms()
);
println!("{:?} {:?} {:?}", url, metric_type, time.to_ms());
}
}
// spec: https://github.com/WICG/time-to-interactive
// https://github.com/GoogleChrome/lighthouse/issues/27
// we can look at three different metrics here:
// navigation start -> visually ready (dom content loaded)
// navigation start -> thread ready (main thread available)
// visually ready -> thread ready
#[derive(MallocSizeOf)]
pub struct InteractiveMetrics {
/// when we navigated to the page
navigation_start: Option<u64>,
/// indicates if the page is visually ready
dom_content_loaded: Cell<Option<u64>>,
/// main thread is available -- there's been a 10s window with no tasks longer than 50ms
main_thread_available: Cell<Option<u64>>,
// max(main_thread_available, dom_content_loaded)
time_to_interactive: Cell<Option<u64>>,
#[ignore_malloc_size_of = "can't measure channels"]
time_profiler_chan: ProfilerChan,
url: ServoUrl,
}
#[derive(Clone, Copy, Debug, MallocSizeOf)]
pub struct InteractiveWindow {
start: u64,
}
impl InteractiveWindow {
pub fn new() -> InteractiveWindow {
InteractiveWindow {
start: precise_time_ns(),
}
}
// We need to either start or restart the 10s window
// start: we've added a new document
// restart: there was a task > 50ms
// not all documents are interactive
pub fn start_window(&mut self) {
self.start = precise_time_ns();
}
/// check if 10s has elapsed since start
pub fn needs_check(&self) -> bool {
precise_time_ns() - self.start >= INTERACTIVE_WINDOW_SECONDS_IN_NS
}
pub fn get_start(&self) -> u64 {
self.start
}
}
#[derive(Debug)]
pub enum InteractiveFlag {
DOMContentLoaded,
TimeToInteractive(u64),
}
impl InteractiveMetrics {
pub fn new(time_profiler_chan: ProfilerChan, url: ServoUrl) -> InteractiveMetrics {
InteractiveMetrics {
navigation_start: None,
dom_content_loaded: Cell::new(None),
main_thread_available: Cell::new(None),
time_to_interactive: Cell::new(None),
time_profiler_chan: time_profiler_chan,
url,
}
}
pub fn set_dom_content_loaded(&self) {
if self.dom_content_loaded.get().is_none() {
self.dom_content_loaded.set(Some(precise_time_ns()));
}
}
pub fn set_main_thread_available(&self, time: u64) {
if self.main_thread_available.get().is_none() {
self.main_thread_available.set(Some(time));
}
}
pub fn get_dom_content_loaded(&self) -> Option<u64> {
self.dom_content_loaded.get()
}
pub fn get_main_thread_available(&self) -> Option<u64> {
self.main_thread_available.get()
}
// can set either dlc or tti first, but both must be set to actually calc metric
// when the second is set, set_tti is called with appropriate time
pub fn maybe_set_tti<T>(&self, profiler_metadata_factory: &T, metric: InteractiveFlag)
where
T: ProfilerMetadataFactory,
{
if self.get_tti().is_some() {
return;
}
match metric {
InteractiveFlag::DOMContentLoaded => self.set_dom_content_loaded(),
InteractiveFlag::TimeToInteractive(time) => self.set_main_thread_available(time),
}
let dcl = self.dom_content_loaded.get();
let mta = self.main_thread_available.get();
let (dcl, mta) = match (dcl, mta) {
(Some(dcl), Some(mta)) => (dcl, mta),
_ => return,
};
let metric_time = match dcl.partial_cmp(&mta) {
Some(Ordering::Less) => mta,
Some(_) => dcl,
None => panic!("no ordering possible. something bad happened"),
};
set_metric(
self,
profiler_metadata_factory.new_metadata(),
ProgressiveWebMetricType::TimeToInteractive,
ProfilerCategory::TimeToInteractive,
&self.time_to_interactive,
Some(metric_time),
&self.url,
);
}
pub fn get_tti(&self) -> Option<u64> {
self.time_to_interactive.get()
}
pub fn needs_tti(&self) -> bool {
self.get_tti().is_none()
}
}
impl ProgressiveWebMetric for InteractiveMetrics {
fn get_navigation_start(&self) -> Option<u64> {
self.navigation_start
}
fn set_navigation_start(&mut self, time: u64) {
self.navigation_start = Some(time);
}
fn send_queued_constellation_msg(&self, _name: ProgressiveWebMetricType, _time: u64) {}
fn get_time_profiler_chan(&self) -> &ProfilerChan {
&self.time_profiler_chan
}
fn get_url(&self) -> &ServoUrl {
&self.url
}
}
// https://w3c.github.io/paint-timing/
pub struct PaintTimeMetrics {
pending_metrics: RefCell<HashMap<Epoch, (Option<TimerMetadata>, bool)>>,
navigation_start: Option<u64>,
first_paint: Cell<Option<u64>>,
first_contentful_paint: Cell<Option<u64>>,
pipeline_id: PipelineId,
time_profiler_chan: ProfilerChan,
constellation_chan: IpcSender<LayoutMsg>,
script_chan: IpcSender<ConstellationControlMsg>,
url: ServoUrl,
}
impl PaintTimeMetrics {
pub fn new(
pipeline_id: PipelineId,
time_profiler_chan: ProfilerChan,
constellation_chan: IpcSender<LayoutMsg>,
script_chan: IpcSender<ConstellationControlMsg>,
url: ServoUrl,
) -> PaintTimeMetrics {
PaintTimeMetrics {
pending_metrics: RefCell::new(HashMap::new()),
navigation_start: None,
first_paint: Cell::new(None),
first_contentful_paint: Cell::new(None),
pipeline_id,
time_profiler_chan,
constellation_chan,
script_chan,
url,
}
}
pub fn maybe_set_first_paint<T>(&self, profiler_metadata_factory: &T)
where
T: ProfilerMetadataFactory,
{
if self.first_paint.get().is_some() {
return;
}
set_metric(
self,
profiler_metadata_factory.new_metadata(),
ProgressiveWebMetricType::FirstPaint,
ProfilerCategory::TimeToFirstPaint,
&self.first_paint,
None,
&self.url,
);
}
pub fn maybe_observe_paint_time<T>(
&self,
profiler_metadata_factory: &T,
epoch: Epoch,
display_list: &DisplayList,
) where
T: ProfilerMetadataFactory,
{
if self.first_paint.get().is_some() && self.first_contentful_paint.get().is_some() {
// If we already set all paint metrics, we just bail out.
return;
}
self.pending_metrics.borrow_mut().insert(
epoch,
(
profiler_metadata_factory.new_metadata(),
display_list.is_contentful(),
),
);
// Send the pending metric information to the compositor thread.
// The compositor will record the current time after painting the
// frame with the given ID and will send the metric back to us.
let msg = LayoutMsg::PendingPaintMetric(self.pipeline_id, epoch);
if let Err(e) = self.constellation_chan.send(msg) {
warn!("Failed to send PendingPaintMetric {:?}", e);
}
}
pub fn maybe_set_metric(&self, epoch: Epoch, paint_time: u64) {
if self.first_paint.get().is_some() && self.first_contentful_paint.get().is_some() ||
self.navigation_start.is_none()
{
// If we already set all paint metrics or we have not set navigation start yet,
// we just bail out.
return;
}
if let Some(pending_metric) = self.pending_metrics.borrow_mut().remove(&epoch) {
let profiler_metadata = pending_metric.0;
set_metric(
self,
profiler_metadata.clone(),
ProgressiveWebMetricType::FirstPaint,
ProfilerCategory::TimeToFirstPaint,
&self.first_paint,
Some(paint_time),
&self.url,
);
if pending_metric.1 {
set_metric(
self,
profiler_metadata,
ProgressiveWebMetricType::FirstContentfulPaint,
ProfilerCategory::TimeToFirstContentfulPaint,
&self.first_contentful_paint,
Some(paint_time),
&self.url,
);
}
}
}
pub fn get_first_paint(&self) -> Option<u64> {
self.first_paint.get()
}
pub fn get_first_contentful_paint(&self) -> Option<u64> {
self.first_contentful_paint.get()
}
}
impl ProgressiveWebMetric for PaintTimeMetrics {
fn get_navigation_start(&self) -> Option<u64> {
self.navigation_start
}
fn set_navigation_start(&mut self, time: u64) {
self.navigation_start = Some(time);
}
fn send_queued_constellation_msg(&self, name: ProgressiveWebMetricType, time: u64) {
let msg = ConstellationControlMsg::PaintMetric(self.pipeline_id, name, time);
if let Err(e) = self.script_chan.send(msg) {
warn!("Sending metric to script thread failed ({}).", e);
}
}
fn get_time_profiler_chan(&self) -> &ProfilerChan {
&self.time_profiler_chan
}
fn get_url(&self) -> &ServoUrl {
&self.url
}
}
|
{
*self as f64 / 1000000.
}
|
identifier_body
|
lib.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
extern crate gfx_traits;
extern crate ipc_channel;
#[macro_use]
extern crate log;
extern crate malloc_size_of;
#[macro_use]
extern crate malloc_size_of_derive;
extern crate msg;
extern crate profile_traits;
extern crate script_traits;
extern crate servo_config;
extern crate servo_url;
extern crate time;
use gfx_traits::{Epoch, DisplayList};
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use profile_traits::time::{ProfilerChan, ProfilerCategory, send_profile_data};
use profile_traits::time::TimerMetadata;
use script_traits::{ConstellationControlMsg, LayoutMsg, ProgressiveWebMetricType};
use servo_config::opts;
use servo_url::ServoUrl;
use std::cell::{Cell, RefCell};
use std::cmp::Ordering;
use std::collections::HashMap;
use time::precise_time_ns;
pub trait ProfilerMetadataFactory {
fn new_metadata(&self) -> Option<TimerMetadata>;
}
pub trait ProgressiveWebMetric {
fn get_navigation_start(&self) -> Option<u64>;
fn set_navigation_start(&mut self, time: u64);
fn get_time_profiler_chan(&self) -> &ProfilerChan;
fn send_queued_constellation_msg(&self, name: ProgressiveWebMetricType, time: u64);
fn get_url(&self) -> &ServoUrl;
}
/// TODO make this configurable
/// maximum task time is 50ms (in ns)
pub const MAX_TASK_NS: u64 = 50000000;
/// 10 second window (in ns)
const INTERACTIVE_WINDOW_SECONDS_IN_NS: u64 = 10000000000;
pub trait ToMs<T> {
fn to_ms(&self) -> T;
}
impl ToMs<f64> for u64 {
fn to_ms(&self) -> f64 {
*self as f64 / 1000000.
}
}
fn set_metric<U: ProgressiveWebMetric>(
pwm: &U,
metadata: Option<TimerMetadata>,
metric_type: ProgressiveWebMetricType,
category: ProfilerCategory,
attr: &Cell<Option<u64>>,
metric_time: Option<u64>,
url: &ServoUrl,
) {
let navigation_start = match pwm.get_navigation_start() {
Some(time) => time,
None => {
warn!("Trying to set metric before navigation start");
return;
},
};
let now = match metric_time {
Some(time) => time,
None => precise_time_ns(),
};
let time = now - navigation_start;
attr.set(Some(time));
// Queue performance observer notification.
pwm.send_queued_constellation_msg(metric_type, time);
// Send the metric to the time profiler.
send_profile_data(
category,
metadata,
&pwm.get_time_profiler_chan(),
time,
time,
0,
0,
);
// Print the metric to console if the print-pwm option was given.
if opts::get().print_pwm {
println!(
"Navigation start: {}",
pwm.get_navigation_start().unwrap().to_ms()
);
println!("{:?} {:?} {:?}", url, metric_type, time.to_ms());
}
}
// spec: https://github.com/WICG/time-to-interactive
// https://github.com/GoogleChrome/lighthouse/issues/27
// we can look at three different metrics here:
// navigation start -> visually ready (dom content loaded)
// navigation start -> thread ready (main thread available)
// visually ready -> thread ready
#[derive(MallocSizeOf)]
pub struct InteractiveMetrics {
/// when we navigated to the page
navigation_start: Option<u64>,
/// indicates if the page is visually ready
dom_content_loaded: Cell<Option<u64>>,
/// main thread is available -- there's been a 10s window with no tasks longer than 50ms
main_thread_available: Cell<Option<u64>>,
// max(main_thread_available, dom_content_loaded)
time_to_interactive: Cell<Option<u64>>,
#[ignore_malloc_size_of = "can't measure channels"]
time_profiler_chan: ProfilerChan,
url: ServoUrl,
}
#[derive(Clone, Copy, Debug, MallocSizeOf)]
pub struct InteractiveWindow {
start: u64,
}
impl InteractiveWindow {
pub fn new() -> InteractiveWindow {
InteractiveWindow {
start: precise_time_ns(),
}
}
// We need to either start or restart the 10s window
// start: we've added a new document
// restart: there was a task > 50ms
// not all documents are interactive
pub fn start_window(&mut self) {
self.start = precise_time_ns();
}
/// check if 10s has elapsed since start
pub fn needs_check(&self) -> bool {
precise_time_ns() - self.start >= INTERACTIVE_WINDOW_SECONDS_IN_NS
}
pub fn get_start(&self) -> u64 {
self.start
}
}
#[derive(Debug)]
pub enum InteractiveFlag {
DOMContentLoaded,
TimeToInteractive(u64),
}
impl InteractiveMetrics {
pub fn new(time_profiler_chan: ProfilerChan, url: ServoUrl) -> InteractiveMetrics {
InteractiveMetrics {
navigation_start: None,
dom_content_loaded: Cell::new(None),
main_thread_available: Cell::new(None),
time_to_interactive: Cell::new(None),
time_profiler_chan: time_profiler_chan,
url,
}
}
pub fn set_dom_content_loaded(&self) {
if self.dom_content_loaded.get().is_none() {
self.dom_content_loaded.set(Some(precise_time_ns()));
}
}
pub fn set_main_thread_available(&self, time: u64) {
|
pub fn get_dom_content_loaded(&self) -> Option<u64> {
self.dom_content_loaded.get()
}
pub fn get_main_thread_available(&self) -> Option<u64> {
self.main_thread_available.get()
}
// can set either dlc or tti first, but both must be set to actually calc metric
// when the second is set, set_tti is called with appropriate time
pub fn maybe_set_tti<T>(&self, profiler_metadata_factory: &T, metric: InteractiveFlag)
where
T: ProfilerMetadataFactory,
{
if self.get_tti().is_some() {
return;
}
match metric {
InteractiveFlag::DOMContentLoaded => self.set_dom_content_loaded(),
InteractiveFlag::TimeToInteractive(time) => self.set_main_thread_available(time),
}
let dcl = self.dom_content_loaded.get();
let mta = self.main_thread_available.get();
let (dcl, mta) = match (dcl, mta) {
(Some(dcl), Some(mta)) => (dcl, mta),
_ => return,
};
let metric_time = match dcl.partial_cmp(&mta) {
Some(Ordering::Less) => mta,
Some(_) => dcl,
None => panic!("no ordering possible. something bad happened"),
};
set_metric(
self,
profiler_metadata_factory.new_metadata(),
ProgressiveWebMetricType::TimeToInteractive,
ProfilerCategory::TimeToInteractive,
&self.time_to_interactive,
Some(metric_time),
&self.url,
);
}
pub fn get_tti(&self) -> Option<u64> {
self.time_to_interactive.get()
}
pub fn needs_tti(&self) -> bool {
self.get_tti().is_none()
}
}
impl ProgressiveWebMetric for InteractiveMetrics {
fn get_navigation_start(&self) -> Option<u64> {
self.navigation_start
}
fn set_navigation_start(&mut self, time: u64) {
self.navigation_start = Some(time);
}
fn send_queued_constellation_msg(&self, _name: ProgressiveWebMetricType, _time: u64) {}
fn get_time_profiler_chan(&self) -> &ProfilerChan {
&self.time_profiler_chan
}
fn get_url(&self) -> &ServoUrl {
&self.url
}
}
// https://w3c.github.io/paint-timing/
pub struct PaintTimeMetrics {
pending_metrics: RefCell<HashMap<Epoch, (Option<TimerMetadata>, bool)>>,
navigation_start: Option<u64>,
first_paint: Cell<Option<u64>>,
first_contentful_paint: Cell<Option<u64>>,
pipeline_id: PipelineId,
time_profiler_chan: ProfilerChan,
constellation_chan: IpcSender<LayoutMsg>,
script_chan: IpcSender<ConstellationControlMsg>,
url: ServoUrl,
}
impl PaintTimeMetrics {
pub fn new(
pipeline_id: PipelineId,
time_profiler_chan: ProfilerChan,
constellation_chan: IpcSender<LayoutMsg>,
script_chan: IpcSender<ConstellationControlMsg>,
url: ServoUrl,
) -> PaintTimeMetrics {
PaintTimeMetrics {
pending_metrics: RefCell::new(HashMap::new()),
navigation_start: None,
first_paint: Cell::new(None),
first_contentful_paint: Cell::new(None),
pipeline_id,
time_profiler_chan,
constellation_chan,
script_chan,
url,
}
}
pub fn maybe_set_first_paint<T>(&self, profiler_metadata_factory: &T)
where
T: ProfilerMetadataFactory,
{
if self.first_paint.get().is_some() {
return;
}
set_metric(
self,
profiler_metadata_factory.new_metadata(),
ProgressiveWebMetricType::FirstPaint,
ProfilerCategory::TimeToFirstPaint,
&self.first_paint,
None,
&self.url,
);
}
pub fn maybe_observe_paint_time<T>(
&self,
profiler_metadata_factory: &T,
epoch: Epoch,
display_list: &DisplayList,
) where
T: ProfilerMetadataFactory,
{
if self.first_paint.get().is_some() && self.first_contentful_paint.get().is_some() {
// If we already set all paint metrics, we just bail out.
return;
}
self.pending_metrics.borrow_mut().insert(
epoch,
(
profiler_metadata_factory.new_metadata(),
display_list.is_contentful(),
),
);
// Send the pending metric information to the compositor thread.
// The compositor will record the current time after painting the
// frame with the given ID and will send the metric back to us.
let msg = LayoutMsg::PendingPaintMetric(self.pipeline_id, epoch);
if let Err(e) = self.constellation_chan.send(msg) {
warn!("Failed to send PendingPaintMetric {:?}", e);
}
}
pub fn maybe_set_metric(&self, epoch: Epoch, paint_time: u64) {
if self.first_paint.get().is_some() && self.first_contentful_paint.get().is_some() ||
self.navigation_start.is_none()
{
// If we already set all paint metrics or we have not set navigation start yet,
// we just bail out.
return;
}
if let Some(pending_metric) = self.pending_metrics.borrow_mut().remove(&epoch) {
let profiler_metadata = pending_metric.0;
set_metric(
self,
profiler_metadata.clone(),
ProgressiveWebMetricType::FirstPaint,
ProfilerCategory::TimeToFirstPaint,
&self.first_paint,
Some(paint_time),
&self.url,
);
if pending_metric.1 {
set_metric(
self,
profiler_metadata,
ProgressiveWebMetricType::FirstContentfulPaint,
ProfilerCategory::TimeToFirstContentfulPaint,
&self.first_contentful_paint,
Some(paint_time),
&self.url,
);
}
}
}
pub fn get_first_paint(&self) -> Option<u64> {
self.first_paint.get()
}
pub fn get_first_contentful_paint(&self) -> Option<u64> {
self.first_contentful_paint.get()
}
}
impl ProgressiveWebMetric for PaintTimeMetrics {
fn get_navigation_start(&self) -> Option<u64> {
self.navigation_start
}
fn set_navigation_start(&mut self, time: u64) {
self.navigation_start = Some(time);
}
fn send_queued_constellation_msg(&self, name: ProgressiveWebMetricType, time: u64) {
let msg = ConstellationControlMsg::PaintMetric(self.pipeline_id, name, time);
if let Err(e) = self.script_chan.send(msg) {
warn!("Sending metric to script thread failed ({}).", e);
}
}
fn get_time_profiler_chan(&self) -> &ProfilerChan {
&self.time_profiler_chan
}
fn get_url(&self) -> &ServoUrl {
&self.url
}
}
|
if self.main_thread_available.get().is_none() {
self.main_thread_available.set(Some(time));
}
}
|
random_line_split
|
Privacy.js
|
/* jshint ignore: start */
import React from 'react';
import Footer from './Footer';
import Popup from 'reactjs-popup';
import BurgerIcon from './BurgerIcon';
import Menu from './Menu';
// import { Content } from 'reactbulma';
import '../smde-editor.css';
const styles = {
fontFamily: 'sans-serif',
textAlign: 'left',
marginTop: '40px'
};
const contentStyle = {
background: 'rgba(255,255,255,0)',
width: '80%',
border: 'none'
};
const Privacy = () => (
<React.Fragment>
<div style={styles}>
<Popup
modal
overlayStyle={{ background: 'rgba(255,255,255,0.98' }}
contentStyle={contentStyle}
closeOnDocumentClick={false}
trigger={open => <BurgerIcon open={open} />}
>
{close => <Menu close={close} />}
</Popup>
</div>
<div className="container is-fluid content">
<h1>Privacy Policy</h1>
<p>Effective date: September 20, 2018</p>
<p>
Check Yo Self ("us", "we", or "our") operates the
https://checkyoself.netlify.com website (the "Service").
</p>
<p>
This page informs you of our policies regarding the collection, use,
and disclosure of personal data when you use our Service and the
choices you have associated with that data. Our Privacy Policy for
Check Yo Self is managed through{' '}
<a href="https://www.freeprivacypolicy.com/free-privacy-policy-generator.php">
Free Privacy Policy
</a>.
</p>
<p>
We use your data to provide and improve the Service. By using the
Service, you agree to the collection and use of information in
accordance with this policy. Unless otherwise defined in this
Privacy Policy, terms used in this Privacy Policy have the same
meanings as in our Terms and Conditions, accessible from
https://checkyoself.netlify.com
</p>
<h2>Information Collection And Use</h2>
<p>
We collect several different types of information for various
purposes to provide and improve our Service to you.
</p>
<h3>Types of Data Collected</h3>
<h4>Personal Data</h4>
<p>
While using our Service, we may ask you to provide us with certain
personally identifiable information that can be used to contact or
identify you ("Personal Data"). Personally identifiable information
may include, but is not limited to:
</p>
<ul>
<li>Cookies and Usage Data</li>
</ul>
<h4>Usage Data</h4>
<p>
We may also collect information how the Service is accessed and used
("Usage Data"). This Usage Data may include information such as your
computer's Internet Protocol address (e.g. IP address), browser
type, browser version, the pages of our Service that you visit, the
time and date of your visit, the time spent on those pages, unique
device identifiers and other diagnostic data.
</p>
<h4>Tracking & Cookies Data</h4>
<p>
We use cookies and similar tracking technologies to track the
activity on our Service and hold certain information.
</p>
<p>
Cookies are files with small amount of data which may include an
anonymous unique identifier. Cookies are sent to your browser from a
website and stored on your device. Tracking technologies also used
are beacons, tags, and scripts to collect and track information and
to improve and analyze our Service.
</p>
<p>
You can instruct your browser to refuse all cookies or to indicate
when a cookie is being sent. However, if you do not accept cookies,
you may not be able to use some portions of our Service.
</p>
<p>Examples of Cookies we use:</p>
<ul>
<li>
<strong>Session Cookies.</strong> We use Session Cookies to
operate our Service.
</li>
<li>
<strong>Preference Cookies.</strong> We use Preference Cookies to
remember your preferences and various settings.
</li>
<li>
<strong>Security Cookies.</strong> We use Security Cookies for
security purposes.
</li>
</ul>
<h2>Use of Data</h2>
<p>Check Yo Self uses the collected data for various purposes:</p>
<ul>
<li>To provide and maintain the Service</li>
<li>To notify you about changes to our Service</li>
<li>
To allow you to participate in interactive features of our Service
when you choose to do so
</li>
<li>To provide customer care and support</li>
<li>
To provide analysis or valuable information so that we can improve
the Service
</li>
<li>To monitor the usage of the Service</li>
<li>To detect, prevent and address technical issues</li>
</ul>
<h2>Transfer Of Data</h2>
<p>
Your information, including Personal Data, may be transferred to —
and maintained on — computers located outside of your state,
province, country or other governmental jurisdiction where the data
protection laws may differ than those from your jurisdiction.
</p>
<p>
If you are located outside United States and choose to provide
information to us, please note that we transfer the data, including
Personal Data, to United States and process it there.
</p>
<p>
Your consent to this Privacy Policy followed by your submission of
such information represents your agreement to that transfer.
</p>
<p>
Check Yo Self will take all steps reasonably necessary to ensure
that your data is treated securely and in accordance with this
Privacy Policy and no transfer of your Personal Data will take place
to an organization or a country unless there are adequate controls
in place including the security of your data and other personal
information.
</p>
<h2>Disclosure Of Data</h2>
<h3>Legal Requirements</h3>
<p>
Check Yo Self may disclose your Personal Data in the good faith
belief that such action is necessary to:
</p>
<ul>
<li>To comply with a legal obligation</li>
<li>
To protect and defend the rights or property of Check Yo Self
</li>
<li>
To prevent or investigate possible wrongdoing in connection with
the Service
</li>
<li>
To protect the personal safety of users of the Service or the
public
</li>
<li>To protect against legal liability</li>
</ul>
<h2>Security Of Data</h2>
<p>
The security of your data is important to us, but remember that no
method of transmission over the Internet, or method of electronic
storage is 100% secure. While we strive to use commercially
acceptable means to protect your Personal Data, we cannot guarantee
its absolute security.
</p>
<h2>Service Providers</h2>
<p>
We may employ third party companies and individuals to facilitate
our Service ("Service Providers"), to provide the Service on our
behalf, to perform Service-related services or to assist us in
analyzing how our Service is used.
</p>
<p>
These third parties have access to your Personal Data only to
perform these tasks on our behalf and are obligated not to disclose
|
<h3>Analytics</h3>
<p>
We may use third-party Service Providers to monitor and analyze the
use of our Service.
</p>
<ul>
<li>
<p>
<strong>Google Analytics</strong>
</p>
<p>
Google Analytics is a web analytics service offered by Google
that tracks and reports website traffic. Google uses the data
collected to track and monitor the use of our Service. This data
is shared with other Google services. Google may use the
collected data to contextualize and personalize the ads of its
own advertising network.
</p>
<p>
You can opt-out of having made your activity on the Service
available to Google Analytics by installing the Google Analytics
opt-out browser add-on. The add-on prevents the Google Analytics
JavaScript (ga.js, analytics.js, and dc.js) from sharing
information with Google Analytics about visits activity.
</p>
<p>
For more information on the privacy practices of Google, please
visit the Google Privacy & Terms web page:{' '}
<a href="https://policies.google.com/privacy?hl=en">
https://policies.google.com/privacy?hl=en
</a>
</p>
</li>
</ul>
<h2>Links To Other Sites</h2>
<p>
Our Service may contain links to other sites that are not operated
by us. If you click on a third party link, you will be directed to
that third party's site. We strongly advise you to review the
Privacy Policy of every site you visit.
</p>
<p>
We have no control over and assume no responsibility for the
content, privacy policies or practices of any third party sites or
services.
</p>
<h2>Children's Privacy</h2>
<p>
Our Service does not address anyone under the age of 18
("Children").
</p>
<p>
We do not knowingly collect personally identifiable information from
anyone under the age of 18. If you are a parent or guardian and you
are aware that your Children has provided us with Personal Data,
please contact us. If we become aware that we have collected
Personal Data from children without verification of parental
consent, we take steps to remove that information from our servers.
</p>
<h2>Changes To This Privacy Policy</h2>
<p>
We may update our Privacy Policy from time to time. We will notify
you of any changes by posting the new Privacy Policy on this page.
</p>
<p>
We will let you know via email and/or a prominent notice on our
Service, prior to the change becoming effective and update the
"effective date" at the top of this Privacy Policy.
</p>
<p>
You are advised to review this Privacy Policy periodically for any
changes. Changes to this Privacy Policy are effective when they are
posted on this page.
</p>
<h2>Contact Us</h2>
<p>
If you have any questions about this Privacy Policy, please contact
us:
</p>
<ul>
<li>By email: <a href="mailto:[email protected]">[email protected]</a></li>
</ul>
</div>
<Footer />
</React.Fragment>
);
export default Privacy;
|
or use it for any other purpose.
</p>
|
random_line_split
|
server.js
|
/**
* Runs a webserver and socket server for visualizating interactions with TJBot
*/
var ip = require('ip');
var express = require("express")
var config = require('./config.js')
var path = require("path")
var app = express();
var http = require('http');
var exports = module.exports = {};
// routes
var routes = require('./routes/index');
var server = http.createServer(app).listen(config.webServerNumber, function() {
var addr = server.address();
console.log('Dashboard running at : http://' + ip.address() + ':' + addr.port);
});
var bodyParser = require('body-parser');
var bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: false
}))
// parse application/json
app.use(bodyParser.json());
app.set('view engine', 'pug');
app.use(express.static('public'));
app.use('/', routes);
var WebSocket = require('ws');
var wss = new WebSocket.Server({
server
});
var clients = new Map();
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
});
clients.set(ws._socket._handle.fd, ws);
//clients.push({id: ws._socket._handle.fd , client: });
// ws.send('something ......');
var hold = ws;
ws.on('close', function close() {
console.log("closing ");
// clients.delete(ws._socket._handle.fd);
});
});
var sendEvent = function(data) {
console.log("Number of connectd clients", clients.size)
for (var [key, client] of clients) {
//console.log(key + ' = sending');
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(data))
} else
|
}
}
exports.sendEvent = sendEvent;
exports.wss = wss
|
{
clients.delete(key);
}
|
conditional_block
|
server.js
|
/**
* Runs a webserver and socket server for visualizating interactions with TJBot
*/
var ip = require('ip');
var express = require("express")
var config = require('./config.js')
var path = require("path")
var app = express();
var http = require('http');
var exports = module.exports = {};
// routes
var routes = require('./routes/index');
var server = http.createServer(app).listen(config.webServerNumber, function() {
var addr = server.address();
console.log('Dashboard running at : http://' + ip.address() + ':' + addr.port);
});
var bodyParser = require('body-parser');
var bodyParser = require('body-parser');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: false
}))
// parse application/json
app.use(bodyParser.json());
app.set('view engine', 'pug');
|
var WebSocket = require('ws');
var wss = new WebSocket.Server({
server
});
var clients = new Map();
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
});
clients.set(ws._socket._handle.fd, ws);
//clients.push({id: ws._socket._handle.fd , client: });
// ws.send('something ......');
var hold = ws;
ws.on('close', function close() {
console.log("closing ");
// clients.delete(ws._socket._handle.fd);
});
});
var sendEvent = function(data) {
console.log("Number of connectd clients", clients.size)
for (var [key, client] of clients) {
//console.log(key + ' = sending');
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(data))
} else {
clients.delete(key);
}
}
}
exports.sendEvent = sendEvent;
exports.wss = wss
|
app.use(express.static('public'));
app.use('/', routes);
|
random_line_split
|
lib.js
|
var ArrayProto = Array.prototype;
var ObjProto = Object.prototype;
var escapeMap = {
'&': '&',
'"': '"',
"'": ''',
"<": '<',
">": '>'
};
var escapeRegex = /[&"'<>]/g;
var lookupEscape = function(ch) {
return escapeMap[ch];
};
var exports = module.exports = {};
exports.withPrettyErrors = function(path, withInternals, func) {
try {
return func();
} catch (e) {
if (!e.Update) {
// not one of ours, cast it
e = new exports.TemplateError(e);
}
e.Update(path);
// Unless they marked the dev flag, show them a trace from here
if (!withInternals) {
var old = e;
e = new Error(old.message);
e.name = old.name;
}
throw e;
}
};
exports.TemplateError = function(message, lineno, colno) {
var err = this;
if (message instanceof Error) { // for casting regular js errors
err = message;
message = message.name + ": " + message.message;
} else {
if(Error.captureStackTrace) {
Error.captureStackTrace(err);
}
}
err.name = 'Template render error';
err.message = message;
err.lineno = lineno;
err.colno = colno;
err.firstUpdate = true;
err.Update = function(path) {
var message = "(" + (path || "unknown path") + ")";
// only show lineno + colno next to path of template
// where error occurred
if (this.firstUpdate) {
if(this.lineno && this.colno) {
message += ' [Line ' + this.lineno + ', Column ' + this.colno + ']';
}
else if(this.lineno) {
message += ' [Line ' + this.lineno + ']';
}
}
message += '\n ';
if (this.firstUpdate) {
message += ' ';
}
this.message = message + (this.message || '');
this.firstUpdate = false;
return this;
};
return err;
};
exports.TemplateError.prototype = Error.prototype;
exports.escape = function(val) {
return val.replace(escapeRegex, lookupEscape);
};
exports.isFunction = function(obj) {
return ObjProto.toString.call(obj) == '[object Function]';
};
exports.isArray = Array.isArray || function(obj) {
return ObjProto.toString.call(obj) == '[object Array]';
};
exports.isString = function(obj) {
return ObjProto.toString.call(obj) == '[object String]';
};
exports.isObject = function(obj) {
return ObjProto.toString.call(obj) == '[object Object]';
};
exports.groupBy = function(obj, val) {
var result = {};
var iterator = exports.isFunction(val) ? val : function(obj) { return obj[val]; };
for(var i=0; i<obj.length; i++) {
var value = obj[i];
var key = iterator(value, i);
(result[key] || (result[key] = [])).push(value);
}
return result;
};
exports.toArray = function(obj) {
return Array.prototype.slice.call(obj);
};
exports.without = function(array) {
var result = [];
if (!array) {
return result;
}
var index = -1,
length = array.length,
contains = exports.toArray(arguments).slice(1);
while(++index < length) {
if(exports.indexOf(contains, array[index]) === -1) {
result.push(array[index]);
}
}
return result;
};
exports.extend = function(obj, obj2) {
for(var k in obj2) {
obj[k] = obj2[k];
}
return obj;
};
exports.repeat = function(char_, n) {
var str = '';
for(var i=0; i<n; i++) {
str += char_;
}
return str;
};
exports.each = function(obj, func, context) {
if(obj == null) {
return;
}
if(ArrayProto.each && obj.each == ArrayProto.each) {
obj.forEach(func, context);
}
else if(obj.length === +obj.length) {
for(var i=0, l=obj.length; i<l; i++) {
func.call(context, obj[i], i, obj);
}
}
};
exports.map = function(obj, func) {
var results = [];
if(obj == null) {
return results;
}
if(ArrayProto.map && obj.map === ArrayProto.map) {
return obj.map(func);
}
for(var i=0; i<obj.length; i++) {
results[results.length] = func(obj[i], i);
}
if(obj.length === +obj.length) {
results.length = obj.length;
}
return results;
};
exports.asyncIter = function(arr, iter, cb) {
var i = -1;
function next() {
i++;
if(i < arr.length) {
iter(arr[i], i, next, cb);
}
else {
cb();
}
}
next();
};
exports.asyncFor = function(obj, iter, cb) {
var keys = exports.keys(obj);
var len = keys.length;
var i = -1;
function next() {
i++;
var k = keys[i];
if(i < len) {
iter(k, obj[k], i, len, next);
}
else {
cb();
}
}
next();
};
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill
exports.indexOf = Array.prototype.indexOf ?
function (arr, searchElement, fromIndex) {
return Array.prototype.indexOf.call(arr, searchElement, fromIndex);
} :
function (arr, searchElement, fromIndex) {
var length = this.length >>> 0; // Hack to convert object.length to a UInt32
fromIndex = +fromIndex || 0;
if(Math.abs(fromIndex) === Infinity) {
fromIndex = 0;
}
if(fromIndex < 0) {
fromIndex += length;
if (fromIndex < 0)
|
}
for(;fromIndex < length; fromIndex++) {
if (arr[fromIndex] === searchElement) {
return fromIndex;
}
}
return -1;
};
if(!Array.prototype.map) {
Array.prototype.map = function() {
throw new Error("map is unimplemented for this js engine");
};
}
exports.keys = function(obj) {
if(Object.prototype.keys) {
return obj.keys();
}
else {
var keys = [];
for(var k in obj) {
if(obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
}
}
|
{
fromIndex = 0;
}
|
conditional_block
|
lib.js
|
var ArrayProto = Array.prototype;
var ObjProto = Object.prototype;
var escapeMap = {
'&': '&',
'"': '"',
"'": ''',
"<": '<',
">": '>'
};
var escapeRegex = /[&"'<>]/g;
var lookupEscape = function(ch) {
return escapeMap[ch];
};
var exports = module.exports = {};
exports.withPrettyErrors = function(path, withInternals, func) {
try {
return func();
} catch (e) {
if (!e.Update) {
// not one of ours, cast it
e = new exports.TemplateError(e);
}
e.Update(path);
// Unless they marked the dev flag, show them a trace from here
if (!withInternals) {
var old = e;
e = new Error(old.message);
e.name = old.name;
}
throw e;
}
};
exports.TemplateError = function(message, lineno, colno) {
var err = this;
if (message instanceof Error) { // for casting regular js errors
err = message;
message = message.name + ": " + message.message;
} else {
if(Error.captureStackTrace) {
Error.captureStackTrace(err);
}
}
err.name = 'Template render error';
err.message = message;
err.lineno = lineno;
err.colno = colno;
err.firstUpdate = true;
err.Update = function(path) {
var message = "(" + (path || "unknown path") + ")";
// only show lineno + colno next to path of template
// where error occurred
if (this.firstUpdate) {
if(this.lineno && this.colno) {
message += ' [Line ' + this.lineno + ', Column ' + this.colno + ']';
}
else if(this.lineno) {
message += ' [Line ' + this.lineno + ']';
}
}
message += '\n ';
if (this.firstUpdate) {
message += ' ';
}
this.message = message + (this.message || '');
this.firstUpdate = false;
return this;
};
return err;
};
exports.TemplateError.prototype = Error.prototype;
exports.escape = function(val) {
return val.replace(escapeRegex, lookupEscape);
};
exports.isFunction = function(obj) {
return ObjProto.toString.call(obj) == '[object Function]';
};
exports.isArray = Array.isArray || function(obj) {
return ObjProto.toString.call(obj) == '[object Array]';
};
exports.isString = function(obj) {
return ObjProto.toString.call(obj) == '[object String]';
};
exports.isObject = function(obj) {
return ObjProto.toString.call(obj) == '[object Object]';
};
exports.groupBy = function(obj, val) {
var result = {};
var iterator = exports.isFunction(val) ? val : function(obj) { return obj[val]; };
for(var i=0; i<obj.length; i++) {
var value = obj[i];
var key = iterator(value, i);
(result[key] || (result[key] = [])).push(value);
}
return result;
};
exports.toArray = function(obj) {
return Array.prototype.slice.call(obj);
};
exports.without = function(array) {
var result = [];
if (!array) {
return result;
}
var index = -1,
length = array.length,
contains = exports.toArray(arguments).slice(1);
while(++index < length) {
if(exports.indexOf(contains, array[index]) === -1) {
result.push(array[index]);
}
}
return result;
};
exports.extend = function(obj, obj2) {
for(var k in obj2) {
obj[k] = obj2[k];
}
return obj;
};
exports.repeat = function(char_, n) {
var str = '';
for(var i=0; i<n; i++) {
str += char_;
}
return str;
};
exports.each = function(obj, func, context) {
if(obj == null) {
return;
}
if(ArrayProto.each && obj.each == ArrayProto.each) {
obj.forEach(func, context);
}
else if(obj.length === +obj.length) {
for(var i=0, l=obj.length; i<l; i++) {
func.call(context, obj[i], i, obj);
}
}
};
exports.map = function(obj, func) {
var results = [];
if(obj == null) {
return results;
}
if(ArrayProto.map && obj.map === ArrayProto.map) {
return obj.map(func);
}
for(var i=0; i<obj.length; i++) {
results[results.length] = func(obj[i], i);
}
if(obj.length === +obj.length) {
results.length = obj.length;
}
return results;
};
exports.asyncIter = function(arr, iter, cb) {
var i = -1;
function next() {
i++;
if(i < arr.length) {
iter(arr[i], i, next, cb);
}
else {
cb();
}
}
next();
};
exports.asyncFor = function(obj, iter, cb) {
var keys = exports.keys(obj);
var len = keys.length;
var i = -1;
function next()
|
next();
};
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill
exports.indexOf = Array.prototype.indexOf ?
function (arr, searchElement, fromIndex) {
return Array.prototype.indexOf.call(arr, searchElement, fromIndex);
} :
function (arr, searchElement, fromIndex) {
var length = this.length >>> 0; // Hack to convert object.length to a UInt32
fromIndex = +fromIndex || 0;
if(Math.abs(fromIndex) === Infinity) {
fromIndex = 0;
}
if(fromIndex < 0) {
fromIndex += length;
if (fromIndex < 0) {
fromIndex = 0;
}
}
for(;fromIndex < length; fromIndex++) {
if (arr[fromIndex] === searchElement) {
return fromIndex;
}
}
return -1;
};
if(!Array.prototype.map) {
Array.prototype.map = function() {
throw new Error("map is unimplemented for this js engine");
};
}
exports.keys = function(obj) {
if(Object.prototype.keys) {
return obj.keys();
}
else {
var keys = [];
for(var k in obj) {
if(obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
}
}
|
{
i++;
var k = keys[i];
if(i < len) {
iter(k, obj[k], i, len, next);
}
else {
cb();
}
}
|
identifier_body
|
lib.js
|
var ArrayProto = Array.prototype;
var ObjProto = Object.prototype;
var escapeMap = {
'&': '&',
'"': '"',
"'": ''',
"<": '<',
">": '>'
};
var escapeRegex = /[&"'<>]/g;
var lookupEscape = function(ch) {
return escapeMap[ch];
};
var exports = module.exports = {};
exports.withPrettyErrors = function(path, withInternals, func) {
try {
return func();
} catch (e) {
if (!e.Update) {
// not one of ours, cast it
e = new exports.TemplateError(e);
}
e.Update(path);
// Unless they marked the dev flag, show them a trace from here
if (!withInternals) {
var old = e;
e = new Error(old.message);
e.name = old.name;
}
throw e;
}
};
exports.TemplateError = function(message, lineno, colno) {
var err = this;
if (message instanceof Error) { // for casting regular js errors
err = message;
message = message.name + ": " + message.message;
} else {
if(Error.captureStackTrace) {
Error.captureStackTrace(err);
}
}
err.name = 'Template render error';
err.message = message;
err.lineno = lineno;
err.colno = colno;
err.firstUpdate = true;
err.Update = function(path) {
var message = "(" + (path || "unknown path") + ")";
// only show lineno + colno next to path of template
// where error occurred
if (this.firstUpdate) {
if(this.lineno && this.colno) {
message += ' [Line ' + this.lineno + ', Column ' + this.colno + ']';
}
else if(this.lineno) {
message += ' [Line ' + this.lineno + ']';
}
}
message += '\n ';
if (this.firstUpdate) {
message += ' ';
}
this.message = message + (this.message || '');
this.firstUpdate = false;
return this;
};
return err;
};
exports.TemplateError.prototype = Error.prototype;
exports.escape = function(val) {
return val.replace(escapeRegex, lookupEscape);
};
exports.isFunction = function(obj) {
return ObjProto.toString.call(obj) == '[object Function]';
};
exports.isArray = Array.isArray || function(obj) {
return ObjProto.toString.call(obj) == '[object Array]';
};
exports.isString = function(obj) {
return ObjProto.toString.call(obj) == '[object String]';
};
exports.isObject = function(obj) {
return ObjProto.toString.call(obj) == '[object Object]';
};
exports.groupBy = function(obj, val) {
var result = {};
var iterator = exports.isFunction(val) ? val : function(obj) { return obj[val]; };
for(var i=0; i<obj.length; i++) {
var value = obj[i];
var key = iterator(value, i);
(result[key] || (result[key] = [])).push(value);
}
return result;
};
exports.toArray = function(obj) {
return Array.prototype.slice.call(obj);
};
exports.without = function(array) {
var result = [];
if (!array) {
return result;
}
var index = -1,
length = array.length,
contains = exports.toArray(arguments).slice(1);
while(++index < length) {
if(exports.indexOf(contains, array[index]) === -1) {
result.push(array[index]);
}
}
return result;
};
exports.extend = function(obj, obj2) {
for(var k in obj2) {
obj[k] = obj2[k];
}
return obj;
};
exports.repeat = function(char_, n) {
var str = '';
for(var i=0; i<n; i++) {
str += char_;
}
return str;
};
exports.each = function(obj, func, context) {
if(obj == null) {
return;
}
if(ArrayProto.each && obj.each == ArrayProto.each) {
obj.forEach(func, context);
}
else if(obj.length === +obj.length) {
for(var i=0, l=obj.length; i<l; i++) {
func.call(context, obj[i], i, obj);
}
}
};
exports.map = function(obj, func) {
var results = [];
if(obj == null) {
return results;
}
if(ArrayProto.map && obj.map === ArrayProto.map) {
return obj.map(func);
}
for(var i=0; i<obj.length; i++) {
results[results.length] = func(obj[i], i);
}
if(obj.length === +obj.length) {
results.length = obj.length;
}
return results;
};
exports.asyncIter = function(arr, iter, cb) {
var i = -1;
function next() {
i++;
if(i < arr.length) {
iter(arr[i], i, next, cb);
}
else {
cb();
}
}
next();
};
exports.asyncFor = function(obj, iter, cb) {
var keys = exports.keys(obj);
var len = keys.length;
var i = -1;
function
|
() {
i++;
var k = keys[i];
if(i < len) {
iter(k, obj[k], i, len, next);
}
else {
cb();
}
}
next();
};
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill
exports.indexOf = Array.prototype.indexOf ?
function (arr, searchElement, fromIndex) {
return Array.prototype.indexOf.call(arr, searchElement, fromIndex);
} :
function (arr, searchElement, fromIndex) {
var length = this.length >>> 0; // Hack to convert object.length to a UInt32
fromIndex = +fromIndex || 0;
if(Math.abs(fromIndex) === Infinity) {
fromIndex = 0;
}
if(fromIndex < 0) {
fromIndex += length;
if (fromIndex < 0) {
fromIndex = 0;
}
}
for(;fromIndex < length; fromIndex++) {
if (arr[fromIndex] === searchElement) {
return fromIndex;
}
}
return -1;
};
if(!Array.prototype.map) {
Array.prototype.map = function() {
throw new Error("map is unimplemented for this js engine");
};
}
exports.keys = function(obj) {
if(Object.prototype.keys) {
return obj.keys();
}
else {
var keys = [];
for(var k in obj) {
if(obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
}
}
|
next
|
identifier_name
|
lib.js
|
var ArrayProto = Array.prototype;
var ObjProto = Object.prototype;
var escapeMap = {
'&': '&',
'"': '"',
"'": ''',
"<": '<',
">": '>'
};
var escapeRegex = /[&"'<>]/g;
var lookupEscape = function(ch) {
return escapeMap[ch];
};
var exports = module.exports = {};
exports.withPrettyErrors = function(path, withInternals, func) {
try {
return func();
} catch (e) {
if (!e.Update) {
// not one of ours, cast it
e = new exports.TemplateError(e);
}
e.Update(path);
// Unless they marked the dev flag, show them a trace from here
if (!withInternals) {
var old = e;
e = new Error(old.message);
e.name = old.name;
}
throw e;
}
};
exports.TemplateError = function(message, lineno, colno) {
var err = this;
if (message instanceof Error) { // for casting regular js errors
err = message;
message = message.name + ": " + message.message;
} else {
if(Error.captureStackTrace) {
Error.captureStackTrace(err);
}
}
err.name = 'Template render error';
err.message = message;
err.lineno = lineno;
err.colno = colno;
err.firstUpdate = true;
err.Update = function(path) {
var message = "(" + (path || "unknown path") + ")";
// only show lineno + colno next to path of template
// where error occurred
if (this.firstUpdate) {
if(this.lineno && this.colno) {
message += ' [Line ' + this.lineno + ', Column ' + this.colno + ']';
}
else if(this.lineno) {
message += ' [Line ' + this.lineno + ']';
}
}
message += '\n ';
if (this.firstUpdate) {
message += ' ';
}
this.message = message + (this.message || '');
this.firstUpdate = false;
return this;
};
return err;
};
exports.TemplateError.prototype = Error.prototype;
|
exports.isFunction = function(obj) {
return ObjProto.toString.call(obj) == '[object Function]';
};
exports.isArray = Array.isArray || function(obj) {
return ObjProto.toString.call(obj) == '[object Array]';
};
exports.isString = function(obj) {
return ObjProto.toString.call(obj) == '[object String]';
};
exports.isObject = function(obj) {
return ObjProto.toString.call(obj) == '[object Object]';
};
exports.groupBy = function(obj, val) {
var result = {};
var iterator = exports.isFunction(val) ? val : function(obj) { return obj[val]; };
for(var i=0; i<obj.length; i++) {
var value = obj[i];
var key = iterator(value, i);
(result[key] || (result[key] = [])).push(value);
}
return result;
};
exports.toArray = function(obj) {
return Array.prototype.slice.call(obj);
};
exports.without = function(array) {
var result = [];
if (!array) {
return result;
}
var index = -1,
length = array.length,
contains = exports.toArray(arguments).slice(1);
while(++index < length) {
if(exports.indexOf(contains, array[index]) === -1) {
result.push(array[index]);
}
}
return result;
};
exports.extend = function(obj, obj2) {
for(var k in obj2) {
obj[k] = obj2[k];
}
return obj;
};
exports.repeat = function(char_, n) {
var str = '';
for(var i=0; i<n; i++) {
str += char_;
}
return str;
};
exports.each = function(obj, func, context) {
if(obj == null) {
return;
}
if(ArrayProto.each && obj.each == ArrayProto.each) {
obj.forEach(func, context);
}
else if(obj.length === +obj.length) {
for(var i=0, l=obj.length; i<l; i++) {
func.call(context, obj[i], i, obj);
}
}
};
exports.map = function(obj, func) {
var results = [];
if(obj == null) {
return results;
}
if(ArrayProto.map && obj.map === ArrayProto.map) {
return obj.map(func);
}
for(var i=0; i<obj.length; i++) {
results[results.length] = func(obj[i], i);
}
if(obj.length === +obj.length) {
results.length = obj.length;
}
return results;
};
exports.asyncIter = function(arr, iter, cb) {
var i = -1;
function next() {
i++;
if(i < arr.length) {
iter(arr[i], i, next, cb);
}
else {
cb();
}
}
next();
};
exports.asyncFor = function(obj, iter, cb) {
var keys = exports.keys(obj);
var len = keys.length;
var i = -1;
function next() {
i++;
var k = keys[i];
if(i < len) {
iter(k, obj[k], i, len, next);
}
else {
cb();
}
}
next();
};
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Polyfill
exports.indexOf = Array.prototype.indexOf ?
function (arr, searchElement, fromIndex) {
return Array.prototype.indexOf.call(arr, searchElement, fromIndex);
} :
function (arr, searchElement, fromIndex) {
var length = this.length >>> 0; // Hack to convert object.length to a UInt32
fromIndex = +fromIndex || 0;
if(Math.abs(fromIndex) === Infinity) {
fromIndex = 0;
}
if(fromIndex < 0) {
fromIndex += length;
if (fromIndex < 0) {
fromIndex = 0;
}
}
for(;fromIndex < length; fromIndex++) {
if (arr[fromIndex] === searchElement) {
return fromIndex;
}
}
return -1;
};
if(!Array.prototype.map) {
Array.prototype.map = function() {
throw new Error("map is unimplemented for this js engine");
};
}
exports.keys = function(obj) {
if(Object.prototype.keys) {
return obj.keys();
}
else {
var keys = [];
for(var k in obj) {
if(obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
}
}
|
exports.escape = function(val) {
return val.replace(escapeRegex, lookupEscape);
};
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.